Skip to content

Truly independent web browser

LibWeb: Give the style engine its own projection of the DOM

Andreas Kling92fbc4120836
diff --git a/Libraries/LibWeb/CSS/StyleEngineInput.cpp b/Libraries/LibWeb/CSS/StyleEngineInput.cpp
index b9d5faf3155..37b84903d1a 100644
--- a/Libraries/LibWeb/CSS/StyleEngineInput.cpp
+++ b/Libraries/LibWeb/CSS/StyleEngineInput.cpp
@@ -8,6 +8,7 @@
#include <AK/QuickSort.h>
#include <AK/SetUnion.h>
#include <AK/TemporaryChange.h>
+#include <LibGC/RootHashTable.h>
#include <LibWeb/Animations/KeyframeEffect.h>
#include <LibWeb/CSS/CSSAnimation.h>
#include <LibWeb/CSS/CSSPropertyRule.h>
@@ -15,6 +16,7 @@
#include <LibWeb/CSS/CSSTransition.h>
#include <LibWeb/CSS/ElementBoxKind.h>
#include <LibWeb/CSS/Invalidation/LanguageInvalidator.h>
+#include <LibWeb/CSS/Invalidation/PseudoClassInvalidator.h>
#include <LibWeb/CSS/Selector.h>
#include <LibWeb/CSS/SelectorMatching.h>
#include <LibWeb/CSS/Sizing.h>
@@ -39,6 +41,7 @@
#include <LibWeb/HTML/HTMLInputElement.h>
#include <LibWeb/HTML/HTMLLinkElement.h>
#include <LibWeb/HTML/HTMLObjectElement.h>
+#include <LibWeb/HTML/HTMLSelectElement.h>
#include <LibWeb/HTML/HTMLSlotElement.h>
#include <LibWeb/HTML/HTMLTableCellElement.h>
#include <LibWeb/HTML/HTMLTableElement.h>
@@ -289,8 +292,6 @@ static void record_feature(
DOM::Element&,
StyleEngineFFI::FfiFeatureKind,
StyleAtomID name_atom,
- StyleEngineFFI::FfiFeatureValueKind old_kind,
- StyleAtomID old_atom,
StyleEngineFFI::FfiFeatureValueKind new_kind,
StyleAtomID new_atom);
@@ -318,27 +319,13 @@ static void record_element_relinked(StyleEngine& style_engine, StyleNodeID node,
});
}
-static void record_element_arrival_delta(DOM::Element& element, StyleEngine& style_engine, TreeScopeID tree_scope)
-{
- // A shadow root that took its identity before its host had one is still waiting to be linked to
- // it. A sheet adopted into a shadow tree names that root, so the root can be identified first,
- // and the link is what lets a `:host` or `::slotted()` rule in that tree reach the host instead
- // of the document.
- if (auto shadow_root = element.shadow_root(); shadow_root && shadow_root->style_node_id() != no_style_node)
- StyleEngineFFI::style_engine_set_shadow_root(style_engine.host(), element.style_node_id(), shadow_root->style_node_id());
- style_engine.record_tree_delta({
- .node = element.style_node_id().value(),
- .old_connected = false,
- .new_connected = true,
- .old_relations = detached_relations(),
- .new_relations = relations_of(element, style_engine, tree_scope),
- });
- style_engine.defer_element_initial_features(element.style_node_id());
-}
-
-void publish_pending_element_features(StyleEngine& style_engine, StyleComputer& style_computer)
+void publish_pending_element_features(StyleEngine& style_engine, StyleComputer& style_computer, Layout::BegunRead const& read)
{
auto nodes = style_engine.take_deferred_element_initial_features().values();
+ // What the engine reads decides what of the elements is withheld from it, which the host asks the engine where a
+ // rule it queued since its last job leaves it not knowing.
+ if (!nodes.is_empty())
+ StyleEngineFFI::document_host_learn_selector_requirements(style_engine.host(), &read);
// Feature postings are ordered by node identity. Publish arrivals in that order so growing
// their indexes appends members instead of repeatedly searching and splitting posting chunks.
quick_sort(nodes);
@@ -348,7 +335,7 @@ void publish_pending_element_features(StyleEngine& style_engine, StyleComputer&
continue;
// An inserted subtree takes its identities before its insertion steps mark its nodes connected, in tree order.
// A step that submits the recorded input on the way, as a <style> writing its sheet to the engine in place
- // while a style transaction flies, finds the elements after it unconnected: their arrivals are submitted, and
+ // while a style update flies, finds the elements after it unconnected: their arrivals are submitted, and
// their features wait for the next submit, which folds them onto those arrivals.
if (!element->is_connected()) {
style_engine.defer_element_initial_features(node);
@@ -367,9 +354,12 @@ void publish_pending_element_features(StyleEngine& style_engine, StyleComputer&
static void mark_style_arrival_pending(DOM::Node& node, StyleEngine& style_engine)
{
style_engine.note_pending_arrivals(1);
+ style_engine.list_arrival(node);
node.set_style_arrival_pending(true);
+ // NB: The path is marked all the way up: a take-in that finds the subtrees among the nodes listed clears only the
+ // paths to them, and may leave the mark of a subtree that left on an element below a path it cleared.
for (auto* ancestor = node.parent_or_shadow_host(); ancestor; ancestor = ancestor->parent_or_shadow_host()) {
- if (ancestor->descendant_style_arrival_pending() || ancestor->style_arrival_pending())
+ if (ancestor->style_arrival_pending())
break;
ancestor->set_descendant_style_arrival_pending(true);
}
@@ -448,6 +438,7 @@ static bool element_can_wait_to_arrive(DOM::Element& element, StyleEngine::Relat
// notes that they arrive as the input is next submitted.
static void release_waiting_children(DOM::Element& element)
{
+ element.document().style_computer().style_engine().note_unlisted_arrivals();
element.set_child_style_arrivals_wait(false);
element.set_descendant_style_arrival_pending(true);
auto mark = [](DOM::Node& child) { child.set_style_arrival_pending(true); };
@@ -630,6 +621,9 @@ static void record_subtree_arrivals(DOM::Document& document, ReadonlySpan<Pendin
node.set_style_arrival_pending(false);
node.set_descendant_style_arrival_pending(false);
if (auto* element = as_if<DOM::Element>(node); element && element->style_node_id() == no_style_node) {
+ // NB: An arrival reads its language through its parent, which may arrive after it, and whose answer an
+ // earlier read left cached from where the subtree stood.
+ element->invalidate_lang_value();
arrivals.append({ *element, tree_scope });
dom_order_arrivals.append(*element);
++element_count;
@@ -662,14 +656,22 @@ static void record_subtree_arrivals(DOM::Document& document, ReadonlySpan<Pendin
identities.resize(text_arrivals.size());
style_engine.mint_text_style_nodes(identities.span());
style_computer.ensure_style_node_slot(identities.last());
+ Vector<StyleEngineFFI::FfiArrivingText, 64> texts;
+ texts.ensure_capacity(text_arrivals.size());
for (size_t i = 0; i < text_arrivals.size(); ++i) {
- text_arrivals[i]->set_style_node_id(identities[i]);
- style_computer.register_style_node(identities[i], text_arrivals[i]);
- StyleEngineFFI::style_engine_set_text_is_ascii_whitespace(style_engine.host(), identities[i], text_arrivals[i]->data().is_ascii_whitespace());
- StyleEngineFFI::style_engine_set_text_is_in_user_agent_shadow_tree(style_engine.host(), identities[i], text_is_in_user_agent_shadow_tree(*text_arrivals[i]));
- StyleEngineFFI::style_engine_set_text_is_password_input(style_engine.host(), identities[i], text_arrivals[i]->is_password_input());
- StyleEngineFFI::style_engine_set_text_data(style_engine.host(), identities[i].value(), text_arrivals[i]->data().to_raw_leaked());
+ auto& text = *text_arrivals[i];
+ text.set_style_node_id(identities[i]);
+ style_computer.register_style_node(identities[i], text);
+ texts.unchecked_append({
+ .data = text.data().to_raw_leaked(),
+ .node = identities[i].value(),
+ .is_ascii_whitespace = text.data().is_ascii_whitespace(),
+ .is_in_user_agent_shadow_tree = text_is_in_user_agent_shadow_tree(text),
+ .is_password_input = text.is_password_input(),
+ });
}
+ // The text nodes of the subtrees take their places in the engine in one write.
+ StyleEngineFFI::style_engine_stage_text_arrivals(style_engine.host(), texts.span());
}
if (!arrivals.is_empty()) {
@@ -684,10 +686,7 @@ static void record_subtree_arrivals(DOM::Document& document, ReadonlySpan<Pendin
auto identity = identities[next_element_identity++];
element->set_style_node_id(identity);
style_computer.register_style_node(identity, *element);
- StyleEngineFFI::style_engine_set_element_unique_node_id(style_engine.host(), identity, static_cast<u64>(element->unique_id().value()));
Layout::publish_table_spans(*element);
- if (element->style_recomputes_on_environment_move())
- element->publish_style_recomputes_on_environment_move();
if (element->is_size_query_container() || element->style_depends_on_size_container_query())
element->publish_size_container_query_facts();
} else {
@@ -699,10 +698,26 @@ static void record_subtree_arrivals(DOM::Document& document, ReadonlySpan<Pendin
}
}
+ // The elements of the subtrees arrive in the engine's tree in one write, each standing in no tree before.
+ Vector<StyleEngineFFI::FfiArrivingElement, 64> arriving_elements;
+ arriving_elements.ensure_capacity(element_count);
for (auto const& arrival : arrivals) {
- if (auto* element = as_if<DOM::Element>(*arrival.node))
- record_element_arrival_delta(*element, style_engine, arrival.tree_scope);
+ auto* element = as_if<DOM::Element>(*arrival.node);
+ if (!element)
+ continue;
+ // A shadow root that took its identity before its host had one is still waiting to be linked to it. A sheet
+ // adopted into a shadow tree names that root, so the root can be identified first, and the link is what lets
+ // a `:host` or `::slotted()` rule in that tree reach the host instead of the document.
+ if (auto shadow_root = element->shadow_root(); shadow_root && shadow_root->style_node_id() != no_style_node)
+ StyleEngineFFI::style_engine_set_shadow_root(style_engine.host(), element->style_node_id(), shadow_root->style_node_id());
+ arriving_elements.unchecked_append({
+ .unique_node_id = static_cast<u64>(element->unique_id().value()),
+ .node = element->style_node_id().value(),
+ .relations = relations_of(*element, style_engine, arrival.tree_scope),
+ });
+ style_engine.defer_element_initial_features(element->style_node_id());
}
+ style_engine.record_element_arrivals(arriving_elements.span());
for (auto const& slottable : slottables_identified_earlier)
record_element_assigned_slot_changed(slottable, nullptr);
}
@@ -860,6 +875,50 @@ static bool collect_pending_style_arrival_roots(DOM::Node& node, Vector<PendingA
return waits_below;
}
+// OPTIMIZATION: The subtrees waiting to arrive, found among the nodes marked since the last take-in rather than along the
+// marks, which reach every child of each node on the path to one. Answers false, having found nothing,
+// where the marks have to be walked: a node is in a shadow tree, whose tree order the walk follows.
+static bool take_listed_arrival_roots(DOM::Document& document, GC::RootVector<GC::Ref<DOM::Node>> const& listed, GC::ConservativeVector<PendingArrivalRoot, 16>& roots, HiddenChildArrivalDecision& decision)
+{
+ GC::RootVector<GC::Ref<DOM::Node>> found;
+ GC::RootHashTable<GC::Ref<DOM::Node>> seen;
+ for (auto node : listed) {
+ if (!node->is_connected() || !node->style_arrival_pending() || &node->document() != &document || seen.set(node) != HashSetResult::InsertedNewEntry)
+ continue;
+ if (is<DOM::ShadowRoot>(node->root()))
+ return false;
+ // A node in a subtree waiting to arrive arrives with it.
+ bool in_waiting_subtree = false;
+ for (auto* ancestor = node->parent_or_shadow_host(); ancestor; ancestor = ancestor->parent_or_shadow_host()) {
+ if (ancestor->style_arrival_pending()) {
+ in_waiting_subtree = true;
+ break;
+ }
+ }
+ if (!in_waiting_subtree)
+ found.append(node);
+ }
+ quick_sort(found, [](auto const& a, auto const& b) {
+ return (a->compare_document_position(b) & DOM::Node::DOCUMENT_POSITION_FOLLOWING) != 0;
+ });
+ // The marks on the path to each subtree are cleared, and kept on the path to one whose children go on waiting.
+ GC::RootVector<GC::Ref<DOM::Node>> waiting;
+ for (auto node : found) {
+ auto children_wait = decision.children_of_arrival_can_wait(node);
+ roots.append({ node, children_wait });
+ if (children_wait)
+ waiting.append(node);
+ for (auto* ancestor = node->parent_or_shadow_host(); ancestor && ancestor->descendant_style_arrival_pending(); ancestor = ancestor->parent_or_shadow_host())
+ ancestor->set_descendant_style_arrival_pending(false);
+ }
+ for (auto node : waiting) {
+ for (auto* ancestor = node->parent_or_shadow_host(); ancestor; ancestor = ancestor->parent_or_shadow_host())
+ ancestor->set_descendant_style_arrival_pending(true);
+ }
+ document.style_computer().style_engine().set_may_have_waiting_children(!waiting.is_empty());
+ return true;
+}
+
void take_in_pending_style_arrivals(DOM::Document& document, HiddenChildArrivals hidden_child_arrivals)
{
if (s_taking_in_pending_style_arrivals)
@@ -868,8 +927,10 @@ void take_in_pending_style_arrivals(DOM::Document& document, HiddenChildArrivals
// Nodes that waited and left the tree again are counted too, and nothing is left of them to take in.
auto arrivals_were_noted = style_engine.has_pending_arrivals();
style_engine.forget_pending_arrivals();
- if (!document.descendant_style_arrival_pending())
+ if (!document.descendant_style_arrival_pending()) {
+ (void)style_engine.take_listed_arrivals();
return;
+ }
// Children that wait in a display:none subtree go on waiting until a node connects, something notes they may have
// to arrive, or the keys they were looked at against move. Until then, the marks on the path to them lead to nothing
// that has to arrive.
@@ -883,10 +944,18 @@ void take_in_pending_style_arrivals(DOM::Document& document, HiddenChildArrivals
GC::ConservativeVector<PendingArrivalRoot, 16> roots;
{
HiddenChildArrivalDecision decision { document, hidden_child_arrivals };
- style_engine.set_may_have_waiting_children(collect_pending_style_arrival_roots(document, roots, decision));
+ auto listed = style_engine.take_listed_arrivals();
+ if (!listed.has_value() || style_engine.may_have_waiting_children() || !take_listed_arrival_roots(document, *listed, roots, decision))
+ style_engine.set_may_have_waiting_children(collect_pending_style_arrival_roots(document, roots, decision));
}
- if (!roots.is_empty() && document.style_engine_tracks_tree())
+ if (!roots.is_empty() && document.style_engine_tracks_tree()) {
record_subtree_arrivals(document, roots);
+ // NB: An element shows a highlight only once it has an identity to be named by, which a hidden child can take
+ // without the tree changing.
+ document.set_needs_highlight_style_update(PseudoElement::Selection);
+ document.set_needs_highlight_style_update(PseudoElement::SearchText);
+ document.set_needs_highlight_style_update(PseudoElement::SpellingError);
+ }
}
void record_element_associated_with_animation(DOM::Element& element)
@@ -940,39 +1009,38 @@ static u8 associated_pseudo_kind_plus_one(DOM::Element const& element)
// Publish every selector-visible fact intrinsic to one element.
//
// An element arrives with facts already true of it, and the engine has heard none of them. They are
-// published as ordinary deltas from absent, so the resident fact store is built by exactly the same
-// path later mutations take rather than by a second one.
+// published as ordinary deltas from absent, so the projection learns them by exactly the same path
+// later mutations take rather than by a second one.
static void publish_element_selector_features(StyleEngine& style_engine, DOM::Element& element)
{
auto node = element.style_node_id();
- auto publish_feature = [&](StyleEngineFFI::FfiFeatureKind kind, StyleAtomID name_atom, StyleEngineFFI::FfiFeatureValueKind value_kind, StyleAtomID value_atom) {
- style_engine.record_local_feature_delta({
- .node = node.value(),
- .feature_kind = kind,
- .name_atom = name_atom.value(),
- .old_kind = StyleEngineFFI::FfiFeatureValueKind::Absent,
- .old_atom = 0,
- .new_kind = value_kind,
- .new_atom = value_atom.value(),
- });
- };
+ // Everything the element's selectors test arrives as one row, which the engine writes in one go.
// Slot identity and namespace never change during an element's lifetime.
auto is_slot = is<HTML::HTMLSlotElement>(element);
StyleAtomID namespace_atom;
if (auto const& namespace_uri = element.namespace_uri(); namespace_uri.has_value() && !namespace_uri->is_empty())
namespace_atom = style_engine.intern_atom(*namespace_uri);
- publish_feature(StyleEngineFFI::FfiFeatureKind::TagName, StyleAtomID {}, StyleEngineFFI::FfiFeatureValueKind::Atom, style_engine.intern_atom(element.local_name()));
+ auto tag_atom = style_engine.intern_atom(element.local_name());
+ auto folded_tag_atom = tag_atom;
if (auto folded_name = element.local_name().to_ascii_lowercase(); folded_name != element.local_name())
- publish_feature(StyleEngineFFI::FfiFeatureKind::FoldedTagName, StyleAtomID {}, StyleEngineFFI::FfiFeatureValueKind::Atom, style_engine.intern_atom(folded_name));
+ folded_tag_atom = style_engine.intern_atom(folded_name);
+ StyleAtomID id_atom;
if (auto const& id = element.id(); id.has_value())
- publish_feature(StyleEngineFFI::FfiFeatureKind::Id, StyleAtomID {}, StyleEngineFFI::FfiFeatureValueKind::Atom, intern_id_or_class_atom(style_engine, element, *id));
+ id_atom = intern_id_or_class_atom(style_engine, element, *id);
+ Vector<StyleAtomID, 8> classes;
for (auto const& class_name : element.class_names())
- publish_feature(StyleEngineFFI::FfiFeatureKind::Class, intern_id_or_class_atom(style_engine, element, class_name), StyleEngineFFI::FfiFeatureValueKind::Present, StyleAtomID {});
- element.for_each_attribute([&](DOM::QualifiedName const& name, Utf16String const& value) {
+ classes.append(intern_id_or_class_atom(style_engine, element, class_name));
+ Vector<StyleAtomID, 16> attributes;
+ for (auto const& [name, value] : element.attribute_list()) {
auto name_atom = style_engine.intern_attribute_name(name.local_name(), name.namespace_());
- publish_feature(StyleEngineFFI::FfiFeatureKind::Attribute, name_atom, StyleEngineFFI::FfiFeatureValueKind::Atom, style_engine.intern_attribute_value(name_atom, value));
- });
+ if (style_engine.attribute_is_known_unread(name_atom)) {
+ style_engine.note_attribute_withheld(name.local_name(), name.namespace_(), node);
+ continue;
+ }
+ attributes.append(name_atom);
+ attributes.append(style_engine.intern_attribute_value(name_atom, value));
+ }
bool has_nonempty_text_child = false;
for (GC::Ptr<DOM::Node const> child = element.first_child(); child; child = child->next_sibling()) {
@@ -981,25 +1049,21 @@ static void publish_element_selector_features(StyleEngine& style_engine, DOM::El
break;
}
}
- style_engine.record_local_feature_delta({
- .node = node.value(),
- .feature_kind = StyleEngineFFI::FfiFeatureKind::Emptiness,
- .name_atom = 0,
- .old_kind = has_nonempty_text_child ? StyleEngineFFI::FfiFeatureValueKind::Present : StyleEngineFFI::FfiFeatureValueKind::Absent,
- .old_atom = 0,
- .new_kind = has_nonempty_text_child ? StyleEngineFFI::FfiFeatureValueKind::Absent : StyleEngineFFI::FfiFeatureValueKind::Present,
- .new_atom = 0,
- });
- auto states = SelectorMatching::element_states(element);
+ auto ask_local_link = SelectorMatching::AskLocalLink::Yes;
+ if (element.matches_link_pseudo_class() && style_engine.local_link_is_known_untested()) {
+ ask_local_link = SelectorMatching::AskLocalLink::No;
+ style_engine.note_local_link_state_withheld(node);
+ }
+ auto states = SelectorMatching::element_states(element, ask_local_link);
+ u64 state_bits = 0;
for (size_t index = 0; index < to_underlying(PseudoClass::__Count); ++index) {
auto pseudo_class = static_cast<PseudoClass>(index);
// The engine's hover chain holds `:hover`, which the hover follows to an element that arrives hovered.
if (pseudo_class == PseudoClass::Hover || !states.get(pseudo_class))
continue;
- auto fact = state_fact_for(pseudo_class);
- if (fact.has_value())
- style_engine.record_state_delta({ .node = node.value(), .fact = *fact, .new_value = true });
+ if (auto fact = state_fact_for(pseudo_class); fact.has_value())
+ state_bits |= static_cast<u64>(1) << to_underlying(*fact);
}
// The tag is computed afresh and not left cached. One cached where the element used to be says nothing about where
@@ -1021,20 +1085,26 @@ static void publish_element_selector_features(StyleEngine& style_engine, DOM::El
custom_states.append(style_engine.intern_atom(state));
}
style_engine.record_element_arrival({
+ .states = state_bits,
.node = node.value(),
+ .tag_atom = tag_atom.value(),
+ .folded_tag_atom = folded_tag_atom.value(),
+ .id_atom = id_atom.value(),
.namespace_atom = namespace_atom.value(),
.language_atom = language_atom.value(),
.directionality_atom = directionality_atom.value(),
- .custom_state_offset = 0,
- .custom_state_count = 0,
+ .custom_state_count = static_cast<u32>(custom_states.size()),
+ .class_count = static_cast<u32>(classes.size()),
+ .attribute_count = static_cast<u32>(attributes.size() / 2),
.heading_level = heading_level,
.is_slot = is_slot,
+ .has_text_content = has_nonempty_text_child,
.associated_pseudo_kind_plus_one = associated_pseudo_kind_plus_one(element),
.box_kind = to_underlying(box_kind_for_layout(element)),
.adjustment_facts = element_style_adjustment_facts(element),
.construction_facts = element_construction_facts(element),
},
- custom_states);
+ custom_states, classes, attributes);
// The hover follows the element the events hover to where it arrives, the place a move took it to.
if (&element == hovered_element_of(element.document().hovered_node()))
style_engine.record_hover(node);
@@ -1137,7 +1207,7 @@ enum ElementStyleAdjustmentFact : u32 {
// tree build can read it out of the mirror rather than off the DOM node. Mirrors Rust `element_construction_fact`.
enum ElementConstructionFact : u32 {
IsHtmlInputElement = 1 << 0,
- // This and ConstructedAsDocumentElement are also ElementStyleAdjustmentFacts. A row is built out of this word
+ // This and ConstructedAsDocumentElement are also ElementStyleAdjustmentFact bits. A row is built out of this word
// alone, so they are published into both rather than read across two.
ConstructedAsHtmlHtmlElement = 1 << 1,
IsInUserAgentShadowTree = 1 << 2,
@@ -1147,6 +1217,7 @@ enum ElementConstructionFact : u32 {
ConstructedAsDocumentElement = 1 << 6,
IsSvgResourceElement = 1 << 7,
IsSvgGeometryElement = 1 << 8,
+ IsHtmlSelectElement = 1 << 9,
// The layout algorithm a MathML element's tag name selects, as a MathMLLayoutKind in these bits.
MathMLLayoutKindShift = 16,
MathMLLayoutKindMask = 0x1f << MathMLLayoutKindShift,
@@ -1338,6 +1409,7 @@ static u32 element_construction_facts(DOM::Element const& element)
set(element.is_document_element(), ElementConstructionFact::ConstructedAsDocumentElement);
set(svg_element && svg_element->is_resource_element(), ElementConstructionFact::IsSvgResourceElement);
set(element.is_svg_geometry_element(), ElementConstructionFact::IsSvgGeometryElement);
+ set(is<HTML::HTMLSelectElement>(element), ElementConstructionFact::IsHtmlSelectElement);
facts |= to_underlying(mathml_layout_kind(element)) << ElementConstructionFact::MathMLLayoutKindShift;
return facts;
}
@@ -1378,14 +1450,13 @@ void record_element_adjustment_facts(DOM::Element& element)
StyleEngineFFI::style_engine_set_element_adjustment_facts(style_engine->host(), element.style_node_id(), element_style_adjustment_facts(element));
StyleEngineFFI::style_engine_set_element_construction_facts(style_engine->host(), element.style_node_id(), element_construction_facts(element));
StyleEngineFFI::style_engine_set_element_box_kind(style_engine->host(), element.style_node_id(), to_underlying(box_kind_for_layout(element)));
- StyleEngineFFI::style_engine_set_element_associated_pseudo_kind(style_engine->host(), element.style_node_id(), associated_pseudo_kind_plus_one(element));
+ auto pseudo_kind_plus_one = associated_pseudo_kind_plus_one(element);
+ StyleEngineFFI::style_engine_set_element_backing_pseudo_kind(style_engine->host(), element.style_node_id(), pseudo_kind_plus_one);
}
void record_element_animations_changed(DOM::Element& element)
{
record_element_adjustment_facts(element);
- if (auto* style_engine = style_engine_for_identified(element))
- style_engine->note_animations_changed(element.style_node_id());
}
void record_element_box_kind(DOM::Element& element)
@@ -1511,14 +1582,59 @@ void record_element_construction_facts(DOM::Element& element)
StyleEngineFFI::style_engine_set_element_construction_facts(style_engine->host(), element.style_node_id(), element_construction_facts(element));
}
-void publish_required_attribute_value_texts(StyleEngine& style_engine, StyleComputer& style_computer)
+void publish_withheld_element_features(StyleEngine& style_engine, StyleComputer& style_computer, Layout::BegunRead const& read)
{
- style_computer.for_each_style_node([&](DOM::Element& element) {
- element.for_each_attribute([&](DOM::QualifiedName const& name, Utf16String const& value) {
+ auto now_read = style_engine.take_withheld_features_now_read(read);
+ if (now_read.local_link_states.is_empty() && now_read.attributes.is_empty())
+ return;
+ auto element_holding = [&](StyleNodeID node) -> GC::Ptr<DOM::Element> {
+ auto element = style_computer.element_for_style_node(node);
+ if (!element || !element->is_connected() || element->style_node_id() != node)
+ return nullptr;
+ return element;
+ };
+ auto local_link = state_fact_for(PseudoClass::LocalLink);
+ VERIFY(local_link.has_value());
+ for (auto node : now_read.local_link_states) {
+ if (auto element = element_holding(node); element && element->matches_local_link_pseudo_class())
+ style_engine.record_state_delta({ .node = node.value(), .fact = *local_link, .new_value = true });
+ }
+ // Each element is asked once about every name now read that was withheld from it.
+ HashMap<StyleNodeID, Vector<StyleEngine::WithheldAttributeName, 2>> names_by_carrier;
+ for (auto const& [name, carriers] : now_read.attributes) {
+ for (auto node : carriers)
+ names_by_carrier.ensure(node).append(name);
+ }
+ for (auto const& [node, names] : names_by_carrier) {
+ auto element = element_holding(node);
+ if (!element)
+ continue;
+ Vector<StyleEngine::WithheldAttributeName, 2> names_gone = names;
+ element->for_each_attribute([&](DOM::QualifiedName const& name, Utf16String const& value) {
+ StyleEngine::WithheldAttributeName withheld { name.local_name(), name.namespace_() };
+ if (!names.contains_slow(withheld))
+ return;
+ names_gone.remove_all_matching([&](auto const& gone) { return gone == withheld; });
auto name_atom = style_engine.intern_attribute_name(name.local_name(), name.namespace_());
- style_engine.backfill_attribute_value_text_if_required(name_atom, value);
+ style_engine.record_local_feature_delta({
+ .node = node.value(),
+ .feature_kind = StyleEngineFFI::FfiFeatureKind::Attribute,
+ .name_atom = name_atom.value(),
+ .new_kind = StyleEngineFFI::FfiFeatureValueKind::Atom,
+ .new_atom = style_engine.intern_attribute_value(name_atom, value).value(),
+ });
});
- });
+ // NB: The row may hold a value published before the name was known to be unread, of an attribute removed since.
+ for (auto const& name : names_gone) {
+ style_engine.record_local_feature_delta({
+ .node = node.value(),
+ .feature_kind = StyleEngineFFI::FfiFeatureKind::Attribute,
+ .name_atom = style_engine.intern_attribute_name(name.local_name, name.namespace_uri).value(),
+ .new_kind = StyleEngineFFI::FfiFeatureValueKind::Absent,
+ .new_atom = 0,
+ });
+ }
+ }
}
// The atom an id or class name is published under. A quirks-mode document matches those selectors
@@ -1562,7 +1678,7 @@ void record_node_moved_in_dom_order(DOM::Node& node, DOM::Node const& old_parent
link_in_dom_order(*style_engine, node);
}
-void record_element_moved(DOM::Element& element, DOM::Node* old_parent, DOM::Element* old_previous_sibling, DOM::Element* old_next_sibling)
+void record_element_moved(DOM::Element& element, DOM::Node* old_parent, DOM::Element* old_previous_sibling, DOM::Element* old_next_sibling, DOM::Element* old_assigned_slot)
{
auto* style_engine = style_engine_for_identified(element);
if (!style_engine)
@@ -1580,13 +1696,15 @@ void record_element_moved(DOM::Element& element, DOM::Node* old_parent, DOM::Ele
previous.parent = old_shadow_root->style_node_id().value();
previous.previous_element_sibling = identity_of_arrived_previous_sibling(old_previous_sibling).value();
previous.next_element_sibling = identity_of_arrived_next_sibling(old_next_sibling).value();
+ previous.assigned_slot = identity_of(old_assigned_slot).value();
+ if (old_parent)
+ previous.tree_scope = tree_scope_of(old_parent->root()).value();
if (previous.parent == relations.parent
&& previous.previous_element_sibling == relations.previous_element_sibling
- && previous.next_element_sibling == relations.next_element_sibling) {
+ && previous.next_element_sibling == relations.next_element_sibling
+ && previous.assigned_slot == relations.assigned_slot) {
return;
}
- // A style transaction that flew styled the element where it was, and what inherits from it under where it was.
- style_engine->note_style_node_arrived_or_retired(element.style_node_id());
// A heading's level counts the heading offset its ancestors declare, so moving under a
// different ancestor can change it without the element itself changing at all.
@@ -1616,6 +1734,26 @@ void record_element_moved(DOM::Element& element, DOM::Node* old_parent, DOM::Ele
// matches exactly the same rules. Recomputing its style lets ordinary inherited-style
// propagation carry any change through its light and shadow subtrees.
style_engine->record_derived_element_style_input_change(element.style_node_id(), StyleEngine::RecomputeStyle);
+
+ // The tree the element's light descendants stand in moved with it, which they answer for themselves. Their own
+ // shadow trees are scopes of their own.
+ if (previous.tree_scope != relations.tree_scope) {
+ element.for_each_in_subtree_of_type<DOM::Element>([&](DOM::Element& descendant) {
+ if (descendant.style_node_id() == no_style_node)
+ return TraversalDecision::Continue;
+ auto descendant_relations = relations_of(descendant, *style_engine, TreeScopeID { relations.tree_scope });
+ auto descendant_previous = descendant_relations;
+ descendant_previous.tree_scope = previous.tree_scope;
+ record_element_relinked(*style_engine, descendant.style_node_id(), descendant_previous, descendant_relations);
+ return TraversalDecision::Continue;
+ });
+ // The hosts it and those below it are exposed to as parts are those of the tree it stands in now.
+ element.for_each_shadow_including_inclusive_descendant([](DOM::Node& node) {
+ if (auto* moved = as_if<DOM::Element>(node))
+ record_element_parts_changed(*moved);
+ return TraversalDecision::Continue;
+ });
+ }
}
// The relinking path rather than the neighbour one. A move rewrites the DOM's own links without
@@ -1624,15 +1762,6 @@ void record_element_moved(DOM::Element& element, DOM::Node* old_parent, DOM::Ele
// them. Publishing this as a neighbour change leaves the columns holding the order the element
// left, which is the order every positional question is then answered in.
record_element_relinked(*style_engine, element.style_node_id(), previous, relations);
-
- // A move across parents is a departure from one child list and an arrival in another, so both
- // parents' emptiness can have moved even though no node was created or destroyed.
- if (old_parent != element.parent()) {
- if (auto* old_parent_element = as_if<DOM::Element>(old_parent))
- record_element_emptiness_changed(*old_parent_element, element, true, false);
- if (auto* new_parent = as_if<DOM::Element>(element.parent()))
- record_element_emptiness_changed(*new_parent, element, false, true);
- }
}
void record_element_assigned_slot_changed(DOM::Element& element, DOM::Element* old_slot)
@@ -1640,6 +1769,11 @@ void record_element_assigned_slot_changed(DOM::Element& element, DOM::Element* o
auto* style_engine = style_engine_for_identified(element);
if (!style_engine)
return;
+ // An element without a parent is between the removal and insertion steps of a move, or has
+ // left. The move or the departure publishes its relations: relinking it here would report it
+ // as having had no parent before, which a transaction keeps as where the element came from.
+ if (!element.parent())
+ return;
auto relations = relations_of(element, *style_engine);
auto previous = relations;
@@ -1650,9 +1784,6 @@ void record_element_assigned_slot_changed(DOM::Element& element, DOM::Element* o
// The engine holds the slot a slottable is assigned to, and only relinking updates it. Every other relation is
// identical on both sides, so unlinking and linking again leaves them where they were.
record_element_relinked(*style_engine, element.style_node_id(), previous, relations);
- // A style transaction already running on the StyleLayout thread styled the element under its previous slot,
- // as for a move.
- style_engine->note_style_node_arrived_or_retired(element.style_node_id());
}
void record_slot_assignment_changed(HTML::HTMLSlotElement& slot)
@@ -1672,6 +1803,7 @@ void record_slot_assignment_changed(HTML::HTMLSlotElement& slot)
identities.unchecked_append(identity);
}
StyleEngineFFI::style_engine_set_slot_assigned_nodes(slot.document().style_computer().style_engine().host(), slot.style_node_id(), identities.span());
+ Invalidation::invalidate_style_after_slot_assignment_changed(slot);
}
// Only a connected element in a fully active document enters the top layer. A member still waiting to arrive has no
@@ -1759,24 +1891,6 @@ static void record_element_disconnecting(DOM::Element& element, TreeScopeID tree
element.set_style_node_id(no_style_node);
}
-// The animation names an element's computed style references.
-//
-// Not an input: the element was recomputed by whatever moved its `animation-name`. This is the index
-// that lets a `@keyframes` rule find the elements running the animation it describes, which nothing
-// about selector matching can say.
-void record_element_animation_names(DOM::Element& element, ReadonlySpan<Utf16FlyString> names)
-{
- auto* style_engine = style_engine_for_identified(element);
- if (!style_engine)
- return;
-
- Vector<StyleAtomID> atoms;
- atoms.ensure_capacity(names.size());
- for (auto const& name : names)
- atoms.unchecked_append(style_engine->intern_atom(name));
- StyleEngineFFI::style_engine_set_element_animation_names(style_engine->host(), element.style_node_id(), atoms);
-}
-
// The names of the CSS animations the element owns, in one of its per-pseudo-element lists, and the
// definition each one last had applied.
//
@@ -1846,6 +1960,27 @@ static void describe_easing(EasingFunction const& easing, StyleEngineFFI::FfiPub
//
// Everything a keyframe declares that does not depend on the element being sampled is settled here. What
// does, a value or an easing still to be substituted against the element, travels as written.
+void record_attr_names_read_by_keyframes(DOM::Element& element, Animations::KeyframeEffect const& effect)
+{
+ auto* style_engine = style_engine_for(element);
+ if (!style_engine || !effect.key_frame_set())
+ return;
+ bool reads_more_attributes = false;
+ for (auto const& keyframe : effect.key_frame_set()->keyframes_by_key) {
+ for (auto const& [property, value] : keyframe.properties) {
+ if (auto const* handle = value.get_pointer<RustStyleValueHandle>())
+ reads_more_attributes |= StyleEngineFFI::style_engine_note_attr_names_read_by_value(style_engine->host(), handle->data());
+ }
+ if (auto const* easing = keyframe.easing.get_pointer<RustStyleValueHandle>())
+ reads_more_attributes |= StyleEngineFFI::style_engine_note_attr_names_read_by_value(style_engine->host(), easing->data());
+ }
+ // NB: An effect is sampled against what the engine holds as a read begins, so the attributes go over
+ // now. Only a script's keyframes get here with a new name, between reads: the keyframes of a CSS
+ // animation were noted as their rule was published.
+ if (reads_more_attributes)
+ style_engine->flush();
+}
+
void record_element_animation_effect_descriptions(DOM::Element& element, u8 slot, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>> effects)
{
auto* style_engine = style_engine_for_identified(element);
@@ -1951,57 +2086,6 @@ void record_element_animation_effect_descriptions(DOM::Element& element, u8 slot
base_url_bytes.data(), base_url_bytes.size());
}
-// The custom properties an element declares or references.
-//
-// Also an index rather than an input, and for the same reason as the animation names: what it answers
-// is which elements an `@property` registration reaches, and nothing about selector matching or the
-// element's own recomputation can say that.
-void record_element_custom_property_names(DOM::Element& element, CustomPropertyData const* data, ReadonlySpan<RefPtr<CustomPropertyData const>> pseudo_element_data, ReadonlySpan<Utf16FlyString> references, bool uses_unnamed, bool uses_custom_functions)
-{
- auto* style_engine = style_engine_for_identified(element);
- if (!style_engine)
- return;
-
- // OPTIMIZATION: Each environment hands out its declared names sorted and deduplicated, so they are merged
- // rather than sorted once more for every element that holds that environment.
- ReadonlySpan<StyleAtomID> published;
- Vector<StyleAtomID> atoms;
- Vector<StyleAtomID> merged;
- auto merge_names = [&](ReadonlySpan<StyleAtomID> names) {
- if (names.is_empty())
- return;
- if (published.is_empty()) {
- published = names;
- return;
- }
- merged.clear_with_capacity();
- merged.ensure_capacity(published.size() + names.size());
- set_union(published, names, merged);
- swap(atoms, merged);
- published = atoms;
- };
- Vector<CustomPropertyData const*, 4> merged_environments;
- auto merge_declared_names = [&](CustomPropertyData const* custom_property_data) {
- if (!custom_property_data || merged_environments.contains_slow(custom_property_data))
- return;
- merged_environments.append(custom_property_data);
- merge_names(custom_property_data->declared_name_atoms(bit_cast<FlatPtr>(&element.document()), style_engine->atom_generation(), [&](Utf16FlyString const& name) { return style_engine->intern_atom(name); }));
- };
- merge_declared_names(data);
- for (auto const& pseudo_data : pseudo_element_data)
- merge_declared_names(pseudo_data.ptr());
- // The references arrive deduplicated, and interning is injective, so their atoms only need sorting.
- Vector<StyleAtomID> reference_atoms;
- if (!references.is_empty()) {
- reference_atoms.ensure_capacity(references.size());
- for (auto const& name : references)
- reference_atoms.unchecked_append(style_engine->intern_atom(name));
- quick_sort(reference_atoms);
- merge_names(reference_atoms);
- }
- StyleEngineFFI::style_engine_set_element_custom_property_names(style_engine->host(), element.style_node_id(), published, uses_unnamed, uses_custom_functions);
-}
-
// An element's heading level, which `:heading()` tests. It follows from what the element is plus
// the heading offset its ancestors declare, so it moves when the element does and when one of those
// attributes changes - not with anything the element itself publishes.
@@ -2147,18 +2231,24 @@ void record_element_emptiness_changed(DOM::Element& element, DOM::Node const& ch
if (!style_engine)
return;
- // Whether the element is empty either side of the change is decided by the child that moved
- // together with the ones that did not, and the ones that did not are the same both times.
- auto empty_but_for_the_changing_child = SelectorMatching::element_is_empty_ignoring_child(element, changing_child);
- auto was_empty = empty_but_for_the_changing_child && !counted_before;
- auto is_empty = empty_but_for_the_changing_child && !counts_after;
+ // The engine reads an element's element children from its tree, so what it holds here is whether the element has
+ // text: an element child that comes or goes beside the text leaves it as it is.
+ auto has_other_text = false;
+ for (GC::Ptr<DOM::Node const> child = element.first_child(); child; child = child->next_sibling()) {
+ if (GC::Ptr<DOM::Text const> text = as_if<DOM::Text>(*child); text && child.ptr() != &changing_child && !text->data().is_empty()) {
+ has_other_text = true;
+ break;
+ }
+ }
+ auto was_empty = !has_other_text && !counted_before;
+ auto is_empty = !has_other_text && !counts_after;
if (was_empty == is_empty)
return;
auto kind_of = [](bool empty) {
return empty ? StyleEngineFFI::FfiFeatureValueKind::Present : StyleEngineFFI::FfiFeatureValueKind::Absent;
};
- record_feature(element, StyleEngineFFI::FfiFeatureKind::Emptiness, 0, kind_of(was_empty), 0, kind_of(is_empty), 0);
+ record_feature(element, StyleEngineFFI::FfiFeatureKind::Emptiness, 0, kind_of(is_empty), 0);
}
// An element can arrive with a style attribute already written, so this is published on arrival as
@@ -2403,6 +2493,22 @@ static void compile_rules_into(RuleCompilationContext const& context, StyleSheet
publish_layer_order_for_sheet(sheet, *context.document);
}
+// Has the process keep the rules of `sheet`, a user agent sheet, where it does not yet. No document records them: a
+// user agent sheet has no import, no scope and no owning style scope, and declares no transition.
+void publish_user_agent_sheet(StyleSheetState const& sheet, DOM::Document const& document)
+{
+ MediaEnvironmentSnapshot environment { document };
+ Parser::ValueParserFFI::NativeCompilationCallbacks callbacks {
+ .context = nullptr,
+ .import_source = [](void const*, u64, Parser::ValueParserFFI::NativeStyleSheet const*) -> void const* { VERIFY_NOT_REACHED(); },
+ .implicit_scope_root = [](void const*) -> u32 { VERIFY_NOT_REACHED(); },
+ .visit_rule = [](void const*, void const*, u64, RustRule::Type, Parser::ValueParserFFI::NativeCompilationContext const*, Parser::ValueParserFFI::NativeCompilationResult result) {
+ VERIFY(!result.declares_transitions);
+ return true; },
+ };
+ Parser::ValueParserFFI::rust_user_agent_style_sheet_publish(sheet.native_sheet().handle(), &sheet, environment.ffi_environment(), &callbacks);
+}
+
// The sheet a rule's compiled rules belong to. An imported sheet's rules cascade in the importing
// sheet's program, so the handle to compile into is the outermost sheet's. A constructed sheet is
// always its own engine sheet: its ids are held per adopting document, so its raw id member being 0
@@ -2471,8 +2577,10 @@ static bool sheet_can_share_compiled_style_sheet(StyleSheetState const& sheet)
return false;
if (!sheet.title().is_empty() || !sheet.native_rules().shared_contents_identity())
return false;
+ // NB: A link loads a sheet of its own, but the parse cache answers the same text with the same contents, as it
+ // does for style elements: components commonly link each shadow tree to one sheet.
auto const* owner_node = sheet.owner_node();
- if (!owner_node || !(owner_node->is_html_style_element() || owner_node->is_svg_style_element()))
+ if (!owner_node || !(owner_node->is_html_style_element() || owner_node->is_svg_style_element() || owner_node->is_html_link_element()))
return false;
return !sheet.native_rules().has_implicit_scope();
}
@@ -2490,17 +2598,13 @@ static RefPtr<SharedCompiledStyleSheet> shared_compiled_style_sheet_for(StyleShe
// Keep a separate program when another occurrence already occupies this scope.
if ((*existing)->is_attached_to(tree_scope) && sheet.native_rules().has_anonymous_layer())
return nullptr;
- if (!(*existing)->has_attachments()) {
+ if (!(*existing)->has_attachments())
style_computer.detached_shared_compiled_style_sheets().remove_first_matching([&](auto const& detached) { return detached == key; });
- StyleEngineFFI::style_engine_set_sheet_kept_for_reattachment(style_engine.host(), (*existing)->sheet_id(), false);
- }
return *existing;
}
auto contents = StyleSheetState::create(sheet.native_rules().clone_shared_contents(), &document, RustMediaList {}, {});
contents->set_base_url(sheet.style_resource_base_url().value_or(document.base_url()));
- auto sheet_id = style_engine.add_sheet(
- static_cast<u32>(reinterpret_cast<FlatPtr>(contents.ptr()) >> 3),
- StyleEngineFFI::FfiCascadeOrigin::Author);
+ auto sheet_id = style_engine.add_sheet(StyleEngineFFI::FfiCascadeOrigin::Author);
contents->set_style_engine_sheet_id(sheet_id);
RuleCompilationContext context { style_engine, sheet_id, 0, document, style_computer };
compile_rules_into(context, *contents);
@@ -2516,7 +2620,6 @@ static void release_shared_compiled_style_sheet(SharedCompiledStyleSheetKey cons
auto& shared_compiled_style_sheets = style_computer.shared_compiled_style_sheets();
auto sheet_id = shared_compiled_style_sheets.get(key).value()->sheet_id();
auto& style_engine = style_computer.style_engine();
- StyleEngineFFI::style_engine_set_sheet_kept_for_reattachment(style_engine.host(), sheet_id, false);
StyleEngineFFI::style_engine_begin_sheet_rules_replacement(style_engine.host(), sheet_id.value());
style_engine.finish_sheet_rules_replacement(sheet_id);
shared_compiled_style_sheets.remove(key);
@@ -2537,7 +2640,6 @@ static void detach_shared_compiled_style_sheet(SharedCompiledStyleSheet& sheet,
// and since it holds the parsed contents, the parse cache answers the arriving text without parsing it again.
auto& detached = style_computer.detached_shared_compiled_style_sheets();
detached.append(sheet.key());
- StyleEngineFFI::style_engine_set_sheet_kept_for_reattachment(style_engine.host(), sheet.sheet_id(), true);
if (detached.size() > StyleComputer::max_detached_shared_compiled_style_sheets)
release_shared_compiled_style_sheet(detached.take_first(), style_computer);
}
@@ -2752,11 +2854,7 @@ void record_stylesheet_attached(StyleSheetState& sheet, DOM::Node& document_or_s
sheet_id = shared_compiled_style_sheet->sheet_id();
sheet.set_shared_compiled_style_sheet(move(shared_compiled_style_sheet));
} else {
- // The CSSOM object's identity is what the program keys its wrapper by; the semantic sheet
- // is a separate identity that survives edits to its contents.
- sheet_id = style_engine.add_sheet(
- static_cast<u32>(reinterpret_cast<FlatPtr>(&sheet) >> 3),
- StyleEngineFFI::FfiCascadeOrigin::Author);
+ sheet_id = style_engine.add_sheet(StyleEngineFFI::FfiCascadeOrigin::Author);
}
style_computer.set_style_engine_sheet_id_for(sheet, sheet_id);
}
@@ -2804,6 +2902,12 @@ void record_stylesheet_attached(StyleSheetState& sheet, DOM::Node& document_or_s
return;
RuleCompilationContext context { style_engine, sheet_id, 0, document_or_shadow_root.document(), style_computer };
compile_rules_into(context, sheet);
+
+ // OPTIMIZATION: Until a document's first style update, the render owner has nothing else to do for it, so it takes
+ // each sheet's rules in as the sheet arrives, beside the parser, rather than the first style update
+ // waiting while it takes in every sheet the document parsed.
+ if (auto& document = document_or_shadow_root.document(); document.navigable() && !document.has_completed_style_update())
+ StyleEngineFFI::style_engine_stream_rule_writes(style_engine.host());
}
// The user-agent and user origins have no style sheet list to attach from, so nothing announces
@@ -2817,11 +2921,42 @@ void record_stylesheet_attached(StyleSheetState& sheet, DOM::Node& document_or_s
// sheets they name. The user sheet is rebuilt rather than edited when content blockers change, so
// the set is compared by identity. A set that keeps the order of the sheets it had attaches only the
// sheets new to it; any other difference re-attaches the set whole.
+// The key the document's user-agent and user sheets are collected under: its mode, whether it holds MathML or SVG, its
+// kind, and its user sheet, which is rebuilt rather than edited. The sheets the key names are shared, or held by the
+// recorded set, so an equal key names the sheets that were recorded.
+static StyleComputer::NonAuthorStyleSheetsKey non_author_style_sheets_key(DOM::Document& document)
+{
+ auto& style_scope = document.style_scope();
+ style_scope.build_user_style_sheet_if_needed();
+ return {
+ .in_quirks_mode = document.in_quirks_mode(),
+ .needs_mathml_and_svg_user_agent_style_sheets = document.needs_mathml_and_svg_user_agent_style_sheets(),
+ .is_html_document = document.document_type() == DOM::Document::Type::HTML,
+ .user_style_sheet = style_scope.m_user_style_sheet.ptr(),
+ };
+}
+
+// Whether the user-agent and user sheets the document's scope holds are the ones recorded with the style engine, in
+// order.
+bool non_author_stylesheets_are_recorded(DOM::Document const& document)
+{
+ auto& mutable_document = const_cast<DOM::Document&>(document);
+ return mutable_document.style_computer().non_author_style_sheets_key() == non_author_style_sheets_key(mutable_document);
+}
+
void record_non_author_stylesheets(DOM::Document& document)
{
auto& style_computer = document.style_computer();
auto& style_scope = document.style_scope();
+ // OPTIMIZATION: The sheets follow from the key, so an unchanged key leaves nothing to collect or compare.
+ auto key = non_author_style_sheets_key(document);
+ if (style_computer.non_author_style_sheets_key() == key)
+ return;
+ ScopeGuard record_key = [&] {
+ style_computer.non_author_style_sheets_key() = key;
+ };
+
publish_document_kind(document);
Vector<NonnullRefPtr<StyleSheetState>> sheets;
@@ -2864,18 +2999,28 @@ void record_non_author_stylesheets(DOM::Document& document)
}
auto attach_sheet = [&](size_t index, SheetID successor) {
- auto sheet_id = style_engine.add_sheet(
- static_cast<u32>(reinterpret_cast<FlatPtr>(sheets[index].ptr()) >> 3),
- origins[index]);
+ // A user agent sheet's rules are the process's: the first document needing the sheet has them compiled, and
+ // each document only notes what its media leave out of them.
+ if (origins[index] == StyleEngineFFI::FfiCascadeOrigin::UserAgent) {
+ publish_user_agent_sheet(*sheets[index], document);
+ SheetID sheet_id { StyleEngineFFI::style_engine_add_user_agent_sheet(style_engine.host(), sheets[index]->native_sheet().identity()) };
+ StyleEngineFFI::style_engine_attach_sheet(style_engine.host(), sheet_id, document_tree_scope, successor);
+ style_computer.register_style_engine_sheet_source(*sheets[index]);
+ MediaEnvironmentSnapshot environment { document };
+ Parser::ValueParserFFI::rust_style_sheet_publish_failing_conditions(sheets[index]->native_sheet().handle(), style_engine.host(), environment.ffi_environment());
+ return StyleComputer::NonAuthorStyleSheet { sheets[index], sheet_id };
+ }
+ auto sheet_id = style_engine.add_sheet(origins[index]);
StyleEngineFFI::style_engine_attach_sheet(style_engine.host(), sheet_id, document_tree_scope, successor);
RuleCompilationContext context { style_engine, sheet_id, 0, document, style_computer };
compile_rules_into(context, *sheets[index]);
return StyleComputer::NonAuthorStyleSheet { sheets[index], sheet_id };
};
- // OPTIMIZATION: A document takes in the MathML and SVG user-agent sheets once it first holds such an element. The
- // sheets recorded before keep their places among them, so only the new ones are attached, each before
- // the sheet that follows it, rather than detaching every sheet and routing all of their rules again.
+ // OPTIMIZATION: A document takes in the MathML and SVG user-agent sheets once it first holds such an element, and
+ // a new user sheet replaces the old one. The sheets recorded before that stay keep their places
+ // among them, so only the sheets that left are detached and the new ones attached, each before the
+ // sheet that follows it, rather than detaching every sheet and routing all of their rules again.
auto recorded_index_of = [&](StyleSheetState const& sheet) -> Optional<size_t> {
for (size_t index = 0; index < recorded.size(); ++index) {
if (recorded[index].sheet.ptr() == &sheet)
@@ -2884,18 +3029,25 @@ void record_non_author_stylesheets(DOM::Document& document)
return {};
};
auto recorded_sheets_keep_their_order = [&] {
- size_t found = 0;
+ Optional<size_t> previous;
for (auto const& sheet : sheets) {
auto index = recorded_index_of(*sheet);
if (!index.has_value())
continue;
- if (*index != found)
+ if (previous.has_value() && *index < *previous)
return false;
- ++found;
+ previous = index;
}
- return found == recorded.size();
+ return true;
};
if (recorded_sheets_keep_their_order()) {
+ for (auto const& entry : recorded) {
+ auto stays = false;
+ for (auto const& sheet : sheets)
+ stays |= sheet.ptr() == entry.sheet.ptr();
+ if (!stays)
+ StyleEngineFFI::style_engine_detach_sheet(style_engine.host(), entry.sheet_id, document_tree_scope);
+ }
Vector<StyleComputer::NonAuthorStyleSheet> updated;
for (size_t index = 0; index < sheets.size(); ++index) {
if (auto recorded_index = recorded_index_of(*sheets[index]); recorded_index.has_value()) {
@@ -3038,8 +3190,6 @@ static void record_feature(
DOM::Element& element,
StyleEngineFFI::FfiFeatureKind kind,
StyleAtomID name_atom,
- StyleEngineFFI::FfiFeatureValueKind old_kind,
- StyleAtomID old_atom,
StyleEngineFFI::FfiFeatureValueKind new_kind,
StyleAtomID new_atom)
{
@@ -3052,14 +3202,12 @@ static void record_feature(
.node = element.style_node_id().value(),
.feature_kind = kind,
.name_atom = name_atom.value(),
- .old_kind = old_kind,
- .old_atom = old_atom.value(),
.new_kind = new_kind,
.new_atom = new_atom.value(),
});
}
-void record_element_id_changed(DOM::Element& element, Optional<Utf16FlyString> const& old_value, Optional<Utf16FlyString> const& new_value)
+void record_element_id_changed(DOM::Element& element, Optional<Utf16FlyString> const& new_value)
{
auto* style_engine = style_engine_for_identified(element);
if (!style_engine) {
@@ -3075,7 +3223,7 @@ void record_element_id_changed(DOM::Element& element, Optional<Utf16FlyString> c
return value.has_value() ? StyleEngineFFI::FfiFeatureValueKind::Atom : StyleEngineFFI::FfiFeatureValueKind::Absent;
};
- record_feature(element, StyleEngineFFI::FfiFeatureKind::Id, 0, kind_of(old_value), atom_of(old_value), kind_of(new_value), atom_of(new_value));
+ record_feature(element, StyleEngineFFI::FfiFeatureKind::Id, 0, kind_of(new_value), atom_of(new_value));
// `getElementById` is case-sensitive in every mode, so the name the inverse index is keyed by
// is the one written rather than the one a quirks-mode selector folds it to.
@@ -3096,11 +3244,21 @@ void record_element_class_list_changed(DOM::Element& element, ReadonlySpan<Utf16
// exists to avoid.
// Two class names that differ only in case are one class where the document folds them, so
// membership is decided between the folded names rather than the written ones.
- auto folded = [&](Utf16FlyString const& name) {
- return element.document().in_quirks_mode() ? name.to_ascii_lowercase() : name;
- };
- auto contains_folded = [&](ReadonlySpan<Utf16FlyString> names, Utf16FlyString const& folded_name) {
- return any_of(names, [&](auto const& name) { return folded(name) == folded_name; });
+ Vector<Utf16FlyString> folded_old_classes;
+ Vector<Utf16FlyString> folded_new_classes;
+ if (element.document().in_quirks_mode()) {
+ auto fold = [](ReadonlySpan<Utf16FlyString> names, Vector<Utf16FlyString>& folded_names) {
+ folded_names.ensure_capacity(names.size());
+ for (auto const& name : names)
+ folded_names.unchecked_append(name.to_ascii_lowercase());
+ };
+ fold(old_classes, folded_old_classes);
+ fold(new_classes, folded_new_classes);
+ old_classes = folded_old_classes;
+ new_classes = folded_new_classes;
+ }
+ auto contains = [](ReadonlySpan<Utf16FlyString> names, Utf16FlyString const& name) {
+ return any_of(names, [&](auto const& other) { return other == name; });
};
auto record_membership = [&](Utf16FlyString const& folded_name, bool was_present, bool is_present) {
@@ -3111,17 +3269,15 @@ void record_element_class_list_changed(DOM::Element& element, ReadonlySpan<Utf16
element,
StyleEngineFFI::FfiFeatureKind::Class,
atom,
- was_present ? StyleEngineFFI::FfiFeatureValueKind::Present : StyleEngineFFI::FfiFeatureValueKind::Absent,
- 0,
is_present ? StyleEngineFFI::FfiFeatureValueKind::Present : StyleEngineFFI::FfiFeatureValueKind::Absent,
0);
};
for (auto const& name : old_classes)
- record_membership(folded(name), true, contains_folded(new_classes, folded(name)));
+ record_membership(name, true, contains(new_classes, name));
for (auto const& name : new_classes) {
- if (!contains_folded(old_classes, folded(name)))
- record_membership(folded(name), false, true);
+ if (!contains(old_classes, name))
+ record_membership(name, false, true);
}
}
@@ -3159,32 +3315,45 @@ void record_element_attribute_changed(DOM::Element& element, Utf16FlyString cons
});
}
- // Both values cross as atoms. Their text is recorded once per distinct value only when a
+ // The new value crosses as an atom. Its text is recorded once per distinct value only when a
// compiled selector for this attribute uses an operator that cannot compare atom identities,
- // or when an attr() can read the name. This lets the match evaluator reconstruct either side
- // of such a transaction without asking the DOM, and two different values cannot cancel in the
- // journal merely because both are present.
+ // or when an attr() can read the name, so the match evaluator reads it without asking the DOM.
// The same name an arriving attribute publishes, with the same other forms noted alongside it.
// See `StyleEngine::intern_attribute_name`.
auto atom = style_engine->intern_attribute_name(name, namespace_uri);
+ // OPTIMIZATION: Nothing of the engine reads this name, so the element's row need not hear of the change. The element
+ // is noted as an arrival withholding the name is, and is published if something comes to read it.
+ if (style_engine->attribute_is_known_unread(atom)) {
+ style_engine->note_attribute_withheld(name, namespace_uri, element.style_node_id());
+ return;
+ }
auto kind_of = [](Optional<Utf16String> const& value) {
return value.has_value() ? StyleEngineFFI::FfiFeatureValueKind::Atom : StyleEngineFFI::FfiFeatureValueKind::Absent;
};
auto atom_of = [&](Optional<Utf16String> const& value) {
return value.has_value() ? style_engine->intern_attribute_value(atom, *value) : 0;
};
- auto old_kind = kind_of(old_value);
- auto old_atom = atom_of(old_value);
auto new_kind = kind_of(new_value);
auto new_atom = atom_of(new_value);
record_feature(
element,
StyleEngineFFI::FfiFeatureKind::Attribute,
atom,
- old_kind,
- old_atom,
new_kind,
new_atom);
}
+// OPTIMIZATION: A document records its user-agent and user sheets once it knows its mode, which decides which user-agent
+// sheets it takes and how their selectors compile, rather than in its first style update. The render
+// owner takes their rules in beside the parser, compiling the selectors of the user agent rules the
+// process has not compiled yet, so the first style update does not wait on it.
+void prepare_non_author_stylesheets(DOM::Document& document)
+{
+ // NB: A document nothing renders, as DOMParser makes, never styles anything.
+ if (!document.navigable())
+ return;
+ record_non_author_stylesheets(document);
+ StyleEngineFFI::style_engine_stream_rule_writes(document.style_computer().style_engine().host());
+}
+
}
diff --git a/Libraries/LibWeb/CSS/StyleEngineInput.h b/Libraries/LibWeb/CSS/StyleEngineInput.h
index 7f03dca2d92..783c0c4d6e9 100644
--- a/Libraries/LibWeb/CSS/StyleEngineInput.h
+++ b/Libraries/LibWeb/CSS/StyleEngineInput.h
@@ -86,15 +86,15 @@ WEB_API void record_waiting_element_classes_changed(DOM::Element&);
// Called whenever a text node's data is replaced. The mirror carries the characters, which the layout tree build
// renders, and whether they are nothing but ASCII whitespace.
WEB_API void record_text_data_changed(DOM::Text&);
-WEB_API void publish_pending_element_features(StyleEngine&, StyleComputer&);
-WEB_API void publish_required_attribute_value_texts(StyleEngine&, StyleComputer&);
+WEB_API void publish_pending_element_features(StyleEngine&, StyleComputer&, Layout::BegunRead const&);
+WEB_API void publish_withheld_element_features(StyleEngine&, StyleComputer&, Layout::BegunRead const&);
// Called while the subtree is still linked, so its old relations are still readable.
WEB_API void record_subtree_disconnecting(DOM::Node&);
// Report that an element moved without leaving the tree. `moveBefore()` keeps the element's state
// and its identity, so nothing disconnects and nothing connects, and only its relations move.
-WEB_API void record_element_moved(DOM::Element&, DOM::Node* old_parent, DOM::Element* old_previous_sibling, DOM::Element* old_next_sibling);
+WEB_API void record_element_moved(DOM::Element&, DOM::Node* old_parent, DOM::Element* old_previous_sibling, DOM::Element* old_next_sibling, DOM::Element* old_assigned_slot);
// Report that an element or text node moved without leaving the tree, which moves its place in the
// DOM child sequence even where its element relations stay the same.
@@ -150,16 +150,12 @@ WEB_API void record_element_replaced_content_input(DOM::Element&);
WEB_API bool record_element_presentational_hint_properties(DOM::Element&, ReadonlySpan<StyleProperty>);
// Publish the element's hints again, after something they are mapped from beside its own attributes moved.
WEB_API void republish_presentational_hints(DOM::Element&);
-WEB_API void record_element_animation_names(DOM::Element&, ReadonlySpan<Utf16FlyString>);
WEB_API void record_element_css_defined_animations(DOM::Element&, u8 slot, ReadonlySpan<Utf16FlyString> names, ReadonlySpan<StyleEngineFFI::FfiAppliedAnimationDefinition> definitions);
+// Called where an effect takes keyframes or a target: ahead of the read that samples it, as an attr() in the keyframes
+// needs the attributes it names handed over before then.
+WEB_API void record_attr_names_read_by_keyframes(DOM::Element&, Animations::KeyframeEffect const&);
WEB_API void record_element_animation_effect_descriptions(DOM::Element&, u8 slot, ReadonlySpan<GC::Ref<Animations::KeyframeEffect>>);
-// The same index, from the environments the element and its pseudo-elements resolved to, plus
-// names read outside substitution (for example by style queries). The names each environment
-// declares are interned into engine identities once for that environment. The references must hold
-// no duplicates.
-WEB_API void record_element_custom_property_names(DOM::Element&, CustomPropertyData const*, ReadonlySpan<RefPtr<CustomPropertyData const>> pseudo_element_data, ReadonlySpan<Utf16FlyString> references, bool uses_unnamed, bool uses_custom_functions);
-
// Report that a child of an element arrived, left, or changed in a way that can move whether the
// element is empty. `counted_before` and `counts_after` say whether that child is one `:empty` counts:
// an element child always counts, a text child counts while its data is not empty, and anything else
@@ -175,6 +171,11 @@ WEB_API void record_element_state_changed(DOM::Element&, PseudoClass, bool new_v
// Called before each style flush. The user-agent and user origins have no sheet list to announce
// themselves from, so the engine is told about them from here.
WEB_API void record_non_author_stylesheets(DOM::Document&);
+WEB_API bool non_author_stylesheets_are_recorded(DOM::Document const&);
+
+// Called once a document knows its mode, ahead of its first style flush: records its user-agent and user sheets, and
+// has the render owner take their rules in beside the caller.
+WEB_API void prepare_non_author_stylesheets(DOM::Document&);
// Called once a sheet has taken its place in the sheet list, so its successor is known.
WEB_API void record_stylesheet_attached(StyleSheetState&, DOM::Node& document_or_shadow_root, StyleSheetState* before);
@@ -202,10 +203,11 @@ WEB_API bool stop_sharing_compiled_style_sheet(StyleSheetState&);
// Called once a sheet's media queries have been evaluated.
WEB_API void record_stylesheet_conditions(StyleSheetState&, DOM::Node& document_or_shadow_root, bool conditions_hold);
+void publish_user_agent_sheet(StyleSheetState const&, DOM::Document const&);
WEB_API void record_stylesheet_rule_conditions(StyleSheetState&);
WEB_API void record_stylesheet_rule_conditions(StyleSheetState&, DOM::Document&);
-WEB_API void record_element_id_changed(DOM::Element&, Optional<Utf16FlyString> const& old_value, Optional<Utf16FlyString> const& new_value);
+WEB_API void record_element_id_changed(DOM::Element&, Optional<Utf16FlyString> const& new_value);
WEB_API void record_element_class_list_changed(DOM::Element&, ReadonlySpan<Utf16FlyString> old_classes, ReadonlySpan<Utf16FlyString> new_classes);
WEB_API void record_element_attribute_changed(DOM::Element&, Utf16FlyString const& name, Optional<Utf16FlyString> const& namespace_uri, Optional<Utf16String> const& old_value, Optional<Utf16String> const& new_value);
diff --git a/Libraries/LibWeb/Rust/src/css/style/atoms.rs b/Libraries/LibWeb/Rust/src/css/style/atoms.rs
index c1466907f13..09fc4f9d370 100644
--- a/Libraries/LibWeb/Rust/src/css/style/atoms.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/atoms.rs
@@ -9,19 +9,18 @@ use std::collections::HashMap;
use std::collections::HashSet;
use std::collections::hash_map::Entry;
use std::hash::BuildHasher;
+use std::sync::Arc;
use std::sync::Mutex;
+use std::sync::MutexGuard;
use std::sync::OnceLock;
+use std::sync::atomic::{AtomicU8, AtomicU32, AtomicU64, AtomicUsize, Ordering};
use super::index::StyleAtomID;
+use crate::css::retained_fly_string::RetainedUtf16FlyString;
const TEXT_KEY_MASK: u64 = 0x0000_ffff_ffff_ffff;
const TEXT_KEY_FLOOR: usize = usize::MAX - TEXT_KEY_MASK as usize;
-#[must_use]
-pub(super) fn synthetic_text_atom_key(hash: u64) -> usize {
- usize::MAX - (hash & TEXT_KEY_MASK) as usize
-}
-
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
enum RawAtomLifetime {
RetainedFlyString,
@@ -40,131 +39,571 @@ impl RawAtomLifetime {
}
}
-#[derive(Clone, Copy)]
-struct GlobalAtomEntry {
- atom: StyleAtomID,
- document_references: u64,
- raw_lifetime: Option<RawAtomLifetime>,
+/// What a number of the table says while a live atom has it. Only the table's lock writes a cell, and a cell a live
+/// atom has is written once, but for its lowercase form and its references, so a thread that holds a reference to the
+/// atom reads the rest of it without the lock.
+#[derive(Default)]
+struct AtomCell {
+ /// The raw identity of the name, or the namespace and local name of a qualified one.
+ key: AtomicU64,
+ /// What the key is, or zero where no live atom has the number.
+ kind: AtomicU8,
+ /// The atom of the name's ASCII-lowercase form, once asked for, which the cell holds a reference to where it is
+ /// another atom.
+ lowercase: AtomicU32,
+ document_references: AtomicU64,
+}
+
+const ATOM_KIND_FREE: u8 = 0;
+const ATOM_KIND_QUALIFIED: u8 = 1;
+const ATOM_KIND_RETAINED_RAW: u8 = 2;
+const ATOM_KIND_SYNTHETIC_RAW: u8 = 3;
+#[cfg(test)]
+const ATOM_KIND_OPAQUE_TEST_RAW: u8 = 4;
+
+impl AtomCell {
+ fn key(&self) -> Option<AtomKey> {
+ let key = self.key.load(Ordering::Acquire);
+ match self.kind.load(Ordering::Acquire) {
+ ATOM_KIND_FREE => None,
+ ATOM_KIND_QUALIFIED => Some(AtomKey::Qualified(
+ StyleAtomID((key >> 32) as u32),
+ StyleAtomID(key as u32),
+ )),
+ _ => Some(AtomKey::Raw(key as usize)),
+ }
+ }
+
+ fn raw_lifetime(&self) -> Option<RawAtomLifetime> {
+ match self.kind.load(Ordering::Acquire) {
+ ATOM_KIND_RETAINED_RAW => Some(RawAtomLifetime::RetainedFlyString),
+ ATOM_KIND_SYNTHETIC_RAW => Some(RawAtomLifetime::SyntheticTextKey),
+ #[cfg(test)]
+ ATOM_KIND_OPAQUE_TEST_RAW => Some(RawAtomLifetime::OpaqueTestToken),
+ _ => None,
+ }
+ }
+}
+
+fn qualified_key(namespace: StyleAtomID, name: StyleAtomID) -> u64 {
+ (u64::from(namespace.0) << 32) | u64::from(name.0)
+}
+
+/// How many cells the first chunk of the table's cells holds. Each next chunk holds twice what all before it do.
+const FIRST_ATOM_CHUNK_BITS: u32 = 10;
+
+/// The cells of the table, by atom number, which never move: a chunk stays for as long as the table does.
+struct AtomCells {
+ chunks: [OnceLock<Box<[AtomCell]>>; 23],
+}
+
+impl Default for AtomCells {
+ fn default() -> Self {
+ Self {
+ chunks: std::array::from_fn(|_| OnceLock::new()),
+ }
+ }
+}
+
+impl AtomCells {
+ fn place_of(atom: StyleAtomID) -> (usize, usize) {
+ let place = u64::from(atom.0) + (1 << FIRST_ATOM_CHUNK_BITS);
+ let bits = place.ilog2();
+ ((bits - FIRST_ATOM_CHUNK_BITS) as usize, (place - (1 << bits)) as usize)
+ }
+
+ /// The cell of `atom`, where one was ever made.
+ fn get(&self, atom: StyleAtomID) -> Option<&AtomCell> {
+ let (chunk, index) = Self::place_of(atom);
+ Some(&self.chunks[chunk].get()?[index])
+ }
+
+ fn get_or_make(&self, atom: StyleAtomID) -> &AtomCell {
+ let (chunk, index) = Self::place_of(atom);
+ let cells = self.chunks[chunk].get_or_init(|| {
+ (0..1_usize << (chunk as u32 + FIRST_ATOM_CHUNK_BITS))
+ .map(|_| AtomCell::default())
+ .collect()
+ });
+ &cells[index]
+ }
}
#[derive(Default)]
-struct GlobalAtoms {
- raw: HashMap<usize, GlobalAtomEntry>,
- qualified: HashMap<(u32, u32), GlobalAtomEntry>,
+struct AtomIndexSlot {
+ /// The key the slot is for, or zero where it never held one. A slot holding a key stays in the probe sequences
+ /// through it until the index is laid out again.
+ key: AtomicU64,
+ /// The atom of the key, or zero where the slot's key has none any more.
+ atom: AtomicU32,
+}
+
+/// The atom of each key, which a thread reads without the table's lock and only the lock's holder writes: open
+/// addressing over slots that never move. A read without the lock may miss, as the index is laid out again beside it,
+/// or find the atom a key just lost: a caller goes on to the lock on a miss, and takes an answer only if the atom it
+/// names is one it holds, whose cell names the key.
+struct AtomIndex {
+ /// The slots, by size: each is twice the one before, and the last made is the one in use.
+ generations: [OnceLock<Box<[AtomIndexSlot]>>; 32],
+ current: AtomicUsize,
+ /// How many slots hold a key, and how many of those keys have an atom. Only the lock's holder reads these.
+ used: AtomicUsize,
+ live: AtomicUsize,
+}
+
+impl Default for AtomIndex {
+ fn default() -> Self {
+ Self {
+ generations: std::array::from_fn(|_| OnceLock::new()),
+ current: AtomicUsize::new(usize::MAX),
+ used: AtomicUsize::new(0),
+ live: AtomicUsize::new(0),
+ }
+ }
+}
+
+const FIRST_ATOM_INDEX_BITS: u32 = 10;
+
+impl AtomIndex {
+ fn slots(&self) -> Option<&[AtomIndexSlot]> {
+ let current = self.current.load(Ordering::Acquire);
+ (current != usize::MAX).then(|| &**self.generations[current].get().expect("the current slots are made"))
+ }
+
+ fn home(key: u64, slots: usize) -> usize {
+ debug_assert!(slots.is_power_of_two());
+ (key.wrapping_mul(0x9e37_79b9_7f4a_7c15) >> (u64::BITS - slots.ilog2())) as usize
+ }
+
+ fn get(&self, key: u64) -> Option<StyleAtomID> {
+ let slots = self.slots()?;
+ let mask = slots.len() - 1;
+ let mut place = Self::home(key, slots.len());
+ // NB: Fewer than all slots hold a key, whichever slots a reader sees written.
+ for _ in 0..slots.len() {
+ let slot = &slots[place];
+ match slot.key.load(Ordering::Acquire) {
+ 0 => return None,
+ found if found == key => {
+ let atom = slot.atom.load(Ordering::Acquire);
+ return (atom != 0).then_some(StyleAtomID(atom));
+ }
+ _ => place = (place + 1) & mask,
+ }
+ }
+ None
+ }
+
+ /// Note the atom of `key`, which has none. Only the lock's holder calls this.
+ fn insert(&self, key: u64, atom: StyleAtomID) {
+ assert_ne!(key, 0, "no atom has the empty key");
+ let used = self.used.load(Ordering::Relaxed);
+ let live = self.live.load(Ordering::Relaxed);
+ let capacity = self.slots().map_or(0, <[AtomIndexSlot]>::len);
+ if (used + 1) * 4 > capacity * 3 {
+ self.lay_out(live + 1);
+ }
+ let slots = self.slots().expect("the index was laid out");
+ let mask = slots.len() - 1;
+ let mut place = Self::home(key, slots.len());
+ let mut reusable = None;
+ loop {
+ let slot = &slots[place];
+ match slot.key.load(Ordering::Relaxed) {
+ 0 => break,
+ found if found == key => {
+ reusable = Some(place);
+ break;
+ }
+ _ if reusable.is_none() && slot.atom.load(Ordering::Relaxed) == 0 => reusable = Some(place),
+ _ => {}
+ }
+ place = (place + 1) & mask;
+ }
+ let slot = match reusable {
+ Some(reusable) => &slots[reusable],
+ None => {
+ self.used.fetch_add(1, Ordering::Relaxed);
+ &slots[place]
+ }
+ };
+ slot.key.store(key, Ordering::Release);
+ slot.atom.store(atom.0, Ordering::Release);
+ self.live.fetch_add(1, Ordering::Relaxed);
+ }
+
+ /// Note that `key` has no atom any more. Only the lock's holder calls this.
+ fn remove(&self, key: u64) {
+ let slots = self.slots().expect("a key with an atom is in the index");
+ let mask = slots.len() - 1;
+ let mut place = Self::home(key, slots.len());
+ loop {
+ let slot = &slots[place];
+ if slot.key.load(Ordering::Relaxed) == key {
+ slot.atom.store(0, Ordering::Release);
+ self.live.fetch_sub(1, Ordering::Relaxed);
+ return;
+ }
+ place = (place + 1) & mask;
+ }
+ }
+
+ /// Have the slots hold nothing but the keys with an atom, with room for `wanted` of them: in the slots in use where
+ /// they fit in a quarter of those, as a reader that misses meanwhile goes on to the lock, or in twice as many.
+ fn lay_out(&self, wanted: usize) {
+ let current = self.current.load(Ordering::Relaxed);
+ let live: Vec<(u64, u32)> = self.slots().map_or_else(Vec::new, |slots| {
+ slots
+ .iter()
+ .filter_map(|slot| {
+ let atom = slot.atom.load(Ordering::Relaxed);
+ (atom != 0).then(|| (slot.key.load(Ordering::Relaxed), atom))
+ })
+ .collect()
+ });
+ let capacity = self.slots().map_or(0, <[AtomIndexSlot]>::len);
+ if wanted * 4 <= capacity {
+ for slot in self.slots().expect("the slots have a capacity") {
+ slot.atom.store(0, Ordering::Release);
+ slot.key.store(0, Ordering::Release);
+ }
+ } else {
+ let next = current.wrapping_add(1);
+ self.generations[next].get_or_init(|| {
+ (0..1_usize << (next as u32 + FIRST_ATOM_INDEX_BITS))
+ .map(|_| AtomIndexSlot::default())
+ .collect()
+ });
+ self.current.store(next, Ordering::Release);
+ }
+ self.used.store(0, Ordering::Relaxed);
+ self.live.store(0, Ordering::Relaxed);
+ for (key, atom) in live {
+ self.insert(key, StyleAtomID(atom));
+ }
+ }
+}
+
+/// What the table's lock writes and any thread reads without it.
+#[derive(Default)]
+struct SharedAtoms {
+ cells: AtomCells,
+ raw: AtomIndex,
+ qualified: AtomIndex,
+}
+
+impl SharedAtoms {
+ fn key_of(&self, atom: StyleAtomID) -> Option<AtomKey> {
+ self.cells.get(atom).and_then(AtomCell::key)
+ }
+}
+
+#[derive(Default)]
+struct AtomTable {
+ shared: Arc<SharedAtoms>,
available: BTreeSet<u32>,
next: u32,
}
-impl GlobalAtoms {
+impl AtomTable {
fn allocate(&mut self) -> StyleAtomID {
- if let Some(atom) = self.available.pop_first() {
- return StyleAtomID(atom);
+ match self.available.pop_first() {
+ Some(atom) => StyleAtomID(atom),
+ None => {
+ self.next = self
+ .next
+ .checked_add(1)
+ .expect("process-global style atom space exhausted");
+ StyleAtomID(self.next)
+ }
+ }
+ }
+
+ fn cell(&self, atom: StyleAtomID) -> &AtomCell {
+ self.shared
+ .cells
+ .get(atom)
+ .expect("an atom read through the table is live")
+ }
+
+ /// Takes one more reference to the live atom `atom`.
+ fn reference(&mut self, atom: StyleAtomID) {
+ let references = &self.cell(atom).document_references;
+ assert_ne!(references.load(Ordering::Relaxed), 0, "a reference is to a live atom");
+ references.fetch_add(1, Ordering::Relaxed);
+ }
+
+ /// Lets go of one reference to the live atom `atom`, which goes with the last of them.
+ fn release(&mut self, atom: StyleAtomID) {
+ let cell = self.cell(atom);
+ if cell.document_references.fetch_sub(1, Ordering::Relaxed) != 1 {
+ return;
+ }
+ let key = cell.key.load(Ordering::Relaxed);
+ let lifetime = cell.raw_lifetime();
+ let lowercase = StyleAtomID(cell.lowercase.swap(0, Ordering::Release));
+ cell.kind.store(ATOM_KIND_FREE, Ordering::Release);
+ match lifetime {
+ Some(lifetime) => {
+ self.shared.raw.remove(key);
+ if lifetime == RawAtomLifetime::RetainedFlyString {
+ // SAFETY: acquire_raw retained exactly one global reference for this entry.
+ unsafe {
+ ak::release_utf16_string_with(key as usize, crate::css::ffi_stats::release_utf16_fly_string);
+ };
+ }
+ }
+ None => self.shared.qualified.remove(key),
+ }
+ self.available.insert(atom.0);
+ if !lowercase.is_none() && lowercase != atom {
+ self.release(lowercase);
+ }
+ }
+
+ /// What `atom` names, or none where no live atom has its number.
+ fn key_of(&self, atom: StyleAtomID) -> Option<AtomKey> {
+ self.shared.key_of(atom)
+ }
+
+ /// The raw identity of the name `atom` was interned from, for a live name the table holds a reference to.
+ fn retained_raw(&self, atom: StyleAtomID) -> Option<usize> {
+ let cell = self.shared.cells.get(atom)?;
+ (cell.raw_lifetime() == Some(RawAtomLifetime::RetainedFlyString))
+ .then(|| cell.key.load(Ordering::Relaxed) as usize)
+ }
+
+ /// The atom of the ASCII-lowercase form of the live atom `atom`'s name, which the cell of `atom` keeps live: the
+ /// atom itself where the name has no uppercase letter, or where it was not interned from a name.
+ fn ascii_lowercase(&mut self, atom: StyleAtomID) -> StyleAtomID {
+ assert!(self.key_of(atom).is_some(), "an atom read through the table is live");
+ let known = StyleAtomID(self.cell(atom).lowercase.load(Ordering::Relaxed));
+ if !known.is_none() {
+ return known;
}
- self.next = self
- .next
- .checked_add(1)
- .expect("process-global style atom space exhausted");
- StyleAtomID(self.next)
+ let lowercase = match self.key_of(atom) {
+ Some(AtomKey::Qualified(namespace, local)) => {
+ let lowercase_local = self.ascii_lowercase(local);
+ if lowercase_local == local {
+ atom
+ } else {
+ self.acquire_qualified(namespace, lowercase_local)
+ }
+ }
+ _ => match self.retained_raw(atom) {
+ None => atom,
+ Some(raw) => {
+ // SAFETY: The table holds a reference to the name, which this borrows.
+ let name = std::mem::ManuallyDrop::new(unsafe { ak::Utf16FlyString::from_raw_owned(raw) });
+ let text = name.to_utf16();
+ if !text
+ .iter()
+ .any(|unit| (u16::from(b'A')..=u16::from(b'Z')).contains(unit))
+ {
+ atom
+ } else {
+ let lowercase: Vec<u16> = text
+ .iter()
+ .map(|&unit| crate::css::ffi_support::ascii_lowercase(unit))
+ .collect();
+ let lowercase = ak::Utf16FlyString::from_utf16(&lowercase);
+ self.acquire_raw(lowercase.raw_identity(), RawAtomLifetime::RetainedFlyString)
+ }
+ }
+ },
+ };
+ self.cell(atom).lowercase.store(lowercase.0, Ordering::Release);
+ lowercase
+ }
+
+ /// Makes the atom of a name that has none.
+ fn make(&mut self, key: u64, kind: u8) -> StyleAtomID {
+ let atom = self.allocate();
+ let cell = self.shared.cells.get_or_make(atom);
+ cell.key.store(key, Ordering::Release);
+ cell.lowercase.store(0, Ordering::Release);
+ cell.document_references.store(1, Ordering::Relaxed);
+ cell.kind.store(kind, Ordering::Release);
+ atom
}
fn acquire_raw(&mut self, raw: usize, lifetime: RawAtomLifetime) -> StyleAtomID {
let lifetime = lifetime.for_raw(raw);
- if let Some(entry) = self.raw.get_mut(&raw) {
+ if let Some(atom) = self.shared.raw.get(raw as u64) {
+ let cell = self.cell(atom);
assert_eq!(
- entry.raw_lifetime,
+ cell.raw_lifetime(),
Some(lifetime),
"one raw atom cannot mix live and test identity"
);
- entry.document_references += 1;
- return entry.atom;
+ cell.document_references.fetch_add(1, Ordering::Relaxed);
+ return atom;
}
- let atom = self.allocate();
- if lifetime == RawAtomLifetime::RetainedFlyString {
- // SAFETY: Live StyleEngine callers pass the raw identity of a referenced Utf16FlyString.
- unsafe { ak::reference_utf16_string(raw) };
- }
- self.raw.insert(
- raw,
- GlobalAtomEntry {
- atom,
- document_references: 1,
- raw_lifetime: Some(lifetime),
- },
- );
+ let kind = match lifetime {
+ RawAtomLifetime::RetainedFlyString => {
+ // SAFETY: Live StyleEngine callers pass the raw identity of a referenced Utf16FlyString.
+ unsafe { ak::reference_utf16_string(raw) };
+ ATOM_KIND_RETAINED_RAW
+ }
+ RawAtomLifetime::SyntheticTextKey => ATOM_KIND_SYNTHETIC_RAW,
+ #[cfg(test)]
+ RawAtomLifetime::OpaqueTestToken => ATOM_KIND_OPAQUE_TEST_RAW,
+ };
+ let atom = self.make(raw as u64, kind);
+ self.shared.raw.insert(raw as u64, atom);
atom
}
fn acquire_qualified(&mut self, namespace: StyleAtomID, name: StyleAtomID) -> StyleAtomID {
- let key = (namespace.0, name.0);
- if let Some(entry) = self.qualified.get_mut(&key) {
- entry.document_references += 1;
- return entry.atom;
+ let key = qualified_key(namespace, name);
+ if let Some(atom) = self.shared.qualified.get(key) {
+ self.cell(atom).document_references.fetch_add(1, Ordering::Relaxed);
+ return atom;
}
- let atom = self.allocate();
- self.qualified.insert(
- key,
- GlobalAtomEntry {
- atom,
- document_references: 1,
- raw_lifetime: None,
- },
- );
+ let atom = self.make(key, ATOM_KIND_QUALIFIED);
+ self.shared.qualified.insert(key, atom);
atom
}
+}
+
+/// The style atoms of the process, which every style engine and document host of the process interns names in: one
+/// name is one atom in every document. The process style holds the table, and each engine, host and lease names it.
+pub(crate) struct ProcessAtoms {
+ table: Mutex<AtomTable>,
+ shared: Arc<SharedAtoms>,
+}
+
+impl Default for ProcessAtoms {
+ fn default() -> Self {
+ let table = AtomTable::default();
+ Self {
+ shared: Arc::clone(&table.shared),
+ table: Mutex::new(table),
+ }
+ }
+}
+
+impl ProcessAtoms {
+ fn lock(&self) -> MutexGuard<'_, AtomTable> {
+ self.table.lock().expect("process style atom lock is poisoned")
+ }
- fn release_raw(&mut self, raw: usize, expected: StyleAtomID) {
- let Entry::Occupied(mut occupied) = self.raw.entry(raw) else {
- unreachable!("a document must release a live global atom");
+ /// The name `atom` was interned from, a qualified atom's being its local name's, or none where it was interned
+ /// from text rather than from a name, or no live atom has the number.
+ pub(crate) fn text(&self, atom: StyleAtomID) -> Option<RetainedUtf16FlyString> {
+ let table = self.lock();
+ let atom = match table.key_of(atom) {
+ Some(AtomKey::Qualified(_, local)) => local,
+ _ => atom,
};
- let entry = occupied.get_mut();
- assert_eq!(entry.atom, expected);
- entry.document_references -= 1;
- if entry.document_references != 0 {
- return;
+ let raw = table.retained_raw(atom)?;
+ // SAFETY: The table holds a reference to the name, so it is live while the lock is held.
+ Some(unsafe { RetainedUtf16FlyString::from_borrowed_raw(raw) })
+ }
+
+ /// The raw identity of the name `atom` was interned from, or of a qualified atom's local name, which the table
+ /// holds a reference to while `atom` lives, or none where it was interned from text rather than from a name.
+ pub(crate) fn local_raw_of(&self, atom: StyleAtomID) -> Option<usize> {
+ let atom = match self.shared.key_of(atom) {
+ Some(AtomKey::Qualified(_, local)) => local,
+ _ => atom,
+ };
+ let cell = self.shared.cells.get(atom)?;
+ (cell.raw_lifetime() == Some(RawAtomLifetime::RetainedFlyString))
+ .then(|| cell.key.load(Ordering::Acquire) as usize)
+ }
+
+ /// A reference to the atom of the name `units` spell.
+ pub(crate) fn intern(self: &Arc<Self>, units: &[u16]) -> AtomLease {
+ let name = ak::Utf16FlyString::from_utf16(units);
+ // SAFETY: The fly string is live for the call, and the lease takes a reference of its own.
+ unsafe { AtomLease::acquire_raw(self, name.raw_identity()) }
+ }
+
+ /// The atom of the ASCII-lowercase form of `atom`'s name, which lives at least as long as `atom` does: what a
+ /// quirks-mode document compares ids and classes by, and an HTML element in an HTML document its tag name by.
+ pub(crate) fn ascii_lowercase(&self, atom: StyleAtomID) -> StyleAtomID {
+ // NB: The caller holds a reference to `atom`, so its cell says what it says until the caller lets go. Only the
+ // first ask for a name takes the lock, as matching asks for each name it tests, on every thread.
+ if let Some(cell) = self.shared.cells.get(atom) {
+ let known = cell.lowercase.load(Ordering::Acquire);
+ if known != 0 {
+ return StyleAtomID(known);
+ }
}
- let entry = occupied.remove();
- self.available.insert(entry.atom.0);
- if entry.raw_lifetime == Some(RawAtomLifetime::RetainedFlyString) {
- // SAFETY: acquire_raw retained exactly one global reference for this entry.
- unsafe { ak::release_utf16_string_with(raw, crate::css::ffi_stats::release_utf16_fly_string) };
+ self.lock().ascii_lowercase(atom)
+ }
+
+ /// One reference to each distinct atom of `atoms`, all live, which the leases hold until they drop.
+ pub(crate) fn lease(self: &Arc<Self>, atoms: impl IntoIterator<Item = StyleAtomID>) -> AtomLeases {
+ let mut atoms: Vec<StyleAtomID> = atoms.into_iter().filter(|atom| !atom.is_none()).collect();
+ atoms.sort_unstable_by_key(|atom| atom.0);
+ atoms.dedup();
+ let mut table = self.lock();
+ for &atom in &atoms {
+ table.reference(atom);
+ }
+ AtomLeases {
+ process: Arc::clone(self),
+ atoms: atoms.into_boxed_slice(),
}
}
+}
+
+/// A reference to each of a set of process atoms, which keeps every one of their numbers from naming another name
+/// while the leases live. A structure that names atoms off the main thread, as parsed selectors do, holds its atoms
+/// this way: one reference per distinct atom, however often the structure names it.
+pub(crate) struct AtomLeases {
+ process: Arc<ProcessAtoms>,
+ /// The atoms, sorted by number.
+ atoms: Box<[StyleAtomID]>,
+}
- /// Takes one more document reference to the live raw atom `raw`, for a fork of a document that holds it.
- fn reference_raw(&mut self, raw: usize, expected: StyleAtomID) {
- let entry = self
- .raw
- .get_mut(&raw)
- .expect("a document references a live global atom");
- assert_eq!(entry.atom, expected);
- entry.document_references += 1;
+impl std::fmt::Debug for AtomLeases {
+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
+ formatter
+ .debug_list()
+ .entries(self.atoms.iter().map(|atom| atom.0))
+ .finish()
}
+}
- /// Takes one more document reference to the live qualified atom `key`, for a fork of a document that holds it.
- fn reference_qualified(&mut self, key: (u32, u32), expected: StyleAtomID) {
- let entry = self
- .qualified
- .get_mut(&key)
- .expect("a document references a live global qualified atom");
- assert_eq!(entry.atom, expected);
- entry.document_references += 1;
+impl AtomLeases {
+ /// The atoms the leases hold.
+ pub(crate) fn atoms(&self) -> &[StyleAtomID] {
+ &self.atoms
}
- fn release_qualified(&mut self, key: (u32, u32), expected: StyleAtomID) {
- let Entry::Occupied(mut occupied) = self.qualified.entry(key) else {
- unreachable!("a document must release a live global qualified atom");
- };
- let entry = occupied.get_mut();
- assert_eq!(entry.atom, expected);
- entry.document_references -= 1;
- if entry.document_references != 0 {
- return;
+ /// Whether the leases hold `atom`.
+ #[cfg_attr(
+ not(test),
+ expect(dead_code, reason = "the selector arena checks its names through it")
+ )]
+ pub(crate) fn holds(&self, atom: StyleAtomID) -> bool {
+ self.atoms.binary_search_by_key(&atom.0, |held| held.0).is_ok()
+ }
+}
+
+impl Clone for AtomLeases {
+ fn clone(&self) -> Self {
+ self.process.lease(self.atoms.iter().copied())
+ }
+}
+
+impl Drop for AtomLeases {
+ fn drop(&mut self) {
+ let mut table = self.process.lock();
+ for &atom in &self.atoms {
+ table.release(atom);
}
- let entry = occupied.remove();
- self.available.insert(entry.atom.0);
}
}
+/// The atoms of the process, which parsed selectors name their names by.
+pub(crate) fn process_atoms() -> &'static Arc<ProcessAtoms> {
+ crate::render_state::process_style().atoms()
+}
+
/// What a reference to a process-global atom is the reference to: the raw atom of a name, or a qualified name.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(super) enum AtomKey {
@@ -176,38 +615,40 @@ pub(super) enum AtomKey {
/// engine, and which keeps the atom's number from being handed out again until the engine has adopted the name. It is
/// the reference itself, so it is neither `Clone` nor `Copy`, and dropping it releases it.
pub(crate) struct AtomLease {
+ process: Arc<ProcessAtoms>,
key: AtomKey,
atom: StyleAtomID,
}
impl AtomLease {
- /// Takes a reference to the global atom of the name whose raw identity is `raw`.
+ /// Takes a reference to the atom `process` has for the name whose raw identity is `raw`.
///
/// # Safety
/// `raw` must be the raw identity of a live `AK::Utf16FlyString`.
- pub(crate) unsafe fn acquire_raw(raw: usize) -> Self {
- let atom = global_atoms()
- .lock()
- .expect("process-global style atom lock is poisoned")
- .acquire_raw(raw, RawAtomLifetime::RetainedFlyString);
+ pub(crate) unsafe fn acquire_raw(process: &Arc<ProcessAtoms>, raw: usize) -> Self {
+ let atom = process.lock().acquire_raw(raw, RawAtomLifetime::RetainedFlyString);
Self {
+ process: Arc::clone(process),
key: AtomKey::Raw(raw),
atom,
}
}
- /// Takes a reference to the global atom of `name` qualified by `namespace`.
- pub(crate) fn acquire_qualified(namespace: StyleAtomID, name: StyleAtomID) -> Self {
- let atom = global_atoms()
- .lock()
- .expect("process-global style atom lock is poisoned")
- .acquire_qualified(namespace, name);
+ /// Takes a reference to the atom `process` has for `name` qualified by `namespace`.
+ pub(crate) fn acquire_qualified(process: &Arc<ProcessAtoms>, namespace: StyleAtomID, name: StyleAtomID) -> Self {
+ let atom = process.lock().acquire_qualified(namespace, name);
Self {
+ process: Arc::clone(process),
key: AtomKey::Qualified(namespace, name),
atom,
}
}
+ /// Whether the lease is a reference to an atom of `process`.
+ pub(super) fn is_of(&self, process: &Arc<ProcessAtoms>) -> bool {
+ Arc::ptr_eq(&self.process, process)
+ }
+
pub(crate) fn atom(&self) -> StyleAtomID {
self.atom
}
@@ -219,23 +660,10 @@ impl AtomLease {
impl Drop for AtomLease {
fn drop(&mut self) {
- let mut global = global_atoms()
- .lock()
- .expect("process-global style atom lock is poisoned");
- match self.key {
- AtomKey::Raw(raw) => global.release_raw(raw, self.atom),
- AtomKey::Qualified(namespace, name) => global.release_qualified((namespace.0, name.0), self.atom),
- }
+ self.process.lock().release(self.atom);
}
}
-fn global_atoms() -> &'static Mutex<GlobalAtoms> {
- // The mutex supplies the `Sync` required by a process-global static. It does not make a
- // `DocumentAtoms` owner, or the StyleEngine containing it, safe to use from multiple threads.
- static GLOBAL_ATOMS: OnceLock<Mutex<GlobalAtoms>> = OnceLock::new();
- GLOBAL_ATOMS.get_or_init(|| Mutex::new(GlobalAtoms::default()))
-}
-
#[derive(Clone, Copy)]
enum AtomScope {
#[cfg(test)]
@@ -243,11 +671,18 @@ enum AtomScope {
Process(RawAtomLifetime),
}
+/// What a document holds of the process's atoms: a reference to each atom it interned, which a sweep lets go of where
+/// nothing in the document names it any more. The table answers what each name's atom is.
pub(super) struct DocumentAtoms {
- raw: HashMap<usize, StyleAtomID>,
- cpp_memoized_raws: HashSet<usize>,
- qualified: HashMap<(u32, u32), StyleAtomID>,
+ /// The atoms the document holds a reference to, as one bit per number of the table's atoms.
+ held: Vec<u64>,
+ held_count: usize,
scope: AtomScope,
+ /// The process's table, which the atoms are the process's references to where the scope is the process's.
+ process: Arc<ProcessAtoms>,
+ /// The table of a document whose atoms are its own, which no other document's are.
+ #[cfg(test)]
+ own: Option<Arc<ProcessAtoms>>,
/// Atoms a layout publication names, and how many publications name each.
///
/// A name the document carries is kept live by the state that carries it, but a published
@@ -255,13 +690,11 @@ pub(super) struct DocumentAtoms {
/// in the document. Nothing else roots such an atom, so a sweep would hand its number out
/// again and the publication would then read as naming whatever took it.
published: HashMap<StyleAtomID, u64>,
- #[cfg(test)]
- available: BTreeSet<u32>,
- #[cfg(test)]
- next: u32,
sweep_at: usize,
}
+const HELD_BITS_PER_WORD: u32 = u64::BITS;
+
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub(crate) struct ReclaimedStyleAtom {
pub raw: usize,
@@ -269,79 +702,148 @@ pub(crate) struct ReclaimedStyleAtom {
}
impl DocumentAtoms {
- pub(super) fn for_live_engine() -> Self {
+ pub(super) fn for_live_engine(process: &Arc<ProcessAtoms>) -> Self {
#[cfg(test)]
let scope = AtomScope::Document;
#[cfg(not(test))]
let scope = AtomScope::Process(RawAtomLifetime::RetainedFlyString);
- Self::new(scope)
+ Self::new(scope, process)
+ }
+
+ /// As a live engine's outside tests: the process's atoms, which the selectors it parses name too.
+ #[cfg(test)]
+ pub(super) fn for_process_engine(process: &Arc<ProcessAtoms>) -> Self {
+ Self::new(AtomScope::Process(RawAtomLifetime::RetainedFlyString), process)
}
#[cfg(test)]
- pub(super) fn for_test() -> Self {
- Self::new(AtomScope::Process(RawAtomLifetime::OpaqueTestToken))
+ pub(super) fn for_test(process: &Arc<ProcessAtoms>) -> Self {
+ Self::new(AtomScope::Process(RawAtomLifetime::OpaqueTestToken), process)
}
- fn new(scope: AtomScope) -> Self {
+ fn new(scope: AtomScope, process: &Arc<ProcessAtoms>) -> Self {
Self {
- raw: HashMap::new(),
- cpp_memoized_raws: HashSet::new(),
- qualified: HashMap::new(),
+ held: Vec::new(),
+ held_count: 0,
scope,
- published: HashMap::new(),
- #[cfg(test)]
- available: BTreeSet::new(),
+ process: Arc::clone(process),
#[cfg(test)]
- next: 0,
+ own: matches!(scope, AtomScope::Document).then(Arc::default),
+ published: HashMap::new(),
sweep_at: 256,
}
}
- pub(super) fn intern_raw(&mut self, raw: usize) -> StyleAtomID {
- if let Some(&atom) = self.raw.get(&raw) {
- return atom;
+ /// Interns the names of an engine that holds none of the process's yet in `process`, the table of the process
+ /// style it shares.
+ pub(super) fn share_process_atoms(&mut self, process: &Arc<ProcessAtoms>) {
+ assert!(
+ Arc::ptr_eq(&self.process, process) || !self.is_process_global() || self.held_count == 0,
+ "an engine shares the process's atoms before it interns any"
+ );
+ self.process = Arc::clone(process);
+ }
+
+ /// The table the atoms are interned in, where they are the process's.
+ pub(super) fn process_atoms(&self) -> &Arc<ProcessAtoms> {
+ &self.process
+ }
+
+ /// The table the document's atoms are numbers of.
+ fn table(&self) -> &Arc<ProcessAtoms> {
+ #[cfg(test)]
+ if let Some(own) = &self.own {
+ return own;
}
- let atom = match self.scope {
+ &self.process
+ }
+
+ /// How raw identities of names are held.
+ fn raw_lifetime(&self) -> RawAtomLifetime {
+ match self.scope {
#[cfg(test)]
- AtomScope::Document => self.allocate_document_atom(),
- AtomScope::Process(lifetime) => global_atoms()
- .lock()
- .expect("process-global style atom lock is poisoned")
- .acquire_raw(raw, lifetime),
- };
- self.raw.insert(raw, atom);
- atom
+ AtomScope::Document => RawAtomLifetime::OpaqueTestToken,
+ AtomScope::Process(lifetime) => lifetime,
+ }
}
- pub(super) fn intern_cpp_raw(&mut self, raw: usize) -> StyleAtomID {
- self.cpp_memoized_raws.insert(raw);
- self.intern_raw(raw)
+ fn holds(&self, atom: StyleAtomID) -> bool {
+ let word = (atom.0 / HELD_BITS_PER_WORD) as usize;
+ self.held
+ .get(word)
+ .is_some_and(|word| word & (1 << (atom.0 % HELD_BITS_PER_WORD)) != 0)
}
- pub(super) fn intern_qualified(&mut self, namespace: StyleAtomID, name: StyleAtomID) -> StyleAtomID {
- let key = (namespace.0, name.0);
- if let Some(&atom) = self.qualified.get(&key) {
+ /// Note that the document took a reference to `atom`.
+ fn note_held(&mut self, atom: StyleAtomID) {
+ let word = (atom.0 / HELD_BITS_PER_WORD) as usize;
+ if self.held.len() <= word {
+ self.held.resize(word + 1, 0);
+ }
+ self.held[word] |= 1 << (atom.0 % HELD_BITS_PER_WORD);
+ self.held_count += 1;
+ }
+
+ /// Every atom the document holds a reference to, by increasing number.
+ fn held_atoms(&self) -> impl Iterator<Item = StyleAtomID> + '_ {
+ self.held.iter().enumerate().flat_map(|(index, &word)| {
+ let base = u32::try_from(index).expect("style atom numbers are u32") * HELD_BITS_PER_WORD;
+ (0..HELD_BITS_PER_WORD)
+ .filter(move |bit| word & (1 << bit) != 0)
+ .map(move |bit| StyleAtomID(base + bit))
+ })
+ }
+
+ /// The atom of `key` the document holds a reference to, read without the table's lock.
+ fn held_without_lock(
+ &self,
+ index: &AtomIndex,
+ key: u64,
+ kind_of_key: impl Fn(&AtomCell) -> bool,
+ ) -> Option<StyleAtomID> {
+ let atom = index.get(key)?;
+ if !self.holds(atom) {
+ return None;
+ }
+ // NB: The document's reference keeps the cell as it is. The index may have answered for a key that just lost
+ // its atom, with a number another name took since.
+ let cell = self.table().shared.cells.get(atom)?;
+ (cell.key.load(Ordering::Acquire) == key && kind_of_key(cell)).then_some(atom)
+ }
+
+ pub(super) fn intern_raw(&mut self, raw: usize) -> StyleAtomID {
+ if let Some(atom) = self.held_without_lock(&self.table().shared.raw, raw as u64, |cell| {
+ cell.raw_lifetime().is_some()
+ }) {
return atom;
}
- let atom = match self.scope {
- #[cfg(test)]
- AtomScope::Document => self.allocate_document_atom(),
- AtomScope::Process(_) => global_atoms()
- .lock()
- .expect("process-global style atom lock is poisoned")
- .acquire_qualified(namespace, name),
+ let atom = {
+ let mut table = self.table().lock();
+ match table.shared.raw.get(raw as u64) {
+ Some(atom) if self.holds(atom) => return atom,
+ _ => table.acquire_raw(raw, self.raw_lifetime()),
+ }
};
- self.qualified.insert(key, atom);
+ self.note_held(atom);
atom
}
- #[cfg(test)]
- fn allocate_document_atom(&mut self) -> StyleAtomID {
- if let Some(atom) = self.available.pop_first() {
- return StyleAtomID(atom);
+ pub(super) fn intern_qualified(&mut self, namespace: StyleAtomID, name: StyleAtomID) -> StyleAtomID {
+ let key = qualified_key(namespace, name);
+ if let Some(atom) = self.held_without_lock(&self.table().shared.qualified, key, |cell| {
+ cell.kind.load(Ordering::Acquire) == ATOM_KIND_QUALIFIED
+ }) {
+ return atom;
}
- self.next = self.next.checked_add(1).expect("document style atom space exhausted");
- StyleAtomID(self.next)
+ let atom = {
+ let mut table = self.table().lock();
+ match table.shared.qualified.get(key) {
+ Some(atom) if self.holds(atom) => return atom,
+ _ => table.acquire_qualified(namespace, name),
+ }
+ };
+ self.note_held(atom);
+ atom
}
/// Whether the atoms are the process's, which every other engine's also are.
@@ -350,7 +852,7 @@ impl DocumentAtoms {
}
pub(super) fn should_sweep(&self) -> bool {
- self.raw.len() + self.qualified.len() >= self.sweep_at
+ self.held_count >= self.sweep_at
}
/// Keep `atom` out of every sweep until the publication naming it is cleared or replaced.
@@ -381,13 +883,16 @@ impl DocumentAtoms {
S: BuildHasher,
{
live.extend(self.published.keys().copied());
- for (&(namespace, name), &qualified) in &self.qualified {
- if live.contains(&qualified) {
- if namespace != 0 {
- live.insert(StyleAtomID(namespace));
+ let shared = &self.table().shared;
+ for atom in self.held_atoms() {
+ if live.contains(&atom)
+ && let Some(AtomKey::Qualified(namespace, name)) = shared.key_of(atom)
+ {
+ if !namespace.is_none() {
+ live.insert(namespace);
}
- if name != 0 {
- live.insert(StyleAtomID(name));
+ if !name.is_none() {
+ live.insert(name);
}
}
}
@@ -400,96 +905,64 @@ impl DocumentAtoms {
where
S: BuildHasher,
{
- let mut reclaimable = self
- .raw
- .values()
- .chain(self.qualified.values())
- .copied()
- .filter(|atom| !live.contains(atom))
- .collect::<Vec<_>>();
- reclaimable.sort_unstable_by_key(|atom| atom.0);
- reclaimable
+ self.held_atoms().filter(|atom| !live.contains(atom)).collect()
}
/// The raw identity of the name each of `atoms` was interned from, a qualified atom's being its name's, or none
/// where one was interned from text rather than from a name.
pub(super) fn raw_identities_of(&self, atoms: impl IntoIterator<Item = StyleAtomID>) -> Option<Vec<usize>> {
- let mut wanted: HashSet<StyleAtomID> = atoms.into_iter().collect();
- for (&(_, name), atom) in &self.qualified {
- if wanted.remove(atom) {
- wanted.insert(StyleAtomID(name));
- }
- }
- let mut raws = Vec::with_capacity(wanted.len());
- for (&raw, atom) in &self.raw {
- if raw < TEXT_KEY_FLOOR && wanted.remove(atom) {
- raws.push(raw);
- }
+ let shared = &self.table().shared;
+ atoms
+ .into_iter()
+ .map(|atom| {
+ let atom = match shared.key_of(atom) {
+ Some(AtomKey::Qualified(_, local)) => local,
+ _ => atom,
+ };
+ match shared.key_of(atom) {
+ Some(AtomKey::Raw(raw)) if raw < TEXT_KEY_FLOOR => Some(raw),
+ _ => None,
+ }
+ })
+ .collect()
+ }
+
+ /// The name `atom` was interned from, a qualified atom's being its name's, for a diagnostic to
+ /// show, or none where it was interned from text or the table holds no names.
+ pub(super) fn name_of(&self, atom: StyleAtomID) -> Option<String> {
+ if !matches!(self.scope, AtomScope::Process(RawAtomLifetime::RetainedFlyString)) {
+ return None;
}
- wanted.is_empty().then_some(raws)
+ let name = self.process.text(atom)?;
+ Some(String::from_utf16_lossy(&name.to_utf16()))
}
/// A sweep marks everything live whatever it reclaims, so the next one waits until the table has doubled: its cost
/// spreads over as many new atoms as this one left live.
fn schedule_next_sweep(&mut self) {
- self.sweep_at = (2 * (self.raw.len() + self.qualified.len())).max(256);
+ self.sweep_at = (2 * self.held_count).max(256);
}
pub(super) fn finish_sweep(&mut self, reclaimable: &[StyleAtomID]) -> Vec<ReclaimedStyleAtom> {
- if reclaimable.is_empty() {
- self.schedule_next_sweep();
- return Vec::new();
- }
- let reclaimable = reclaimable.iter().copied().collect::<HashSet<_>>();
- let mut raw = Vec::new();
- self.raw.retain(|&identity, &mut atom| {
- if !reclaimable.contains(&atom) {
- return true;
- }
- raw.push((identity, atom));
- false
- });
- let mut qualified = Vec::new();
- self.qualified.retain(|&key, &mut atom| {
- if !reclaimable.contains(&atom) {
- return true;
- }
- qualified.push((key, atom));
- false
- });
-
- match self.scope {
- #[cfg(test)]
- AtomScope::Document => {
- self.available.extend(reclaimable.iter().map(|atom| atom.0));
- }
- AtomScope::Process(_) => {
- let mut global = global_atoms()
- .lock()
- .expect("process-global style atom lock is poisoned");
- for &(key, atom) in &qualified {
- global.release_qualified(key, atom);
- }
- for &(identity, atom) in &raw {
- global.release_raw(identity, atom);
- }
- }
+ let reclaimed = {
+ let mut table = self.table().lock();
+ reclaimable
+ .iter()
+ .map(|&atom| {
+ let raw = match table.key_of(atom) {
+ Some(AtomKey::Raw(raw)) => raw,
+ _ => 0,
+ };
+ table.release(atom);
+ ReclaimedStyleAtom { raw, atom }
+ })
+ .collect::<Vec<_>>()
+ };
+ for &atom in reclaimable {
+ self.held[(atom.0 / HELD_BITS_PER_WORD) as usize] &= !(1 << (atom.0 % HELD_BITS_PER_WORD));
}
-
+ self.held_count -= reclaimable.len();
self.schedule_next_sweep();
- let mut reclaimed = raw
- .into_iter()
- .map(|(raw, atom)| ReclaimedStyleAtom {
- raw: if self.cpp_memoized_raws.remove(&raw) { raw } else { 0 },
- atom,
- })
- .chain(
- qualified
- .into_iter()
- .map(|(_, atom)| ReclaimedStyleAtom { raw: 0, atom }),
- )
- .collect::<Vec<_>>();
- reclaimed.sort_unstable_by_key(|entry| entry.atom.0);
reclaimed
}
}
@@ -497,27 +970,20 @@ impl DocumentAtoms {
/// A fork of a document holds its own document reference to each atom the document holds.
impl Clone for DocumentAtoms {
fn clone(&self) -> Self {
- if matches!(self.scope, AtomScope::Process(_)) {
- let mut global = global_atoms()
- .lock()
- .expect("process-global style atom lock is poisoned");
- for (&key, &atom) in &self.qualified {
- global.reference_qualified(key, atom);
- }
- for (&raw, &atom) in &self.raw {
- global.reference_raw(raw, atom);
+ {
+ let mut table = self.table().lock();
+ for atom in self.held_atoms() {
+ table.reference(atom);
}
}
Self {
- raw: self.raw.clone(),
- cpp_memoized_raws: self.cpp_memoized_raws.clone(),
- qualified: self.qualified.clone(),
+ held: self.held.clone(),
+ held_count: self.held_count,
scope: self.scope,
- published: self.published.clone(),
- #[cfg(test)]
- available: self.available.clone(),
+ process: Arc::clone(&self.process),
#[cfg(test)]
- next: self.next.clone(),
+ own: self.own.clone(),
+ published: self.published.clone(),
sweep_at: self.sweep_at,
}
}
@@ -525,17 +991,9 @@ impl Clone for DocumentAtoms {
impl Drop for DocumentAtoms {
fn drop(&mut self) {
- if !matches!(self.scope, AtomScope::Process(_)) {
- return;
- }
- let mut global = global_atoms()
- .lock()
- .expect("process-global style atom lock is poisoned");
- for (&key, &atom) in &self.qualified {
- global.release_qualified(key, atom);
- }
- for (&raw, &atom) in &self.raw {
- global.release_raw(raw, atom);
+ let mut table = self.table().lock();
+ for atom in self.held_atoms() {
+ table.release(atom);
}
}
}
@@ -544,13 +1002,65 @@ impl Drop for DocumentAtoms {
mod tests {
use super::*;
- static GLOBAL_ATOM_TEST_LOCK: Mutex<()> = Mutex::new(());
-
fn prepare_sweep(atoms: &DocumentAtoms, live: &mut HashSet<StyleAtomID>) -> Vec<StyleAtomID> {
atoms.mark_sweep_dependencies(live);
atoms.reclaimable_for_sweep(live)
}
+ fn lease_name(process: &Arc<ProcessAtoms>, text: &str) -> AtomLease {
+ let name = ak::Utf16FlyString::from_utf16(&text.encode_utf16().collect::<Vec<_>>());
+ // SAFETY: The fly string is live for the call, and the lease takes a reference of its own.
+ unsafe { AtomLease::acquire_raw(process, name.raw_identity()) }
+ }
+
+ #[test]
+ fn a_name_is_lowercased_to_the_atom_its_lowercase_form_has() {
+ let process = Arc::default();
+ let mixed = lease_name(&process, "FooBar");
+ let lowercase = lease_name(&process, "foobar");
+ assert_ne!(mixed.atom(), lowercase.atom());
+ assert_eq!(process.ascii_lowercase(mixed.atom()), lowercase.atom());
+ assert_eq!(process.ascii_lowercase(lowercase.atom()), lowercase.atom());
+ let text = process.text(mixed.atom()).unwrap();
+ assert_eq!(String::from_utf16_lossy(&text.to_utf16()), "FooBar");
+ }
+
+ #[test]
+ fn a_lowercase_form_lives_as_long_as_the_name_it_folds() {
+ let process = Arc::default();
+ let mixed = lease_name(&process, "ClassName");
+ let lowercase = process.ascii_lowercase(mixed.atom());
+ assert_ne!(lowercase, mixed.atom());
+ // Nothing but the mixed-case entry references the lowercase form, which a later lease still finds.
+ let again = lease_name(&process, "classname");
+ assert_eq!(again.atom(), lowercase);
+ drop(again);
+ let mixed_atom = mixed.atom();
+ drop(mixed);
+ // Both numbers are free again, so the next two names take them.
+ let first = lease_name(&process, "x");
+ let second = lease_name(&process, "y");
+ let mut taken = [first.atom().0, second.atom().0];
+ taken.sort_unstable();
+ let mut freed = [mixed_atom.0, lowercase.0];
+ freed.sort_unstable();
+ assert_eq!(taken, freed);
+ }
+
+ #[test]
+ fn leases_keep_each_distinct_atom_until_they_drop() {
+ let process = Arc::default();
+ let name = lease_name(&process, "kept");
+ let atom = name.atom();
+ let leases = process.lease([atom, atom, StyleAtomID::NONE]);
+ assert!(leases.holds(atom));
+ let copy = leases.clone();
+ drop((name, leases));
+ assert!(process.text(atom).is_some());
+ drop(copy);
+ assert!(process.text(atom).is_none());
+ }
+
#[test]
fn synthetic_text_keys_do_not_retain_fly_strings() {
assert_eq!(
@@ -565,24 +1075,24 @@ mod tests {
#[test]
fn process_atoms_share_and_recycle_after_the_last_document() {
- let _test_lock = GLOBAL_ATOM_TEST_LOCK.lock().unwrap();
+ let process = Arc::default();
let first_atom;
{
- let mut first = DocumentAtoms::for_test();
- let mut second = DocumentAtoms::for_test();
+ let mut first = DocumentAtoms::for_test(&process);
+ let mut second = DocumentAtoms::for_test(&process);
first_atom = first.intern_raw(0x1234);
assert_eq!(second.intern_raw(0x1234), first_atom);
assert_ne!(second.intern_raw(0x5678), first_atom);
}
- let mut later = DocumentAtoms::for_test();
+ let mut later = DocumentAtoms::for_test(&process);
assert_eq!(later.intern_raw(0x9abc), first_atom);
}
#[test]
fn process_atoms_wait_for_every_raw_and_qualified_owner() {
- let _test_lock = GLOBAL_ATOM_TEST_LOCK.lock().unwrap();
- let mut first = DocumentAtoms::for_test();
- let mut second = DocumentAtoms::for_test();
+ let process = Arc::default();
+ let mut first = DocumentAtoms::for_test(&process);
+ let mut second = DocumentAtoms::for_test(&process);
let namespace = first.intern_raw(0x1000);
let name = first.intern_raw(0x2000);
let qualified = first.intern_qualified(namespace, name);
@@ -597,7 +1107,7 @@ mod tests {
let second_reclaimable = prepare_sweep(&second, &mut HashSet::new());
second.finish_sweep(&second_reclaimable);
- let mut later = DocumentAtoms::for_test();
+ let mut later = DocumentAtoms::for_test(&process);
assert_eq!(later.intern_raw(0x3000), namespace);
assert_eq!(later.intern_raw(0x4000), name);
assert_eq!(later.intern_qualified(namespace, name), qualified);
@@ -605,9 +1115,9 @@ mod tests {
#[test]
fn qualified_atoms_share_the_global_identity_space() {
- let _test_lock = GLOBAL_ATOM_TEST_LOCK.lock().unwrap();
- let mut first = DocumentAtoms::for_test();
- let mut second = DocumentAtoms::for_test();
+ let process = Arc::default();
+ let mut first = DocumentAtoms::for_test(&process);
+ let mut second = DocumentAtoms::for_test(&process);
let namespace = first.intern_raw(0x1000);
let name = first.intern_raw(0x2000);
assert_eq!(second.intern_raw(0x1000), namespace);
@@ -620,7 +1130,7 @@ mod tests {
#[test]
fn qualified_atoms_keep_their_component_atoms_live() {
- let mut atoms = DocumentAtoms::for_live_engine();
+ let mut atoms = DocumentAtoms::for_live_engine(&Arc::default());
let namespace = atoms.intern_raw(0x1000);
let name = atoms.intern_raw(0x2000);
let qualified = atoms.intern_qualified(namespace, name);
@@ -631,15 +1141,15 @@ mod tests {
#[test]
fn a_published_name_survives_a_sweep_that_no_other_owner_reaches() {
- let mut atoms = DocumentAtoms::for_live_engine();
- let referenced = atoms.intern_cpp_raw(0x1000);
- let other = atoms.intern_cpp_raw(0x2000);
+ let mut atoms = DocumentAtoms::for_live_engine(&Arc::default());
+ let referenced = atoms.intern_raw(0x1000);
+ let other = atoms.intern_raw(0x2000);
atoms.retain_published(referenced);
assert_eq!(prepare_sweep(&atoms, &mut HashSet::new()), [other]);
// The publication is replaced by one naming a different name, so the old one becomes
// reclaimable and its number can be issued again.
- let replacement = atoms.intern_cpp_raw(0x3000);
+ let replacement = atoms.intern_raw(0x3000);
atoms.retain_published(replacement);
atoms.release_published(referenced);
let reclaimable = prepare_sweep(&atoms, &mut HashSet::new());
@@ -650,8 +1160,8 @@ mod tests {
#[test]
fn two_publications_of_one_name_each_keep_it() {
- let mut atoms = DocumentAtoms::for_live_engine();
- let referenced = atoms.intern_cpp_raw(0x1000);
+ let mut atoms = DocumentAtoms::for_live_engine(&Arc::default());
+ let referenced = atoms.intern_raw(0x1000);
atoms.retain_published(referenced);
atoms.retain_published(referenced);
atoms.release_published(referenced);
@@ -662,10 +1172,10 @@ mod tests {
#[test]
fn document_atoms_reuse_reclaimed_identities_in_sorted_order() {
- let mut atoms = DocumentAtoms::for_live_engine();
- let first = atoms.intern_cpp_raw(0x1000);
+ let mut atoms = DocumentAtoms::for_live_engine(&Arc::default());
+ let first = atoms.intern_raw(0x1000);
let second = atoms.intern_raw(0x2000);
- let third = atoms.intern_cpp_raw(0x3000);
+ let third = atoms.intern_raw(0x3000);
let reclaimable = prepare_sweep(&atoms, &mut HashSet::from([second]));
assert_eq!(reclaimable, [first, third]);
assert_eq!(
@@ -686,16 +1196,60 @@ mod tests {
}
#[test]
- fn compiler_only_atoms_do_not_claim_a_cpp_memo_entry() {
- let mut atoms = DocumentAtoms::for_live_engine();
- let atom = atoms.intern_raw(0x1000);
- let reclaimable = prepare_sweep(&atoms, &mut HashSet::new());
- assert_eq!(atoms.finish_sweep(&reclaimable), [ReclaimedStyleAtom { raw: 0, atom }]);
+ fn the_index_finds_what_a_table_holds_through_churn_and_growth() {
+ let process = Arc::<ProcessAtoms>::default();
+ let mut atoms = DocumentAtoms::for_test(&process);
+ // Far more names than the first slots hold over time, few at once: the slots are laid out again in place.
+ for round in 0..64_usize {
+ let names: Vec<_> = (0..256)
+ .map(|offset| atoms.intern_raw(0x10_0000 + round * 256 + offset))
+ .collect();
+ assert_eq!(atoms.intern_raw(0x10_0000 + round * 256 + 7), names[7]);
+ let reclaimable = prepare_sweep(&atoms, &mut HashSet::new());
+ atoms.finish_sweep(&reclaimable);
+ }
+ assert_eq!(process.shared.raw.current.load(Ordering::Relaxed), 0);
+ // Many names at once grow them, and each name keeps its atom.
+ let names: Vec<_> = (0..10_000).map(|offset| atoms.intern_raw(0x20_0000 + offset)).collect();
+ for (offset, &atom) in names.iter().enumerate() {
+ assert_eq!(atoms.intern_raw(0x20_0000 + offset), atom);
+ assert_eq!(process.shared.raw.get(0x20_0000 + offset as u64), Some(atom));
+ }
+ }
+
+ #[test]
+ fn documents_on_several_threads_read_each_name_as_the_one_atom_it_is() {
+ let process = Arc::<ProcessAtoms>::default();
+ let threads: Vec<_> = (0..4_usize)
+ .map(|thread| {
+ let process = Arc::clone(&process);
+ std::thread::spawn(move || {
+ let mut atoms = DocumentAtoms::for_test(&process);
+ for round in 0..200_usize {
+ // Names every thread shares, and names that come and go in this thread alone.
+ for offset in 0..64 {
+ let shared = 0x10_0000 + offset;
+ let atom = atoms.intern_raw(shared);
+ assert_eq!(process.shared.key_of(atom), Some(AtomKey::Raw(shared)));
+ assert_eq!(atoms.intern_raw(shared), atom);
+ let own = 0x100_0000 * (thread + 1) + round * 64 + offset;
+ let atom = atoms.intern_raw(own);
+ assert_eq!(process.shared.key_of(atom), Some(AtomKey::Raw(own)));
+ }
+ let reclaimable = prepare_sweep(&atoms, &mut HashSet::new());
+ atoms.finish_sweep(&reclaimable);
+ }
+ })
+ })
+ .collect();
+ for thread in threads {
+ thread.join().expect("the thread keeps its names apart");
+ }
}
#[test]
fn repeated_churn_keeps_the_document_identity_space_bounded() {
- let mut atoms = DocumentAtoms::for_live_engine();
+ let mut atoms = DocumentAtoms::for_live_engine(&Arc::default());
let mut highest = 0;
for round in 0..8 {
for offset in 0..256 {
diff --git a/Libraries/LibWeb/Rust/src/css/style/boundary.rs b/Libraries/LibWeb/Rust/src/css/style/boundary.rs
index 3e65acba143..c83daa4a7b7 100644
--- a/Libraries/LibWeb/Rust/src/css/style/boundary.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/boundary.rs
@@ -7,18 +7,19 @@
//! The host's plain writes and reads of a document's style engine, one row each in the table below. A write row names
//! the [`StyleChange`] its entry queues for the document's render state, which applies the change in the order the host
//! made them; a read is answered in place while the host waits. A row of `writes` or `reads` is exported as
-//! `style_engine_` and its name, and does what the engine method of that name does unless the row says otherwise. A row
-//! of `unexported_writes` names a change only Rust queues, so it has no entry.
+//! `style_engine_` and its name, and does what the engine method of that name does unless the row says otherwise.
//!
//! cbindgen does not expand macros, so the C++ declarations of the entries are written by hand in
//! `CSS/StyleEngineBridge.h`, and a test checks each against its row.
use super::ReplacedContentInput;
use super::StyleEngine;
+use super::animations::HeldAppliedAnimationDefinition;
use super::bridge::{ElementBoxKind, FfiAppliedAnimationDefinition, borrow};
+use super::engine_calls::EngineWrite;
use super::engine_calls::with_engine;
use super::index::StyleAtomID;
-use super::program::{CascadeLayerID, SheetID};
+use super::pipeline::rule_store::{CascadeLayerID, SheetID};
use super::tree::{StyleNodeID, TableSpans, TreeScopeID};
use crate::abort_on_panic;
use crate::css::css_string::CssString;
@@ -68,6 +69,7 @@ macro_rules! carried {
// SAFETY: An entry carries what its caller lends live for the call.
carried! {
+ (): () as "void" = |value| value;
bool: bool as "bool" = |value| value;
u8: u8 as "u8" = |value| value;
u32: u32 as "u32" = |value| value;
@@ -91,8 +93,9 @@ carried! {
|span| unsafe { borrow(span.data, span.size) }.iter().copied().map(StyleAtomID).collect();
Box<[StyleNodeID]>: FfiSpan<u32> as "ReadonlySpan<StyleNodeID>" =
|span| unsafe { borrow(span.data, span.size) }.iter().copied().filter_map(StyleNodeID::from_raw).collect();
- Box<[FfiAppliedAnimationDefinition]>: FfiSpan<FfiAppliedAnimationDefinition>
- as "ReadonlySpan<FfiAppliedAnimationDefinition>" = |span| unsafe { borrow(span.data, span.size) }.into();
+ Box<[HeldAppliedAnimationDefinition]>: FfiSpan<FfiAppliedAnimationDefinition>
+ as "ReadonlySpan<FfiAppliedAnimationDefinition>" =
+ |span| unsafe { borrow(span.data, span.size) }.iter().map(|&definition| unsafe { HeldAppliedAnimationDefinition::retained(definition) }).collect();
FfiSpan<u16>: FfiSpan<u16> as "ReadonlySpan<u16>" = |span| span;
FfiSpan<u32>: FfiSpan<u32> as "ReadonlySpan<StyleNodeID>" = |span| span;
}
@@ -120,6 +123,109 @@ macro_rules! required {
required!(StyleNodeID, SheetID);
+/// A record the host holds, which the change holds a reference to of its own. A change naming none has nothing to apply.
+impl Carried for std::sync::Arc<super::pipeline::Record> {
+ type Ffi = *const std::ffi::c_void;
+ type Held = Option<Self>;
+ #[cfg(test)]
+ const CPP: &'static str = "void const*";
+
+ unsafe fn carry(record: *const std::ffi::c_void) -> Option<Self> {
+ // SAFETY: The host holds a reference to the record for the call.
+ unsafe { super::bridge::retain_host_record(record) }
+ }
+
+ fn applied(held: Option<Self>) -> Option<Self> {
+ held
+ }
+}
+
+/// The record a host's element installed, or none, which the change holds a reference to of its own.
+pub(crate) struct HeldHostRecord(Option<std::sync::Arc<super::pipeline::Record>>);
+
+impl Carried for HeldHostRecord {
+ type Ffi = *const std::ffi::c_void;
+ type Held = Self;
+ #[cfg(test)]
+ const CPP: &'static str = "void const*";
+
+ unsafe fn carry(record: *const std::ffi::c_void) -> Self {
+ // SAFETY: The host holds a reference to the record for the call.
+ Self(unsafe { super::bridge::retain_host_record(record) })
+ }
+
+ fn applied(held: Self) -> Option<Self> {
+ Some(held)
+ }
+}
+
+/// The record a host's pseudo-element let go of as it installed another, or none, which the change holds a reference
+/// to until it applies: what the render side reads of the pseudo-element by its identity until then, as the layout
+/// node's move, stays the record it names.
+pub(crate) struct ReleasedHostRecord(
+ #[allow(dead_code, reason = "held until the change applies")] Option<std::sync::Arc<super::pipeline::Record>>,
+);
+
+impl Carried for ReleasedHostRecord {
+ type Ffi = *const std::ffi::c_void;
+ type Held = Self;
+ #[cfg(test)]
+ const CPP: &'static str = "void const*";
+
+ unsafe fn carry(record: *const std::ffi::c_void) -> Self {
+ // SAFETY: The host holds a reference to the record for the call.
+ Self(unsafe { super::bridge::retain_host_record(record) })
+ }
+
+ fn applied(held: Self) -> Option<Self> {
+ Some(held)
+ }
+}
+
+/// The fills of the faces that loaded into the frozen cascades that waited on them. The host lends each cascade a load
+/// filled faces into followed by the cascade the newer @font-face table resolves its request to, both live for the
+/// call, and the change carries what filling the first toward the second takes.
+pub(crate) struct LoadedFontFaceFills {
+ /// The addresses of the cascades the fills fill in, as the styles naming them hold them.
+ pub(crate) font_lists: Box<[u64]>,
+ pub(crate) fills: Vec<libgfx_rust::font::FrozenFontFills>,
+}
+
+impl Carried for LoadedFontFaceFills {
+ type Ffi = FfiSpan<u64>;
+ type Held = Self;
+ #[cfg(test)]
+ const CPP: &'static str = "ReadonlySpan<u64>";
+
+ unsafe fn carry(span: FfiSpan<u64>) -> Self {
+ // SAFETY: The host lends the addresses for the call.
+ let addresses = unsafe { borrow(span.data, span.size) };
+ let mut font_lists = Vec::new();
+ let mut fills = Vec::new();
+ for &[list, resolved] in addresses.as_chunks::<2>().0 {
+ // SAFETY: The host keeps both cascades live for the call.
+ let fill = unsafe {
+ libgfx_rust::font::FrozenFontFills::toward_cascade(
+ list as usize as *const std::ffi::c_void,
+ resolved as usize as *const std::ffi::c_void,
+ )
+ };
+ if let Some(fill) = fill {
+ font_lists.push(list);
+ fills.push(fill);
+ }
+ }
+ Self {
+ font_lists: font_lists.into(),
+ fills,
+ }
+ }
+
+ fn applied(held: Self) -> Option<Self> {
+ Some(held)
+ }
+}
+
macro_rules! style_boundary {
(@apply $engine:ident $method:ident($($value:ident),*)) => {
$engine.$method($($value),*)
@@ -129,17 +235,16 @@ macro_rules! style_boundary {
};
(
|$engine:ident|
- writes { $($write:ident => $Change:ident $({ $($field:ident: $type:ty),+ })? $(=> $apply:expr)?;)+ }
- unexported_writes {
- $($unexported_write:ident => $UnexportedChange:ident
- $({ $($unexported_field:ident: $unexported_type:ty),+ })? $(=> $unexported_apply:expr)?;)+
+ writes {
+ $($write:ident => $(@$published:ident)? $Change:ident $({ $($field:ident: $type:ty),+ })? $(=> $apply:expr)?;)+
}
+ |$host:ident|
+ host_writes { $($host_write:ident { $($host_field:ident: $host_type:ty),+ } => $host_apply:expr;)+ }
reads { $($read:ident($($argument:ident: $argument_type:ty),*) -> $answer:ty $(=> $ask:expr)?;)+ }
) => {
/// A write of the host or of Rust to the document's style engine, which the render state applies to it.
pub(crate) enum StyleChange {
$($Change $({ $($field: <$type as Carried>::Held),+ })?,)+
- $($UnexportedChange $({ $($unexported_field: <$unexported_type as Carried>::Held),+ })?,)+
}
impl StyleChange {
@@ -149,14 +254,6 @@ macro_rules! style_boundary {
$($(let Some($field) = <$type>::applied($field) else { return };)+)?
style_boundary!(@apply $engine $write($($($field),+)?) $($apply)?);
})+
- $(Self::$UnexportedChange $({ $($unexported_field),+ })? => {
- $($(
- let Some($unexported_field) = <$unexported_type>::applied($unexported_field) else { return };
- )+)?
- style_boundary!(
- @apply $engine $unexported_write($($($unexported_field),+)?) $($unexported_apply)?
- );
- })+
}
}
}
@@ -167,11 +264,26 @@ macro_rules! style_boundary {
abort_on_panic(|| {
// SAFETY: Guaranteed by the caller.
let change = StyleChange::$Change $({ $($field: unsafe { <$type>::carry($field) }),+ })?;
+ // NB: A change that reads the projection rows as the host wrote them takes what it wrote first.
+ $(let _ = stringify!($published); host.publish_element_writes();)?
host.queue_change(ArenaChange::Style(change));
});
}
)+
+ $(
+ #[unsafe(export_name = concat!("style_engine_", stringify!($host_write)))]
+ pub unsafe extern "C" fn $host_write($host: &DocumentHost $(, $host_field: <$host_type as Carried>::Ffi)+) {
+ abort_on_panic(|| {
+ // SAFETY: Guaranteed by the caller.
+ $(let Some($host_field) = <$host_type>::applied(unsafe { <$host_type>::carry($host_field) }) else {
+ return;
+ };)+
+ $host_apply
+ });
+ }
+ )+
+
$(
#[unsafe(export_name = concat!("style_engine_", stringify!($read)))]
pub unsafe extern "C" fn $read(
@@ -191,13 +303,19 @@ macro_rules! style_boundary {
#[cfg(test)]
fn cpp_declarations() -> impl Iterator<Item = String> {
let writes = [$(("void", stringify!($write), "", vec![$($((<$type>::CPP, stringify!($field))),+)?])),+];
+ let host_writes = [$((
+ "void",
+ stringify!($host_write),
+ "",
+ vec![$((<$host_type>::CPP, stringify!($host_field))),+],
+ )),+];
let reads = [$((
<$answer>::CPP,
stringify!($read),
", BegunRead const*",
vec![$((<$argument_type>::CPP, stringify!($argument))),*],
)),+];
- writes.into_iter().chain(reads).map(|(answer, entry, read, parameters)| {
+ writes.into_iter().chain(host_writes).chain(reads).map(|(answer, entry, read, parameters)| {
let parameters: String = parameters.iter().map(|(cpp, name)| format!(", {cpp} {name}")).collect();
format!("{answer} style_engine_{entry}(DocumentHost const*{read}{parameters});")
})
@@ -209,12 +327,8 @@ style_boundary! {
|engine|
writes {
- set_pseudo_element_style_deferred => SetPseudoElementStyleDeferred { kind: u8, deferred: bool } =>
- if deferred {
- engine.deferred_pseudo_elements |= 1 << kind;
- } else {
- engine.deferred_pseudo_elements &= !(1 << kind);
- };
+ set_highlight_observing_elements => SetHighlightObservingElements { kind: u8, nodes: Box<[StyleNodeID]> } =>
+ engine.set_highlight_observing_elements(kind, &nodes);
set_fold_id_and_class_name_case => SetFoldIdAndClassNameCase { fold: bool };
set_html_element_namespace => SetHtmlElementNamespace { namespace_atom: StyleAtomID };
mark_relation_only_style_node => MarkRelationOnlyStyleNode { node: StyleNodeID };
@@ -223,19 +337,9 @@ style_boundary! {
unlink_style_node_from_dom_order => UnlinkStyleNodeFromDomOrder {
node: StyleNodeID, parent: Option<StyleNodeID>
};
- retire_text_style_nodes => RetireTextStyleNodes { nodes: Box<[StyleNodeID]> };
- set_slot_assigned_nodes => SetSlotAssignedNodes { slot: StyleNodeID, assigned: Box<[StyleNodeID]> } => {
- engine.set_slot_assigned_nodes(slot, &assigned);
- // Text-only assignments do not carry element tree deltas, but can hide or restore fallback content.
- if let Some(target) = engine.hover_target() {
- engine.set_hover(Some(target));
- }
- };
set_top_layer_elements => SetTopLayerElements { members: Box<[StyleNodeID]> } =>
engine.set_top_layer_elements(&members);
set_text_is_ascii_whitespace => SetTextIsAsciiWhitespace { node: StyleNodeID, value: bool };
- set_text_is_in_user_agent_shadow_tree => SetTextIsInUserAgentShadowTree { node: StyleNodeID, value: bool };
- set_text_is_password_input => SetTextIsPasswordInput { node: StyleNodeID, value: bool };
set_node_dom_paint_facts => SetNodeDomPaintFacts { node: StyleNodeID, facts: u8 };
set_element_unique_node_id => SetElementUniqueNodeId { node: StyleNodeID, unique_node_id: i64 };
set_element_table_spans => SetElementTableSpans {
@@ -246,8 +350,7 @@ style_boundary! {
row_span: u16::try_from(row_span).expect("a row span is clamped to 65534"),
});
set_element_id_name => SetElementIdName { node: StyleNodeID, name: StyleAtomID };
- set_shadow_root => SetShadowRoot { shadow_host: StyleNodeID, shadow_root: StyleNodeID };
- record_environment_change => RecordEnvironmentChange;
+ record_environment_change => RecordEnvironmentChange { changes: u8 };
record_custom_property_registration_change => RecordCustomPropertyRegistrationChange { name: StyleAtomID };
flush => Flush => engine.flush_without_document_root();
finish_sheet_rules_replacement => FinishSheetRulesReplacement { sheet: SheetID, declaration_block: u32 };
@@ -258,62 +361,29 @@ style_boundary! {
sheet: SheetID, tree_scope: TreeScopeID, identity: u64, before: u64, conditions_hold: bool
};
detach_sheet_occurrence => DetachSheetOccurrence { tree_scope: TreeScopeID, identity: u64 };
- set_sheet_kept_for_reattachment => SetSheetKeptForReattachment { sheet: SheetID, kept: bool } =>
- engine.retained.set_sheet_kept_for_reattachment(sheet, kept);
set_sheet_occurrence_conditions => SetSheetOccurrenceConditions {
tree_scope: TreeScopeID, identity: u64, conditions_hold: bool
};
- set_element_part_exposure => SetElementPartExposure { node: StyleNodeID, exposure: StyleAtomID };
- set_element_directionality => SetElementDirectionality { node: StyleNodeID, directionality: StyleAtomID };
- set_element_custom_states => SetElementCustomStates { node: StyleNodeID, states: Box<[StyleAtomID]> } =>
- engine.set_element_custom_states(node, &states);
end_deferred_geometry_transaction_flush => EndDeferredGeometryTransactionFlush;
record_container_query_input => RecordContainerQueryInput { node: StyleNodeID };
- note_children_explicitly_inherit => NoteChildrenExplicitlyInherit { node: StyleNodeID, groups: u32 };
record_derived_element_style_input => RecordDerivedElementStyleInput {
node: StyleNodeID, reaction: u8, inherited_style_groups: u8
};
record_font_input_changes => RecordFontInputChanges {
family_name_lengths: Box<[u32]>, family_name_units: Box<[u16]>, font_lists: Box<[u64]>
} => engine.record_font_input_changes(&family_name_lengths, &family_name_units, &font_lists);
- record_flat_tree_descendant_style_inputs => RecordFlatTreeDescendantStyleInputs {
- root: StyleNodeID, reaction: u8, inherited_style_groups: u8
- };
+ fill_loaded_font_faces => FillLoadedFontFaces { fills: LoadedFontFaceFills };
consume_element_style_input => ConsumeElementStyleInput { node: StyleNodeID };
- note_style_reaction_applied => NoteStyleReactionApplied {
- node: StyleNodeID, reaction: u8, inherited_style_groups_changed: u8, changed_non_inherited_style_groups: u32, facts: u32
- };
- set_element_adjustment_facts => SetElementAdjustmentFacts { node: StyleNodeID, facts: u32 } => {
- let changed = engine.element_adjustment_facts(node) ^ facts;
- engine.set_element_adjustment_facts(node, facts);
- if changed & super::bridge::element_adjustment_fact::RENDERED_IN_TOP_LAYER != 0 {
- engine.set_hover(engine.hover_target());
- }
- };
- set_element_construction_facts => SetElementConstructionFacts { node: StyleNodeID, facts: u32 };
- set_element_box_kind => SetElementBoxKind { node: StyleNodeID, box_kind: ElementBoxKind };
set_element_replaced_content_input => SetElementReplacedContentInput {
node: StyleNodeID, kind: u8, present: u8, values: [u32; 4]
} => engine.set_element_replaced_content_input(node, ReplacedContentInput::from_raw(kind, present, values));
- set_element_heading_level => SetElementHeadingLevel { node: StyleNodeID, level: u8 };
- acknowledge_engine_computed_record => AcknowledgeEngineComputedRecord { node: StyleNodeID };
record_transition_baseline => RecordTransitionBaseline {
- node: StyleNodeID, pseudo_kind: u8, style_record: u64
+ node: StyleNodeID, pseudo_kind: u8, style_record: std::sync::Arc<super::pipeline::Record>
};
release_transition_baselines => ReleaseTransitionBaselines;
- pin_style_record => PinStyleRecord { style_record: u64 };
- unpin_style_record => UnpinStyleRecord { style_record: u64 };
begin_style_record_view_epoch => BeginStyleRecordViewEpoch;
end_style_record_view_epoch => EndStyleRecordViewEpoch;
set_tree_scope_uses_document_sheets => SetTreeScopeUsesDocumentSheets { tree_scope: TreeScopeID };
- set_element_custom_property_names => SetElementCustomPropertyNames {
- node: StyleNodeID, name_atoms: Box<[StyleAtomID]>, uses_unnamed: bool, uses_custom_functions: bool
- } => engine.set_element_custom_property_names(node, &name_atoms, uses_unnamed, uses_custom_functions);
- set_element_animation_names => SetElementAnimationNames { node: StyleNodeID, name_atoms: Box<[StyleAtomID]> } =>
- engine.set_element_animation_names(node, &name_atoms);
- set_element_recomputes_on_environment_move => SetElementRecomputesOnEnvironmentMove {
- node: StyleNodeID, recomputes: bool
- };
set_element_scroll_state => SetElementScrollState {
node: StyleNodeID, stuck: u8, snapped: u8, scrollable: u8, scrolled: u8
};
@@ -324,38 +394,116 @@ style_boundary! {
node: StyleNodeID
};
record_size_container_query_dependents => RecordSizeContainerQueryDependents { container: StyleNodeID };
- evaluate_size_containers_needing_evaluation_after_layout => EvaluateSizeContainersNeedingEvaluationAfterLayout;
- set_element_associated_pseudo_kind => SetElementAssociatedPseudoKind {
- node: StyleNodeID, pseudo_kind_plus_one: u8
- };
+ evaluate_size_containers_needing_evaluation_after_layout => @published
+ EvaluateSizeContainersNeedingEvaluationAfterLayout;
set_counter_style_environment_identity => SetCounterStyleEnvironmentIdentity {
tree_scope: TreeScopeID, identity: u64
};
- set_held_style_record => SetHeldStyleRecord { node: StyleNodeID, style_record: u64 };
- set_held_pseudo_style_record => SetHeldPseudoStyleRecord { node: StyleNodeID, pseudo_kind: u8, style_record: u64 };
+ set_held_style_record => SetHeldStyleRecord { node: StyleNodeID, record: HeldHostRecord }
+ => engine.set_held_style_record(node, record.0);
+ set_held_pseudo_style_record => SetHeldPseudoStyleRecord {
+ node: StyleNodeID, pseudo_kind: u8, style_record: u64, released: ReleasedHostRecord
+ } => {
+ engine.set_held_pseudo_style_record(node, pseudo_kind, style_record);
+ drop(released);
+ };
set_element_css_defined_animations => SetElementCssDefinedAnimations {
- node: StyleNodeID, slot: u8, names: Box<[CssString]>, definitions: Box<[FfiAppliedAnimationDefinition]>
- } => engine.set_element_css_defined_animations(node, slot, names, &definitions);
- set_tree_scope_root => SetTreeScopeRoot { tree_scope: TreeScopeID, root: StyleNodeID };
+ node: StyleNodeID, slot: u8, names: Box<[CssString]>, definitions: Box<[HeldAppliedAnimationDefinition]>
+ } => engine.set_element_css_defined_animations(node, slot, names, definitions);
set_sheet_conditions_hold => SetSheetConditionsHold { sheet: SheetID, conditions_hold: bool };
}
- unexported_writes {
- begin_cold_matching_batch => BeginColdMatchingBatch { root: StyleNodeID };
- begin_adaptive_cold_matching_batch => BeginAdaptiveColdMatchingBatch { root: StyleNodeID };
- end_cold_matching_batch => EndColdMatchingBatch;
- abandon_demanded_records => AbandonDemandedRecords { node: StyleNodeID };
+ // The writes of the host's projection rows, which the host makes on its own thread as its DOM changes, and the
+ // render owner takes at the host's next barrier (see `pipeline::projection::ProjectionWriter`).
+ |host|
+ host_writes {
+ set_shadow_root { shadow_host: StyleNodeID, shadow_root: StyleNodeID } => {
+ let attached = host.engine_memo().projection.borrow_mut().writes().set_shadow_root(shadow_host, shadow_root);
+ host.queue_change(ArenaChange::Engine(EngineWrite::ShadowRoot { host: shadow_host, attached }));
+ };
+ retire_text_style_nodes { nodes: Box<[StyleNodeID]> } => {
+ host.engine_memo().projection.borrow_mut().retire_texts(nodes.iter().copied());
+ host.queue_change(ArenaChange::Engine(EngineWrite::RetireTexts(nodes)));
+ };
+ set_slot_assigned_nodes { slot: StyleNodeID, assigned: Box<[StyleNodeID]> } => {
+ host.engine_memo().projection.borrow_mut().writes().set_slot_assigned_nodes(slot, &assigned);
+ // NB: The hover's chain reads the slot's assigned nodes as the host wrote them.
+ host.publish_element_writes();
+ host.queue_change(ArenaChange::Engine(EngineWrite::SlotAssignedNodes));
+ };
+ set_tree_scope_root { tree_scope: TreeScopeID, root: StyleNodeID } => {
+ // NB: A shadow root is a node selectors reach and nothing publishes features for, so this is where it gets
+ // a row of its own.
+ if tree_scope != TreeScopeID::DOCUMENT {
+ host.engine_memo().projection.borrow_mut().ensure_facts(root);
+ }
+ host.queue_change(ArenaChange::Engine(EngineWrite::TreeScopeRoot { tree_scope, root }));
+ };
+ set_element_part_exposure { node: StyleNodeID, exposure: StyleAtomID } =>
+ host.engine_memo().projection.borrow_mut().writes().set_element_part_exposure(node, exposure);
+ set_element_directionality { node: StyleNodeID, directionality: StyleAtomID } =>
+ host.engine_memo().projection.borrow_mut().writes().set_element_directionality(node, directionality);
+ set_element_custom_states { node: StyleNodeID, states: Box<[StyleAtomID]> } =>
+ host.engine_memo().projection.borrow_mut().writes().set_element_custom_states(node, &states);
+ set_element_heading_level { node: StyleNodeID, level: u8 } =>
+ host.engine_memo().projection.borrow_mut().writes().set_element_heading_level(node, level);
+ set_element_backing_pseudo_kind { node: StyleNodeID, pseudo_kind_plus_one: u8 } => {
+ let memo = host.engine_memo();
+ memo.projection.borrow_mut().writes().set_element_backing_pseudo_kind(node, pseudo_kind_plus_one);
+ if pseudo_kind_plus_one != 0 {
+ memo.note_backing_element(node);
+ }
+ };
+ set_element_adjustment_facts { node: StyleNodeID, facts: u32 } => {
+ let moved = host.engine_memo().projection.borrow_mut().writes().set_element_adjustment_facts(node, facts);
+ // NB: The adjustments read whether the element is rendered in the top layer, where alone its ::backdrop
+ // exists, so a move of it is a style input of the element like a container query answer. The type
+ // facts are fixed from the element's arrival on, and whether it has animations is no input of its
+ // style.
+ if moved & super::bridge::element_adjustment_fact::RENDERED_IN_TOP_LAYER != 0 {
+ host.publish_element_writes();
+ host.queue_change(ArenaChange::Engine(EngineWrite::TopLayerMove { node }));
+ }
+ };
+ set_element_construction_facts { node: StyleNodeID, facts: u32 } =>
+ host.engine_memo().projection.borrow_mut().writes().set_element_construction_facts(node, facts);
+ set_element_box_kind { node: StyleNodeID, box_kind: ElementBoxKind } => {
+ if host.engine_memo().projection.borrow_mut().writes().set_element_box_kind(node, box_kind) {
+ host.publish_element_writes();
+ host.queue_change(ArenaChange::Engine(EngineWrite::BoxKindChange { node }));
+ }
+ };
}
reads {
connected_element_count() -> u32;
- has_suspended_style_pass() -> bool;
+ custom_property_environment_is_engine_made(identity: u64) -> bool =>
+ engine.custom_property_environments.is_engine_made(identity);
pending_transaction_may_affect_layout_geometry() -> bool;
- defer_pending_transaction_for_geometry_read() -> bool;
+ defer_pending_transaction_for_geometry_read() -> ();
begin_deferred_geometry_transaction_flush() -> bool;
has_deferred_geometry_transaction() -> bool;
- match_document(root: Option<StyleNodeID>) -> usize =>
- root.and_then(|root| engine.match_document(root).ok()).unwrap_or(usize::MAX);
+ cold_pass(root: Option<StyleNodeID>, verify: bool, threads: u32) -> u64 => root.map_or(0, |root| engine.run_cold_pass(root, verify, threads));
+ cold_pass_report(index: u32) -> u64 => engine.cold_pass_report(index);
+ live_report(root: Option<StyleNodeID>, verify: bool, index: u32) -> u64 =>
+ root.map_or(0, |root| engine.retained.live_report(root, verify, index));
+ style_counter(index: u32) -> u64 => engine.retained.live_counters.get(index);
+ reset_style_counters() -> bool => {
+ engine.retained.live_counters.reset();
+ true
+ };
+ last_pass_is_full() -> bool => engine.retained.live_counters.last_pass_is_full();
+ last_pass_size(root: Option<StyleNodeID>, changed: bool) -> u32 => root.map_or(0, |root| {
+ let retained = &mut engine.retained;
+ retained.live_counters.last_pass_elements(&retained.projection, root, changed).len() as u32
+ });
+ last_pass_element(root: Option<StyleNodeID>, changed: bool, index: u32) -> u32 => root.map_or(0, |root| {
+ let retained = &mut engine.retained;
+ let elements = retained.live_counters.last_pass_elements(&retained.projection, root, changed);
+ elements.get(index as usize).map_or(0, |node| node.raw())
+ });
+ animated_style_samples(rebuilt_every_group: bool, reset: bool) -> u64 =>
+ engine.retained.live_counters.animated_samples(rebuilt_every_group, reset);
layer_index(tree_scope: TreeScopeID, layer: CascadeLayerID) -> u32;
size_query_container_scan_visits(reset: bool) -> u64;
ensure_random_base_value(node: Option<StyleNodeID>, name: FfiSpan<u16>, element_shared: bool) -> u64 => {
@@ -367,32 +515,19 @@ style_boundary! {
}
impl StyleChange {
- /// Whether the change only keeps the engine from reclaiming records: it pins or unpins one, or begins or ends an
- /// epoch of style record views. It changes nothing the paint properties are prepared from.
+ /// Whether the change only keeps the engine from reclaiming records: it notes the record a pseudo-element holds, or
+ /// begins or ends an epoch of style record views. It changes nothing the paint properties are prepared from.
pub(crate) fn only_keeps_records_alive(&self) -> bool {
matches!(
self,
- Self::BeginStyleRecordViewEpoch
- | Self::EndStyleRecordViewEpoch
- | Self::PinStyleRecord { .. }
- | Self::SetHeldPseudoStyleRecord { .. }
- | Self::UnpinStyleRecord { .. }
+ Self::BeginStyleRecordViewEpoch | Self::EndStyleRecordViewEpoch | Self::SetHeldPseudoStyleRecord { .. }
)
}
- /// Whether the change may move a fact the host knows of the render state. One that keeps records alive, notes what
- /// a text spells, picks the pseudo-element whose style is deferred, or begins or ends a cold matching batch never
- /// does: none of them stages a style input or touches a layout box.
+ /// Whether the change may move a fact the host knows of the render state. One that keeps records alive or notes
+ /// what a text spells never does: neither stages a style input or touches a layout box.
pub(crate) fn may_move_facts(&self) -> bool {
- !self.only_keeps_records_alive()
- && !matches!(
- self,
- Self::SetTextIsAsciiWhitespace { .. }
- | Self::SetPseudoElementStyleDeferred { .. }
- | Self::BeginColdMatchingBatch { .. }
- | Self::BeginAdaptiveColdMatchingBatch { .. }
- | Self::EndColdMatchingBatch
- )
+ !self.only_keeps_records_alive() && !matches!(self, Self::SetTextIsAsciiWhitespace { .. })
}
}
diff --git a/Libraries/LibWeb/Rust/src/css/style/catalog.rs b/Libraries/LibWeb/Rust/src/css/style/catalog.rs
deleted file mode 100644
index f07fd855a1e..00000000000
--- a/Libraries/LibWeb/Rust/src/css/style/catalog.rs
+++ /dev/null
@@ -1,1674 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-use smallvec::SmallVec;
-
-use super::column::Column;
-use super::column::PooledStampedIndex;
-use super::intern_table::content_hash;
-use super::prefix::{PrefixTransitionContext, PrefixTransitionContexts};
-use super::shared_vector::{SharedVector, SharedVectorPool};
-use super::*;
-
-define_id! { default pub(super) struct MatchAnswerID(pub(super)); }
-define_id! { default pub(super) struct SelectorTruthSetID(pub(super)); }
-
-impl super::intern_table::InternIdentity for MatchAnswerID {
- fn index(self) -> usize {
- self.0 as usize - 1
- }
-}
-
-impl super::intern_table::InternIdentity for SelectorTruthSetID {
- fn index(self) -> usize {
- self.0 as usize - 1
- }
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
-pub(super) struct SelectorTruth {
- pub(super) entry: EntryID,
- pub(super) tree_scope: TreeScopeID,
- pub(super) scope_proximity: u32,
-}
-
-#[derive(Clone, Default)]
-pub(super) struct SelectorTruthSetCatalog {
- sets: super::intern_table::InternTable<SelectorTruthSetID, Arc<[SelectorTruth]>>,
- verified_derived_answers: HashMap<(SelectorTruthSetID, TreeScopeID, u64), Arc<[RetainedRuleMatch]>>,
-}
-
-impl SelectorTruthSetCatalog {
- pub(super) fn intern_prepared(&mut self, truth: Vec<SelectorTruth>) -> (SelectorTruthSetID, bool) {
- let hash = content_hash(&truth);
- if let Some(identity) = self
- .sets
- .find(hash, |_identity, candidate| candidate.as_ref() == truth.as_slice())
- {
- return (identity, true);
- }
- let identity = SelectorTruthSetID(
- u32::try_from(self.sets.len())
- .ok()
- .and_then(|length| length.checked_add(1))
- .expect("selector truth-set identity space exhausted"),
- );
- self.sets.insert(hash, identity, truth.into());
- (identity, false)
- }
-
- pub(super) fn get(&self, identity: SelectorTruthSetID) -> &Arc<[SelectorTruth]> {
- &self.sets[identity]
- }
-
- pub(super) fn verify_derived_answer(
- &mut self,
- truth: SelectorTruthSetID,
- tree_scope: TreeScopeID,
- program_version: ProgramVersion,
- answer: &[RetainedRuleMatch],
- ) -> bool {
- match self
- .verified_derived_answers
- .entry((truth, tree_scope, program_version.0))
- {
- std::collections::hash_map::Entry::Vacant(entry) => {
- entry.insert(answer.into());
- false
- }
- std::collections::hash_map::Entry::Occupied(entry) => {
- assert_eq!(entry.get().as_ref(), answer, "selector truth derived two rule answers");
- true
- }
- }
- }
-}
-
-enum AnswerReferenceCategory {
- Retained,
- Cascade,
- Prefix,
-}
-
-#[derive(Clone)]
-
-pub(super) struct MatchAnswerCatalogEntry {
- pub(super) answer: Arc<[RetainedRuleMatch]>,
- synthetic_pseudo_mask: u64,
- pub(super) prefix_references: u32,
- pub(super) cascade_references: u32,
- pub(super) retained_references: u32,
- pending_references: u32,
- /// Whether the catalog's sweep candidates name this answer already.
- queued_for_sweep: bool,
-}
-
-#[derive(Clone, Default)]
-pub(super) struct MatchAnswerCatalog {
- pub(super) answers: super::intern_table::InternTable<MatchAnswerID, Option<MatchAnswerCatalogEntry>>,
- pub(super) retained_answer_count: usize,
- pub(super) needs_compaction: bool,
- /// Every answer that may have lost its last reference without being removed since the last
- /// sweep: each new answer, and each one whose cascade or pending count dropped to zero. A
- /// sweep only has to look at these. Identities are never reused, so the slots of removed
- /// answers stay behind, and walking all of them made every sweep slower than the last. Each
- /// answer is noted once, so this holds no more entries than the catalog holds live answers.
- sweep_candidates: Vec<MatchAnswerID>,
-}
-
-impl MatchAnswerCatalog {
- #[cfg(test)]
- pub(super) fn pending_reference_count(&self) -> u64 {
- self.answers
- .iter()
- .flatten()
- .map(|entry| u64::from(entry.pending_references))
- .sum()
- }
-
- pub(super) fn retain_pending(&mut self, identity: MatchAnswerID) {
- let entry = self.answers[identity].as_mut().expect("pending answer must be live");
- entry.pending_references = entry
- .pending_references
- .checked_add(1)
- .expect("pending answer reference overflow");
- }
-
- fn transfer_pending(&mut self, identity: MatchAnswerID, category: AnswerReferenceCategory) {
- match category {
- AnswerReferenceCategory::Retained => self.retain_identity(identity),
- AnswerReferenceCategory::Cascade => self.retain_cascade(identity),
- AnswerReferenceCategory::Prefix => self.retain_prefix(identity),
- }
- self.release_pending(identity);
- }
-
- pub(super) fn release_pending(&mut self, identity: MatchAnswerID) {
- let entry = self.answers[identity].as_mut().expect("pending answer must be live");
- entry.pending_references = entry
- .pending_references
- .checked_sub(1)
- .expect("releasing an unowned pending answer");
- if entry.pending_references == 0 {
- Self::queue_for_sweep(&mut self.sweep_candidates, entry, identity);
- }
- // NB: Reclamation remains at the context boundary, after every pending owner
- // has either transferred to a retained category or been released.
- }
-
- pub(super) fn mark_referenced_selector_programs(&self, referenced: &mut Vec<bool>) {
- let mut mark = |program: SelectorProgramID| {
- if referenced.len() <= program.0 as usize {
- referenced.resize(program.0 as usize + 1, false);
- }
- referenced[program.0 as usize] = true;
- };
- for entry in self.answers.iter().flatten().filter(|entry| {
- entry.prefix_references != 0
- || entry.cascade_references != 0
- || entry.retained_references != 0
- || entry.pending_references != 0
- }) {
- for matched in entry.answer.iter() {
- mark(matched.program);
- }
- }
- }
-
- pub(super) fn intern(&mut self, answer: &[RuleMatch]) -> MatchAnswerID {
- const INLINE_ANSWER_LENGTH: usize = 16;
- if let Some(first) = answer.first().copied()
- && answer.len() <= INLINE_ANSWER_LENGTH
- {
- let first = RetainedRuleMatch::from_rule_match(first);
- let mut prepared = [first; INLINE_ANSWER_LENGTH];
- for (output, matched) in prepared.iter_mut().zip(answer.iter().copied()) {
- *output = RetainedRuleMatch::from_rule_match(matched);
- }
- let prepared = &mut prepared[..answer.len()];
- prepared.sort_unstable();
- let hash = content_hash(&*prepared);
- if let Some(identity) = self.identity(prepared, hash) {
- return identity;
- }
- return self.insert_new(Arc::from(&*prepared), hash, Self::mask_for_matches(answer));
- }
- let mut prepared: Vec<RetainedRuleMatch> =
- answer.iter().copied().map(RetainedRuleMatch::from_rule_match).collect();
- prepared.sort_unstable();
- let hash = content_hash(&prepared);
- if let Some(identity) = self.identity(&prepared, hash) {
- return identity;
- }
- self.insert_new(prepared.into(), hash, Self::mask_for_matches(answer))
- }
-
- pub(super) fn intern_prepared(
- &mut self,
- answer: Vec<RetainedRuleMatch>,
- programs: &SelectorPrograms,
- ) -> MatchAnswerID {
- let hash = content_hash(&answer);
- if let Some(identity) = self.identity(&answer, hash) {
- return identity;
- }
- let mask = Self::mask_for_retained_matches(&answer, programs);
- self.insert_new(answer.into(), hash, mask)
- }
-
- fn insert_new(&mut self, answer: Arc<[RetainedRuleMatch]>, hash: u64, synthetic_pseudo_mask: u64) -> MatchAnswerID {
- let identity = MatchAnswerID(
- u32::try_from(self.answers.len())
- .ok()
- .and_then(|length| length.checked_add(1))
- .expect("match answer catalog identity space exhausted"),
- );
- self.answers.insert(
- hash,
- identity,
- Some(MatchAnswerCatalogEntry {
- answer,
- synthetic_pseudo_mask,
- prefix_references: 0,
- cascade_references: 0,
- retained_references: 0,
- pending_references: 0,
- queued_for_sweep: true,
- }),
- );
- self.sweep_candidates.push(identity);
- identity
- }
-
- pub(super) fn answer(&self, identity: MatchAnswerID) -> Option<&Arc<[RetainedRuleMatch]>> {
- self.answers[identity].as_ref().map(|entry| &entry.answer)
- }
-
- fn pseudo_bit(pseudo: Option<tree::PseudoElementTarget>) -> u64 {
- pseudo.map_or(0, |pseudo| {
- if pseudo.kind.0 <= bridge::LAST_SYNTHETIC_PSEUDO_ELEMENT_KIND {
- 1_u64 << pseudo.kind.0
- } else {
- 0
- }
- })
- }
-
- fn mask_for_matches(answer: &[RuleMatch]) -> u64 {
- answer
- .iter()
- .fold(0, |mask, matched| mask | Self::pseudo_bit(matched.pseudo_element))
- }
-
- fn mask_for_retained_matches(answer: &[RetainedRuleMatch], programs: &SelectorPrograms) -> u64 {
- answer.iter().fold(0, |mask, matched| {
- let entry = &programs.get(matched.program).entries()[matched.entry as usize];
- mask | Self::pseudo_bit(entry.pseudo_element)
- })
- }
-
- pub(super) fn synthetic_pseudo_mask(&self, identity: MatchAnswerID) -> Option<u64> {
- self.answers[identity]
- .as_ref()
- .map(|answer| answer.synthetic_pseudo_mask)
- }
-
- pub(super) fn has_cascade_reference(&self, identity: MatchAnswerID) -> bool {
- self.answers[identity]
- .as_ref()
- .is_some_and(|entry| entry.cascade_references != 0)
- }
-
- pub(super) fn retain_cascade(&mut self, identity: MatchAnswerID) {
- let entry = self.answers[identity]
- .as_mut()
- .expect("a cascade-input identity must remain in its catalog");
- entry.cascade_references = entry
- .cascade_references
- .checked_add(1)
- .expect("cascade-input reference count overflow");
- }
-
- pub(super) fn release_cascade(&mut self, identity: MatchAnswerID) {
- let entry = self.answers[identity]
- .as_mut()
- .expect("a cascade-input identity must remain in its catalog");
- entry.cascade_references = entry
- .cascade_references
- .checked_sub(1)
- .expect("releasing an unretained cascade input");
- if entry.cascade_references == 0 {
- Self::queue_for_sweep(&mut self.sweep_candidates, entry, identity);
- }
- }
-
- pub(super) fn retain_prefix(&mut self, identity: MatchAnswerID) {
- let entry = self.answers[identity]
- .as_mut()
- .expect("a retained answer must remain in its catalog");
-
- entry.prefix_references = entry
- .prefix_references
- .checked_add(1)
- .expect("match answer reference count overflow");
- }
-
- pub(super) fn release_prefix(&mut self, identity: MatchAnswerID) {
- let remove = {
- let entry = self.answers[identity]
- .as_mut()
- .expect("a retained answer must remain in its catalog");
- entry.prefix_references = entry
- .prefix_references
- .checked_sub(1)
- .expect("releasing an unretained match answer");
- if entry.prefix_references != 0 {
- return;
- }
- entry.cascade_references == 0 && entry.retained_references == 0 && entry.pending_references == 0
- };
- if remove {
- self.remove_unreferenced(identity);
- }
- }
-
- fn queue_for_sweep(
- sweep_candidates: &mut Vec<MatchAnswerID>,
- entry: &mut MatchAnswerCatalogEntry,
- identity: MatchAnswerID,
- ) {
- if !entry.queued_for_sweep {
- entry.queued_for_sweep = true;
- sweep_candidates.push(identity);
- }
- }
-
- #[cfg(test)]
- pub(super) fn sweep_candidate_count(&self) -> usize {
- self.sweep_candidates.len()
- }
-
- pub(super) fn sweep_unreferenced(&mut self) {
- let mut candidates = std::mem::take(&mut self.sweep_candidates);
- for identity in candidates.drain(..) {
- // A candidate may have been removed since it was noted.
- let Some(entry) = self.answers[identity].as_mut() else {
- continue;
- };
- entry.queued_for_sweep = false;
- if entry.prefix_references == 0
- && entry.cascade_references == 0
- && entry.pending_references == 0
- && entry.retained_references == 0
- {
- self.remove_unreferenced(identity);
- }
- }
- // Keep the allocation for the next batch of candidates.
- self.sweep_candidates = candidates;
- }
-
- pub(super) fn remove_unreferenced(&mut self, identity: MatchAnswerID) {
- let entry = self.answers[identity].take().expect("unreferenced answer must be live");
- let hash = content_hash(&entry.answer);
- self.answers.remove_identity(hash, identity);
- self.needs_compaction = true;
- }
-
- pub(super) fn compact_if_needed(&mut self) {
- if !self.needs_compaction {
- return;
- }
- self.answers.shrink_excess_capacity();
- self.needs_compaction = false;
- }
-
- pub(super) fn identity(&self, answer: &[RetainedRuleMatch], hash: u64) -> Option<MatchAnswerID> {
- self.answers.find(hash, |_identity, entry| {
- entry.as_ref().is_some_and(|entry| entry.answer.as_ref() == answer)
- })
- }
-
- pub(super) fn retain_identity(&mut self, identity: MatchAnswerID) {
- let entry = self.answers[identity].as_mut().unwrap();
- if entry.retained_references == 0 {
- self.retained_answer_count += 1;
- }
- entry.retained_references = entry
- .retained_references
- .checked_add(1)
- .expect("retained match answer reference count overflow");
- }
-
- pub(super) fn release_identity(&mut self, identity: MatchAnswerID) {
- let remove = {
- let entry = self.answers[identity].as_mut().unwrap();
- entry.retained_references = entry
- .retained_references
- .checked_sub(1)
- .expect("releasing an unretained match answer identity");
- if entry.retained_references != 0 {
- return;
- }
- self.retained_answer_count -= 1;
- entry.prefix_references == 0 && entry.cascade_references == 0 && entry.pending_references == 0
- };
- if remove {
- self.remove_unreferenced(identity);
- }
- }
-
- pub(super) fn retained_answer(&self, identity: MatchAnswerID) -> Option<&Arc<[RetainedRuleMatch]>> {
- self.answers[identity]
- .as_ref()
- .filter(|entry| entry.retained_references != 0)
- .map(|entry| &entry.answer)
- }
-
- pub(super) fn release_all_retained(&mut self) {
- for index in 0..self.answers.len() {
- let Some(entry) = self.answers[index].as_mut() else {
- continue;
- };
- if entry.retained_references == 0 {
- continue;
- }
- entry.retained_references = 0;
- if entry.prefix_references == 0 && entry.cascade_references == 0 && entry.pending_references == 0 {
- self.remove_unreferenced(MatchAnswerID(index as u32 + 1));
- }
- }
- self.retained_answer_count = 0;
- }
-}
-
-type PseudoWinnerGroups = Arc<[(super::tree::PseudoElementTarget, CascadeStateID)]>;
-
-pub(super) struct PrefixAnswer {
- pub(super) matches: MatchAnswerID,
- pub(super) winner_group: Option<(u64, CascadeStateID)>,
- /// The pseudo-element winner states published beside the answer, and their generation.
- pub(super) pseudo_winner_groups: Option<(u64, PseudoWinnerGroups)>,
- pub(super) cascade_input: MatchAnswerID,
- pub(super) cascade_winner_inventory_is_complete: bool,
-}
-
-#[derive(Clone)]
-
-struct OwnedPrefixAnswerKey {
- prefix_contribution: MatchAnswerID,
- non_prefix_matches: Box<[RetainedRuleMatch]>,
- non_prefix_hash: u64,
-}
-
-impl OwnedPrefixAnswerKey {
- fn as_key(&self) -> PrefixAnswerKey<'_> {
- PrefixAnswerKey {
- prefix_contribution: self.prefix_contribution,
- non_prefix_matches: &self.non_prefix_matches,
- non_prefix_hash: self.non_prefix_hash,
- }
- }
-}
-
-impl PrefixAnswerKey<'_> {
- fn hash(self) -> u64 {
- content_hash((self.prefix_contribution, self.non_prefix_hash))
- }
-
- fn into_owned(self) -> OwnedPrefixAnswerKey {
- OwnedPrefixAnswerKey {
- prefix_contribution: self.prefix_contribution,
- non_prefix_matches: self.non_prefix_matches.into(),
- non_prefix_hash: self.non_prefix_hash,
- }
- }
-}
-
-pub(super) struct PrefixAnswerCache {
- pub(super) prefix_contribution_by_match_set: Column<Column<MatchAnswerID>>,
- pub(super) exact_prefix_by_match_set: Column<Column<MatchAnswerID>>,
- exact_answers: hashbrown::HashTable<(OwnedPrefixAnswerKey, MatchAnswerID)>,
- answers: hashbrown::HashTable<(OwnedPrefixAnswerKey, PrefixAnswer)>,
- pub(super) retained: bool,
-}
-
-#[derive(Default)]
-pub(super) struct PrefixCaches {
- pub(super) states: PrefixStateCache,
- pub(super) answers: PrefixAnswerCache,
-}
-
-/// The prefix caches the engine shares with the matching traversals and patches that borrow them.
-/// The borrows nest, so each is checked when it is taken, as a `RefCell`'s is: a conflicting borrow
-/// panics rather than waits. The check is atomic, so the engine can move to the thread its stages
-/// run on.
-#[derive(Default)]
-pub(super) struct SharedPrefixCaches(std::sync::RwLock<PrefixCaches>);
-
-impl SharedPrefixCaches {
- #[track_caller]
- pub(super) fn borrow(&self) -> std::sync::RwLockReadGuard<'_, PrefixCaches> {
- match self.0.try_read() {
- Ok(caches) => caches,
- // A panic while the caches were borrowed leaves them as a `RefCell` would.
- Err(std::sync::TryLockError::Poisoned(poisoned)) => poisoned.into_inner(),
- Err(std::sync::TryLockError::WouldBlock) => panic!("the prefix caches are already mutably borrowed"),
- }
- }
-
- #[track_caller]
- pub(super) fn borrow_mut(&self) -> std::sync::RwLockWriteGuard<'_, PrefixCaches> {
- match self.0.try_write() {
- Ok(caches) => caches,
- Err(std::sync::TryLockError::Poisoned(poisoned)) => poisoned.into_inner(),
- Err(std::sync::TryLockError::WouldBlock) => panic!("the prefix caches are already borrowed"),
- }
- }
-}
-
-impl Default for PrefixAnswerCache {
- fn default() -> Self {
- Self {
- prefix_contribution_by_match_set: Column::default(),
- exact_prefix_by_match_set: Column::default(),
- exact_answers: hashbrown::HashTable::new(),
- answers: hashbrown::HashTable::new(),
-
- retained: false,
- }
- }
-}
-
-impl PrefixAnswerCache {
- pub(super) fn lane_lookup<'a>(
- lane: &Column<Column<MatchAnswerID>>,
- catalog: &'a MatchAnswerCatalog,
- key: PrefixContributionKey,
- ) -> Lookup<(MatchAnswerID, &'a Arc<[RetainedRuleMatch]>), PrefixContributionKey> {
- let Some(identity) = lane
- .get(key.program.0 as usize)
- .and_then(|by_match_set| by_match_set.get(key.matches.index()))
- .copied()
- .filter(|&identity| identity != MatchAnswerID::default())
- else {
- return Lookup::Missing(key);
- };
- let answer = catalog
- .answer(identity)
- .expect("a prefix answer identity must remain in its catalog");
- Lookup::Known((identity, answer))
- }
-
- pub(super) fn lane_remember(
- lane: &mut Column<Column<MatchAnswerID>>,
- catalog: &mut MatchAnswerCatalog,
- program: ScopeProgramID,
- matches: PrefixMatchSetID,
- identity: MatchAnswerID,
- ) {
- let by_match_set = lane.entry(program.0 as usize);
- let match_set_index = matches.index();
- by_match_set.ensure(match_set_index);
- let previous = by_match_set[match_set_index];
- if previous != identity {
- catalog.retain_prefix(identity);
- if previous != MatchAnswerID::default() {
- catalog.release_prefix(previous);
- }
- by_match_set[match_set_index] = identity;
- }
- }
-
- pub(super) fn prefix_contribution<'a>(
- &self,
- catalog: &'a MatchAnswerCatalog,
- key: PrefixContributionKey,
- ) -> Lookup<(MatchAnswerID, &'a Arc<[RetainedRuleMatch]>), PrefixContributionKey> {
- Self::lane_lookup(&self.prefix_contribution_by_match_set, catalog, key)
- }
-
- pub(super) fn exact_prefix<'a>(
- &self,
- catalog: &'a MatchAnswerCatalog,
- key: PrefixContributionKey,
- ) -> Lookup<(MatchAnswerID, &'a Arc<[RetainedRuleMatch]>), PrefixContributionKey> {
- Self::lane_lookup(&self.exact_prefix_by_match_set, catalog, key)
- }
-
- pub(super) fn remember_exact_prefix(
- &mut self,
- catalog: &mut MatchAnswerCatalog,
- program: ScopeProgramID,
- matches: PrefixMatchSetID,
- answer: Vec<RetainedRuleMatch>,
- programs: &SelectorPrograms,
- ) -> MatchAnswerID {
- let identity = catalog.intern_prepared(answer, programs);
- Self::lane_remember(&mut self.exact_prefix_by_match_set, catalog, program, matches, identity);
- identity
- }
-
- pub(super) fn remember_prefix_contribution(
- &mut self,
- catalog: &mut MatchAnswerCatalog,
- program: ScopeProgramID,
- matches: PrefixMatchSetID,
- answer: &[RuleMatch],
- ) -> MatchAnswerID {
- let identity = catalog.intern(answer);
- Self::lane_remember(
- &mut self.prefix_contribution_by_match_set,
- catalog,
- program,
- matches,
- identity,
- );
- identity
- }
-
- pub(super) fn exact_answer<'a>(&self, key: PrefixAnswerKey<'a>) -> Lookup<MatchAnswerID, PrefixAnswerKey<'a>> {
- match self
- .exact_answers
- .find(key.hash(), |(candidate, _)| candidate.as_key() == key)
- {
- Some((_, answer)) => Lookup::Known(*answer),
- None => Lookup::Missing(key),
- }
- }
-
- #[cfg(test)]
- pub(super) fn remember_exact_answer(
- &mut self,
- catalog: &mut MatchAnswerCatalog,
- key: PrefixAnswerKey<'_>,
- answer: MatchAnswerID,
- ) {
- catalog.retain_prefix(answer);
- if let Some((_, previous)) = self
- .exact_answers
- .find_mut(key.hash(), |(candidate, _)| candidate.as_key() == key)
- {
- catalog.release_prefix(std::mem::replace(previous, answer));
- } else {
- self.exact_answers
- .insert_unique(key.hash(), (key.into_owned(), answer), |(candidate, _)| {
- candidate.as_key().hash()
- });
- }
- }
-
- fn install_exact_answer(
- &mut self,
- catalog: &mut MatchAnswerCatalog,
- key: OwnedPrefixAnswerKey,
- answer: MatchAnswerID,
- ) {
- catalog.transfer_pending(answer, AnswerReferenceCategory::Prefix);
- if let Some((_, previous)) = self
- .exact_answers
- .find_mut(key.as_key().hash(), |(candidate, _)| candidate.as_key() == key.as_key())
- {
- catalog.release_prefix(std::mem::replace(previous, answer));
- } else {
- self.exact_answers
- .insert_unique(key.as_key().hash(), (key, answer), |(candidate, _)| {
- candidate.as_key().hash()
- });
- }
- }
-
- #[allow(clippy::too_many_arguments)]
- pub(super) fn remember(
- &mut self,
- catalog: &mut MatchAnswerCatalog,
- key: PrefixAnswerKey<'_>,
- answer: &[RuleMatch],
- winner_group: Option<(u64, CascadeStateID)>,
- pseudo_winner_groups: Option<(u64, PseudoWinnerGroups)>,
- cascade_input: MatchAnswerID,
- cascade_winner_inventory_is_complete: bool,
- ) {
- let matches = catalog.intern(answer);
- catalog.retain_prefix(matches);
- let answer = PrefixAnswer {
- matches,
- winner_group,
- pseudo_winner_groups,
- cascade_input,
- cascade_winner_inventory_is_complete,
- };
- if let Some((_, previous)) = self
- .answers
- .find_mut(key.hash(), |(candidate, _)| candidate.as_key() == key)
- {
- catalog.release_prefix(std::mem::replace(previous, answer).matches);
- } else {
- self.answers
- .insert_unique(key.hash(), (key.into_owned(), answer), |(candidate, _)| {
- candidate.as_key().hash()
- });
- }
- }
-
- pub(super) fn release(&mut self, catalog: &mut MatchAnswerCatalog) {
- for lane in [&self.prefix_contribution_by_match_set, &self.exact_prefix_by_match_set] {
- for by_match_set in lane.iter() {
- for &identity in by_match_set.iter() {
- if identity != MatchAnswerID::default() {
- catalog.release_prefix(identity);
- }
- }
- }
- }
- for (_, answer) in &self.answers {
- catalog.release_prefix(answer.matches);
- }
- for (_, answer) in &self.exact_answers {
- catalog.release_prefix(*answer);
- }
- catalog.compact_if_needed();
- self.prefix_contribution_by_match_set = Column::default();
- self.exact_prefix_by_match_set = Column::default();
- self.exact_answers = hashbrown::HashTable::new();
- self.answers = hashbrown::HashTable::new();
-
- self.retained = false;
- }
-
- pub(super) fn retain(&mut self) {
- self.retained = true;
- }
-
- pub(super) fn make_scratch(&mut self) {
- if !self.retained {
- return;
- }
-
- self.retained = false;
- }
-
- pub(super) fn remove_program(&mut self, catalog: &mut MatchAnswerCatalog, program: ScopeProgramID) {
- let program_index = program.0 as usize;
- if self
- .prefix_contribution_by_match_set
- .get(program_index)
- .is_some_and(|by_match_set| !by_match_set.is_empty())
- || self
- .exact_prefix_by_match_set
- .get(program_index)
- .is_some_and(|by_match_set| !by_match_set.is_empty())
- {
- // Canonical contributions are shared across programs. Dropping only this program's
- // lookup entries would leave unreachable contributions behind, so release the small
- // cache as one coherent unit.
- self.release(catalog);
- }
- }
-}
-
-impl PrefixAnswerCache {
- pub(super) fn lookup<'a>(&self, key: PrefixAnswerKey<'a>) -> Lookup<&PrefixAnswer, PrefixAnswerKey<'a>> {
- match self
- .answers
- .find(key.hash(), |(candidate, _)| candidate.as_key() == key)
- {
- Some((_, answer)) => Lookup::Known(answer),
- None => Lookup::Missing(key),
- }
- }
-}
-
-/// Exact selector answers retained as the old side of a later plan.
-///
-/// Cascade compaction is declaration-dependent, so the answer catalog keeps this stable selector
-/// payload and restores the current cascade rank when reading it. A node without retained coverage
-/// turns the next declaration edit into an ordinary cold match without changing semantics.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
-pub(super) struct RetainedRuleMatch {
- pub(super) rule: RuleID,
- pub(super) program: SelectorProgramID,
- pub(super) entry: u32,
- pub(super) tree_scope: TreeScopeID,
- pub(super) scope_proximity: u32,
-}
-
-impl RetainedRuleMatch {
- pub(super) fn from_rule_match(entry: RuleMatch) -> Self {
- Self {
- rule: entry.rule,
- program: entry.program,
- entry: entry.entry,
- tree_scope: entry.tree_scope,
- scope_proximity: entry.scope_proximity,
- }
- }
-
- pub(super) fn materialize(
- self,
- node: StyleNodeID,
- programs: &SelectorPrograms,
- cascade_order: u32,
- ) -> Option<RuleMatch> {
- let entry = programs.get(self.program).entries().get(self.entry as usize)?;
- Some(RuleMatch {
- node,
- pseudo_element: entry.pseudo_element,
- rule: self.rule,
- program: self.program,
- entry: self.entry,
- cascade_order,
- specificity: entry.specificity,
- tree_scope: self.tree_scope,
- scope_proximity: self.scope_proximity,
- })
- }
-}
-
-pub(super) fn prepare_retained_match_answer(matches: impl Iterator<Item = RuleMatch>) -> Vec<RetainedRuleMatch> {
- let mut answer: Vec<_> = matches.map(RetainedRuleMatch::from_rule_match).collect();
- answer.sort_unstable();
- answer
-}
-
-pub(super) fn prepare_selector_truth_set(
- matches: &[RetainedRuleMatch],
- programs: &SelectorPrograms,
-) -> Vec<SelectorTruth> {
- let mut truth = matches
- .iter()
- .map(|matched| SelectorTruth {
- entry: programs.entry_id(matched.program, matched.entry),
- tree_scope: matched.tree_scope,
- scope_proximity: matched.scope_proximity,
- })
- .collect::<Vec<_>>();
- truth.sort_unstable();
- truth.dedup();
- truth
-}
-
-pub(super) fn merge_retained_match_answers(answer: &mut Vec<RetainedRuleMatch>, suffix: &[RetainedRuleMatch]) {
- if answer
- .last()
- .zip(suffix.first())
- .is_none_or(|(last, first)| last <= first)
- {
- answer.extend_from_slice(suffix);
- return;
- }
- let mut answer_index = answer.len();
- let mut suffix_index = suffix.len();
- answer.extend_from_slice(suffix);
- let mut destination = answer.len();
- while answer_index != 0 && suffix_index != 0 {
- destination -= 1;
- if answer[answer_index - 1] > suffix[suffix_index - 1] {
- answer_index -= 1;
- answer[destination] = answer[answer_index];
- } else {
- suffix_index -= 1;
- answer[destination] = suffix[suffix_index];
- }
- }
- if suffix_index != 0 {
- answer[..suffix_index].copy_from_slice(&suffix[..suffix_index]);
- }
-}
-
-/// NB: None leaves a column unchanged; Some(None) is a tombstone. Every
-/// nonempty replacement owns a pending catalog reference until installation.
-#[derive(Clone, Default)]
-pub(super) struct PendingAnswer {
- published_index: Option<usize>,
- pub(super) identity: Option<Option<MatchAnswerID>>,
- pub(super) cascade_input: Option<Option<MatchAnswerID>>,
-}
-
-/// Ordered node updates and exact-cache discoveries owned by one matching context.
-/// NB: The caller must install these effects or release_pending_all before
-/// discarding the context. An incomplete batch retains the entire owner.
-#[derive(Clone, Default)]
-pub(super) struct AnswerEffects {
- pub(super) winners: super::cascade::WinnerEffects,
- entries: Vec<(StyleNodeID, PendingAnswer)>,
- /// Which entry holds each node, addressed by element identity. The batch already knows how
- /// many entries it has; a probed index would re-derive that knowledge once per access.
- by_node: PooledStampedIndex,
- exact_answers: Vec<(OwnedPrefixAnswerKey, MatchAnswerID)>,
- by_content: HashMap<u64, SmallVec<[usize; 1]>>,
-}
-
-impl AnswerEffects {
- pub(super) fn published_lookup<'a>(
- &self,
- published: &'a PublishedMatchAnswers,
- node: StyleNodeID,
- ) -> Option<&'a PublishedMatchAnswer> {
- self.lookup(node)
- .and_then(|entry| entry.published_index)
- .map(|index| &published.entries[index])
- }
-
- pub(super) fn note_published(&mut self, node: StyleNodeID, index: usize) {
- self.entry(node).published_index = Some(index);
- }
-
- pub(super) fn lookup(&self, node: StyleNodeID) -> Option<&PendingAnswer> {
- let index = self.by_node.get(node.element_index()? as usize)?;
- Some(&self.entries[index as usize].1)
- }
-
- fn entry(&mut self, node: StyleNodeID) -> &mut PendingAnswer {
- let row = node
- .element_index()
- .expect("answer effects are keyed by element identity") as usize;
- let index = match self.by_node.get(row) {
- Some(index) => index as usize,
- None => {
- let index = self.entries.len();
-
- self.entries.push((node, PendingAnswer::default()));
- self.by_node.insert(
- row,
- u32::try_from(index).expect("answer effect identity space exhausted"),
- );
- index
- }
- };
- &mut self.entries[index].1
- }
-
- pub(super) fn answer_identity(&self, retained: &RetainedMatchAnswers, node: StyleNodeID) -> Option<MatchAnswerID> {
- self.lookup(node)
- .and_then(|entry| entry.identity)
- .unwrap_or_else(|| retained.answer_identity(node))
- }
-
- pub(super) fn cascade_input(&self, retained: &RetainedMatchAnswers, node: StyleNodeID) -> Option<MatchAnswerID> {
- self.lookup(node)
- .and_then(|entry| entry.cascade_input)
- .unwrap_or_else(|| retained.cascade_input_lookup(node).sparse().ok().copied())
- }
-
- pub(super) fn remember_identity(
- &mut self,
- node: StyleNodeID,
- identity: MatchAnswerID,
- catalog: &mut MatchAnswerCatalog,
- ) {
- catalog.retain_pending(identity);
- if let Some(Some(previous)) = self.entry(node).identity.replace(Some(identity)) {
- catalog.release_pending(previous);
- }
- }
-
- pub(super) fn remember_cascade_input(
- &mut self,
- node: StyleNodeID,
- identity: MatchAnswerID,
- catalog: &mut MatchAnswerCatalog,
- ) {
- catalog.retain_pending(identity);
- if let Some(Some(previous)) = self.entry(node).cascade_input.replace(Some(identity)) {
- catalog.release_pending(previous);
- }
- }
-
- pub(super) fn forget_answer(&mut self, node: StyleNodeID, catalog: &mut MatchAnswerCatalog) {
- if let Some(Some(previous)) = self.entry(node).identity.replace(None) {
- catalog.release_pending(previous);
- }
- }
-
- pub(super) fn forget_cascade_input(&mut self, node: StyleNodeID, catalog: &mut MatchAnswerCatalog) {
- if let Some(Some(previous)) = self.entry(node).cascade_input.replace(None) {
- catalog.release_pending(previous);
- }
- }
-
- pub(super) fn forget(&mut self, node: StyleNodeID, catalog: &mut MatchAnswerCatalog) {
- self.forget_answer(node, catalog);
- self.forget_cascade_input(node, catalog);
- }
-
- pub(super) fn exact_answer(&self, key: PrefixAnswerKey<'_>) -> Option<MatchAnswerID> {
- self.by_content.get(&key.hash())?.iter().rev().find_map(|&index| {
- let (candidate, identity) = &self.exact_answers[index];
- (candidate.as_key() == key).then_some(*identity)
- })
- }
-
- pub(super) fn remember_exact_answer(
- &mut self,
- key: PrefixAnswerKey<'_>,
- identity: MatchAnswerID,
- catalog: &mut MatchAnswerCatalog,
- ) {
- catalog.retain_pending(identity);
- let bucket = self.by_content.entry(key.hash()).or_default();
- bucket.push(self.exact_answers.len());
- self.exact_answers.push((key.into_owned(), identity));
- }
-
- pub(super) fn release_pending_all(
- self,
- catalog: &mut crate::fork::ForkShared<MatchAnswerCatalog>,
- winners: &mut crate::fork::ForkShared<super::cascade::WinnerGroups>,
- ) {
- self.winners.release_pending_all(winners);
- for (_, entry) in self.entries {
- if let Some(Some(identity)) = entry.identity {
- catalog.release_pending(identity);
- }
- if let Some(Some(identity)) = entry.cascade_input {
- catalog.release_pending(identity);
- }
- }
- for (_, identity) in self.exact_answers {
- catalog.release_pending(identity);
- }
- }
-
- pub(super) fn install(
- self,
- retained: &mut RetainedMatchAnswers,
- catalog: &mut MatchAnswerCatalog,
- cache: &mut PrefixAnswerCache,
- ) {
- if self.entries.is_empty() && self.exact_answers.is_empty() {
- return;
- }
- for (node, entry) in self.entries {
- let Some(index) = node.element_index().map(|index| index as usize) else {
- debug_assert!(entry.identity.flatten().is_none() && entry.cascade_input.flatten().is_none());
- continue;
- };
- if let Some(identity) = entry.identity {
- if let Some(identity) = identity {
- catalog.transfer_pending(identity, AnswerReferenceCategory::Retained);
- if retained.column.len() <= index {
- retained.column.resize(index + 1, MatchAnswerID::default());
- }
- }
- if let Some(slot) = retained.column.get_mut(index) {
- let previous = std::mem::replace(slot, identity.unwrap_or_default());
- if previous != MatchAnswerID::default() {
- catalog.release_identity(previous);
- }
- }
- }
- if let Some(identity) = entry.cascade_input {
- if let Some(identity) = identity {
- catalog.transfer_pending(identity, AnswerReferenceCategory::Cascade);
- if retained.cascade_input_column.len() <= index {
- retained
- .cascade_input_column
- .resize(index + 1, MatchAnswerID::default());
- }
- }
- if let Some(slot) = retained.cascade_input_column.get_mut(index) {
- let previous = std::mem::replace(slot, identity.unwrap_or_default());
- if previous != MatchAnswerID::default() {
- catalog.release_cascade(previous);
- }
- }
- }
- }
- for (key, identity) in self.exact_answers {
- cache.install_exact_answer(catalog, key, identity);
- }
- }
-}
-
-#[derive(Clone, Default)]
-pub(super) struct RetainedMatchAnswers {
- pub(super) column: Vec<MatchAnswerID>,
- pub(super) cascade_input_column: Vec<MatchAnswerID>,
-}
-
-/// Activation-independent selector incidence recovered from retained exact match answers.
-///
-/// Active match answers normally discard a rule when its condition becomes false. This inverse
-/// relation preserves the selector side of that join, so a later condition flip can route through
-/// exact selector truth without evaluating the selector again. Incomplete retained coverage simply
-/// leaves program routing on its cold path.
-#[derive(Clone, Default)]
-pub(super) struct RetainedSelectorIncidences {
- by_program: Vec<Option<Arc<[RetainedSelectorIncidence]>>>,
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
-pub(super) struct RetainedSelectorIncidence {
- pub(super) node: StyleNodeID,
- pub(super) entry: u32,
-}
-
-impl RetainedSelectorIncidences {
- pub(super) fn lookup(&self, program: SelectorProgramID) -> Option<&Arc<[RetainedSelectorIncidence]>> {
- self.by_program.get(program.0 as usize).and_then(Option::as_ref)
- }
-
- pub(super) fn remember(
- &mut self,
- program: SelectorProgramID,
- incidences: Vec<RetainedSelectorIncidence>,
- ) -> Arc<[RetainedSelectorIncidence]> {
- let required_len = program.0 as usize + 1;
- let incidences: Arc<[RetainedSelectorIncidence]> = incidences.into();
- if self.by_program.len() < required_len {
- self.by_program.resize(required_len, None);
- }
- self.by_program[program.0 as usize] = Some(Arc::clone(&incidences));
- incidences
- }
-
- pub(super) fn clear(&mut self) {
- self.by_program = Vec::new();
- }
-}
-
-pub(super) struct RetainedAnswerPatch {
- pub(super) prefix_context: PrefixTransitionContext,
- /// Whether this transaction can reorder rules relative to each other (layer or sheet order).
- /// An unchanged match set can then still compact to a different winner, so the unchanged
- /// fast path must not conclude anything from set equality.
- pub(super) orders_shifted: bool,
- /// The affected (rule, program) identities, sorted, as the batch matcher's rule filter.
- pub(super) rule_keys: Vec<(RuleID, SelectorProgramID)>,
- pub(super) scope_program: ScopeProgramID,
- pub(super) dispatch: Arc<RuleDispatch>,
- /// One shared match workspace for every node this patch visits, carrying the relation and
- /// sibling-prefix caches across them exactly as a matching traversal does.
- pub(super) match_workspace: MatchScratch,
- pub(super) prefix_caches: std::sync::Arc<SharedPrefixCaches>,
- pub(super) dispatch_workspace: DispatchCandidateWorkspace,
- pub(super) always_emit: bool,
- pub(super) has_non_selector_inputs: bool,
- pub(super) always_emit_nodes: Vec<StyleNodeID>,
- /// A program join can make a rule contribute without producing a signed selector-truth delta
- /// for every node the join reaches. Those nodes must evaluate the affected rule set instead of
- /// treating deltas from concurrent element inputs as a complete patch.
- pub(super) requires_full_match: bool,
- pub(super) cascade_update_properties: Vec<u16>,
- pub(super) cascade_update_rules: Vec<RuleID>,
- /// Edited rules whose custom declarations moved, sorted: a node matching one reacts even
- /// when the patch moves none of its winners.
- pub(super) custom_changed_rules: Vec<RuleID>,
- pub(super) cascade_candidates: Vec<OrderedCascadeCandidate>,
- pub(super) cascade_compaction_workspace: ordering::CascadeCompactionWorkspace,
- pub(super) program_base_version: Option<ProgramVersion>,
- /// Memoized stopping delta transitions, shared by every node whose retained answer identity,
- /// compact cascade identity, and consolidated delta content are equal. The patch's cascade
- /// orders are fixed for the flush and the transition is node-independent for comparable
- /// document-scope answers, so a container of equal siblings pays the O(answer) derivation once
- /// and every further member is one column store.
- pub(super) delta_memo: HashMap<RetainedAnswerDeltaMemoKey, RetainedAnswerDeltaMemoEntry>,
-}
-
-#[derive(Clone, Copy, PartialEq, Eq, Hash)]
-pub(super) struct RetainedAnswerDeltaMemoKey {
- pub(super) old_answer: MatchAnswerID,
- pub(super) old_cascade_input: MatchAnswerID,
- pub(super) delta_count: usize,
- pub(super) delta_digest: u64,
-}
-
-pub(super) struct RetainedAnswerDeltaMemoEntry {
- pub(super) deltas: Vec<(RuleID, EntryID, SetChange)>,
- pub(super) transition: RetainedAnswerDeltaTransition,
-}
-
-impl RetainedAnswerDeltaMemoEntry {}
-
-pub(super) struct RetainedAnswerDeltaTransition {
- pub(super) new_answer: MatchAnswerID,
- /// The compact identity after the transition. Equal to the asker's old identity exactly when
- /// the transition stopped.
- pub(super) new_cascade_input: MatchAnswerID,
- /// The winner state the cohort's first member settled after applying the same deltas, with
- /// its program version, when one was retained. Emitting replays assign it by column store.
- pub(super) winner_state: Option<(CascadeStateID, ProgramVersion)>,
- /// The pseudo-element winner states the first member settled beside its winner state, of
- /// the same program version.
- pub(super) pseudo_winner_states: Box<[(super::tree::PseudoElementTarget, CascadeStateID)]>,
- /// Whether the first member's winner application reported an update, which decides whether
- /// replays hand the traversal an incremental cascade answer.
- pub(super) winners_updated: bool,
- pub(super) cascade_winners_are_complete: bool,
-}
-
-pub(super) struct RetainedAnswerPatchOutcome {
- pub(super) emit: bool,
- /// The patch proved the answer identity and winner state unchanged and emits only because
- /// the plan demands it; publication may confirm such a reaction away without any re-proof.
- pub(super) identity_preserved: bool,
- pub(super) incremental_cascade_answer: Option<IncrementalCascadeAnswer>,
-}
-
-pub(super) struct IncrementalCascadeAnswer {
- pub(super) node: StyleNodeID,
- pub(super) cascade_input: MatchAnswerID,
- pub(super) matches: Option<Box<[RuleMatch]>>,
- pub(super) cascade_winners_are_complete: bool,
-}
-
-impl RetainedAnswerPatch {
- pub(super) fn orders_shifted_for(&self, retained: &[RetainedRuleMatch]) -> bool {
- self.orders_shifted
- && retained
- .iter()
- .any(|entry| self.cascade_update_rules.binary_search(&entry.rule).is_ok())
- }
-
- pub(super) fn always_emit_for(&self, node: StyleNodeID) -> bool {
- self.always_emit || self.always_emit_nodes.binary_search(&node).is_ok()
- }
-}
-
-#[derive(Default)]
-pub(super) struct RetainedAnswerPatchSelection {
- pub(super) affected: Vec<RetainedAnswerPatchSelectionRule>,
- pub(super) always_emit: bool,
- pub(super) has_non_selector_inputs: bool,
- pub(super) always_emit_nodes: Vec<StyleNodeID>,
- pub(super) orders_shifted: bool,
- pub(super) requires_full_match: bool,
- pub(super) cascade_update_properties: Vec<u16>,
- pub(super) cascade_update_rules: Vec<RuleID>,
- pub(super) custom_changed_rules: Vec<RuleID>,
- pub(super) program_base_version: Option<ProgramVersion>,
-}
-
-pub(super) struct RetainedAnswerPatchSelectionRule {
- pub(super) rule: RuleID,
- pub(super) program: SelectorProgramID,
- pub(super) evaluate: bool,
-}
-
-impl RetainedMatchAnswers {
- pub(super) fn answer_identity(&self, node: StyleNodeID) -> Option<MatchAnswerID> {
- let index = node.element_index()? as usize;
- self.column
- .get(index)
- .copied()
- .filter(|identity| *identity != MatchAnswerID::default())
- }
-
- #[cfg(test)]
- pub(super) fn remember_prepared(
- &mut self,
- catalog: &mut MatchAnswerCatalog,
- node: StyleNodeID,
- answer: Vec<RetainedRuleMatch>,
- programs: &SelectorPrograms,
- ) -> Result<(), Vec<RetainedRuleMatch>> {
- if node.element_index().is_none() {
- return Err(answer);
- }
- let identity = catalog.intern_prepared(answer, programs);
- let mut effects = AnswerEffects::default();
- effects.remember_identity(node, identity, catalog);
- effects.install(self, catalog, &mut PrefixAnswerCache::default());
- Ok(())
- }
-
- #[cfg(test)]
- pub(super) fn remember_cascade_input(
- &mut self,
- catalog: &mut MatchAnswerCatalog,
- node: StyleNodeID,
- cascade_input: MatchAnswerID,
- ) {
- if node.element_index().is_none() {
- return;
- }
- let mut effects = AnswerEffects::default();
- effects.remember_cascade_input(node, cascade_input, catalog);
- effects.install(self, catalog, &mut PrefixAnswerCache::default());
- }
-
- pub(super) fn forget_cascade_input(&mut self, catalog: &mut MatchAnswerCatalog, node: StyleNodeID) {
- let Some(index) = node.element_index().map(|index| index as usize) else {
- return;
- };
- let Some(slot) = self.cascade_input_column.get_mut(index) else {
- return;
- };
- let previous = std::mem::take(slot);
- if previous != MatchAnswerID::default() {
- catalog.release_cascade(previous);
- }
- }
-
- pub(super) fn cascade_input_lookup(&self, node: StyleNodeID) -> Lookup<&MatchAnswerID, StyleNodeID> {
- let Some(index) = node.element_index().map(|index| index as usize) else {
- return Lookup::Missing(node);
- };
- match self.cascade_input_column.get(index) {
- Some(cascade_input) if *cascade_input != MatchAnswerID::default() => Lookup::Known(cascade_input),
- _ => Lookup::Missing(node),
- }
- }
-
- /// Retire the optional exact payload while preserving its compact semantic old side.
- pub(super) fn forget_answer(&mut self, catalog: &mut MatchAnswerCatalog, node: StyleNodeID) {
- let Some(index) = node.element_index().map(|index| index as usize) else {
- return;
- };
- if let Some(slot) = self.column.get_mut(index) {
- let identity = std::mem::take(slot);
- if identity != MatchAnswerID::default() {
- catalog.release_identity(identity);
- }
- }
- }
-
- pub(super) fn for_each_answer_node(&self, mut visit: impl FnMut(StyleNodeID)) {
- for (index, identity) in self.column.iter().enumerate().skip(1) {
- if *identity != MatchAnswerID::default() {
- visit(StyleNodeID::element(
- u32::try_from(index).expect("retained answer column exceeds style node identity space"),
- ));
- }
- }
- }
-
- pub(super) fn for_each_answer_containing_any_rule(
- &self,
- catalog: &MatchAnswerCatalog,
- rules: &[RuleID],
- mut visit: impl FnMut(StyleNodeID),
- ) {
- debug_assert!(rules.is_sorted());
- let mut contains_rule = HashMap::default();
- self.for_each_answer_node(|node| {
- let index = node.element_index().unwrap() as usize;
- let answer = self.column[index];
- if *contains_rule.entry(answer).or_insert_with(|| {
- catalog
- .retained_answer(answer)
- .is_some_and(|answer| answer.iter().any(|matched| rules.binary_search(&matched.rule).is_ok()))
- }) {
- visit(node);
- }
- });
- }
-
- /// Drop one node's retained answer. A plan that names a node no longer vouches for the answer
- /// remembered before the change it routes, and a departed identity must not leave one behind
- /// for a reused dense slot. The interned payload stays shared with any other node holding it.
- pub(super) fn forget(&mut self, catalog: &mut MatchAnswerCatalog, node: StyleNodeID) {
- self.forget_answer(catalog, node);
- self.forget_cascade_input(catalog, node);
- }
-
- pub(super) fn clear(&mut self, catalog: &mut MatchAnswerCatalog) {
- catalog.release_all_retained();
- self.column = Vec::new();
- }
-}
-
-impl RetainedMatchAnswers {
- pub(super) fn lookup(&self, node: StyleNodeID) -> Lookup<&MatchAnswerID, StyleNodeID> {
- let Some(index) = node.element_index().map(|index| index as usize) else {
- return Lookup::Missing(node);
- };
- let Some(identity) = self
- .column
- .get(index)
- .filter(|&&identity| identity != MatchAnswerID::default())
- else {
- return Lookup::Missing(node);
- };
- Lookup::Known(identity)
- }
-}
-
-/// Matching scratch owned by one synchronous style traversal.
-#[derive(Clone)]
-pub(super) struct BatchMatchingTraversal {
- pub(super) pending_published: PublishedMatchAnswers,
- pub(super) answer_effects: AnswerEffects,
- pub(super) prefix_contexts: PrefixTransitionContexts,
- pub(super) root: StyleNodeID,
- pub(super) batch: Option<MatchingFactBatch>,
- pub(super) topology: Option<TransactionTopology>,
- /// The dispatch a retained answer is read through, when the traversal reuses retained answers.
- pub(super) retained_answer_dispatch: Option<Arc<RuleDispatch>>,
- pub(super) ancestor_requirements: AncestorRequirementsCache,
- pub(super) prefix_caches: std::sync::Arc<SharedPrefixCaches>,
- pub(super) match_workspace: MatchScratch,
- pub(super) dispatch_workspace: DispatchCandidateWorkspace,
- pub(super) cascade_compaction_workspace: ordering::CascadeCompactionWorkspace,
- /// The fact rows the traversal's elements matched outside a batch, one per node. Facts do not change while the
- /// traversal runs, and the elements it matches share most of their ancestors.
- pub(super) unbatched_facts: StyleNodeFacts,
-}
-
-/// Current-side matching scratch produced by the transaction immediately before a style
-/// traversal.
-#[derive(Clone)]
-pub(super) struct PreparedBatchMatchingTraversal {
- pub(super) root: StyleNodeID,
- pub(super) batch: Option<MatchingFactBatch>,
- pub(super) topology: Option<TransactionTopology>,
- pub(super) reuse_retained_match_answers: bool,
- pub(super) match_workspace: MatchScratch,
-}
-
-impl PreparedBatchMatchingTraversal {
- pub(super) fn new(root: StyleNodeID) -> Self {
- Self {
- root,
- batch: None,
- topology: None,
- reuse_retained_match_answers: false,
- match_workspace: MatchScratch::default(),
- }
- }
-}
-
-/// Distinct retained cascade states per (dispatch key, winner-group generation), shared by the
-/// route-pruning proofs of one routing pass. `None` records incomplete posting coverage, which is
-/// a `false` verdict for every asker under that key.
-pub(super) type RoutePruningStateCache = HashMap<(DispatchKey, u64), Option<Arc<Vec<CascadeStateID>>>>;
-
-#[derive(Clone)]
-
-pub(super) struct PublishedMatchAnswer {
- pub(super) node: StyleNodeID,
- pub(super) cascade_input: Option<MatchAnswerID>,
- pub(super) matches: Option<Box<[RuleMatch]>>,
- pub(super) cascade_winners_are_complete: bool,
-}
-
-#[derive(Clone, Default)]
-pub(super) struct PublishedMatchAnswers {
- pub(super) answer_effects: AnswerEffects,
- pub(super) entries: Vec<PublishedMatchAnswer>,
- pub(super) shared_payloads: HashMap<MatchAnswerID, Box<[RuleMatch]>>,
- pub(super) match_element_calls_at_publication: u64,
-}
-
-impl PublishedMatchAnswers {
- pub(super) fn push(&mut self, mut entry: PublishedMatchAnswer, counters: &Counters) {
- if let Some(cascade_input) = entry.cascade_input {
- if let Some(matches) = entry.matches.take() {
- match self.shared_payloads.entry(cascade_input) {
- std::collections::hash_map::Entry::Occupied(_) => {
- counters.bump(Counter::PublishedMatchAnswerSharedPayloadReuses);
- }
- std::collections::hash_map::Entry::Vacant(shared) => {
- shared.insert(matches);
- counters.bump(Counter::PublishedMatchAnswerSharedPayloads);
- }
- }
- }
- } else {
- counters.bump(Counter::PublishedMatchAnswerContextualPayloads);
- }
- self.entries.push(entry);
- }
-
- /// Publish `entry` in its node's place, outside a batch, in place of any answer published for
- /// the node before.
- pub(super) fn publish(&mut self, entry: PublishedMatchAnswer, counters: &Counters) {
- let index = match self
- .entries
- .binary_search_by_key(&entry.node, |published| published.node)
- {
- Ok(index) => {
- self.entries.remove(index);
-
- index
- }
- Err(index) => index,
- };
- self.push(entry, counters);
- self.entries[index..].rotate_right(1);
- }
-
- pub(super) fn append_pending(&mut self, mut pending: Self) {
- if pending.entries.is_empty() {
- return;
- }
- self.entries.append(&mut pending.entries);
- for (identity, matches) in pending.shared_payloads.drain() {
- self.shared_payloads.entry(identity).or_insert(matches);
- }
- self.sort();
- }
-
- pub(super) fn sort(&mut self) {
- self.entries.sort_unstable_by_key(|entry| entry.node);
- }
-
- pub(super) fn lookup(&self, node: StyleNodeID) -> Option<&PublishedMatchAnswer> {
- let index = self.entries.binary_search_by_key(&node, |entry| entry.node).ok()?;
- self.entries.get(index)
- }
-
- pub(super) fn matches_for<'a>(&'a self, answer: &'a PublishedMatchAnswer) -> Option<&'a [RuleMatch]> {
- match answer.cascade_input {
- Some(cascade_input) => self.shared_payloads.get(&cascade_input).map(Box::as_ref),
- None => answer.matches.as_deref(),
- }
- }
-
- pub(super) fn clear(&mut self) {
- self.entries = Vec::new();
- self.shared_payloads = HashMap::default();
- }
-
- pub(super) fn release(mut self) {
- self.clear();
- }
-}
-
-pub(super) struct TransactionFactClassification {
- pub(super) prefix: Option<PrefixFactTransition>,
- pub(super) retained_truth_available: bool,
-}
-
-// A promoted batch costs one document row per element to build. Wait until local asks have already
-// packed four times that many rows, then require another ask to prove reuse. Even if that ask is the
-// traversal's last, the speculative rebuild keeps total packing below 1.25 times the local work.
-
-/// The document-origin sheets a tree scope adds to its own ordered sheet set.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
-pub(super) enum DocumentSheetMode {
- None,
- NonAuthor,
- All,
-}
-
-/// Every input that can change a scope's immutable selector dispatch or its static cascade ranks.
-///
-/// Constructed sheets commonly attach the same ordered set of programs to hundreds of shadow
-/// roots. The matches still belong to the concrete scope being evaluated, but the dispatch they
-/// evaluate against contains no scope-local state and can be shared wherever this key is equal.
-#[derive(Clone, Debug, PartialEq, Eq, Hash)]
-pub(super) struct ScopeDispatchKey {
- pub(super) depth: u32,
- pub(super) document_sheet_mode: DocumentSheetMode,
- pub(super) sheets: Vec<(SheetID, u64)>,
- pub(super) layer_order: Vec<(CascadeLayerID, u32)>,
-}
-
-/// The selector-derived topology shared by scopes whose concrete sheets contain the same compiled
-/// selector programs in the same order. Rule identities and cascade ranks remain scope-local.
-#[derive(Clone, Debug, PartialEq, Eq, Hash)]
-pub(super) struct ScopeDispatchShape(pub(super) SharedVector<(SelectorProgramID, bool)>);
-
-/// The pools for the shapes scope dispatches are keyed by.
-#[derive(Default)]
-pub(super) struct ScopeShapePools {
- dispatch_shapes: SharedVectorPool<(SelectorProgramID, bool)>,
- cascade_origins: SharedVectorPool<(u8, CascadeLayerID)>,
-}
-
-impl ScopeDispatchShape {
- pub(super) fn share(&mut self, pools: &mut ScopeShapePools) {
- self.0.share(&mut pools.dispatch_shapes);
- }
-}
-
-/// Every part of static cascade ordering that is not a concrete rule or sheet identity.
-#[derive(Clone, Debug, PartialEq, Eq, Hash)]
-pub(super) struct ScopeCascadeShape {
- pub(super) dispatch: ScopeDispatchShape,
- pub(super) depth: u32,
- pub(super) document_sheet_mode: DocumentSheetMode,
- pub(super) rule_origins_and_layers: SharedVector<(u8, CascadeLayerID)>,
- pub(super) layer_order: Vec<(CascadeLayerID, u32)>,
-}
-
-impl ScopeCascadeShape {
- pub(super) fn share(&mut self, pools: &mut ScopeShapePools) {
- // Cache keys contain immutable numeric identities. Equal scopes can share these arrays
- // without retaining any mutable cascade result.
- self.dispatch.share(pools);
- self.rule_origins_and_layers.share(&mut pools.cascade_origins);
- }
-}
-
-/// The ordered ancestor keys whose dense indices define an ancestor-requirement table.
-#[derive(Clone, Debug, PartialEq, Eq, Hash)]
-pub(super) struct AncestorDispatchShape(pub(super) Vec<DispatchKey>);
-
-define_id! {
- /// The immutable selector and static-cascade program shared by equivalent tree scopes.
- pub(super) struct ScopeProgramID(pub(super));
-}
-
-impl super::intern_table::InternIdentity for ScopeProgramID {
- fn index(self) -> usize {
- self.0 as usize
- }
-}
-
-#[derive(Clone)]
-
-pub(super) struct ScopeProgram {
- pub(super) key: ScopeDispatchKey,
- pub(super) dispatch: Arc<RuleDispatch>,
- /// The shapes the dispatch is filed under among the templates, which stay while a program has them.
- pub(super) shapes: ScopeTemplateShapes,
- pub(super) scope_count: u32,
-}
-
-/// The shapes one scope program's dispatch is filed under among the scope templates.
-#[derive(Clone)]
-pub(super) struct ScopeTemplateShapes {
- pub(super) dispatch: ScopeDispatchShape,
- pub(super) cascade: ScopeCascadeShape,
-}
-
-#[derive(Clone)]
-
-pub(super) struct ReplacedStyleRule {
- pub(super) rule: RuleID,
- pub(super) version: RuleVersion,
- pub(super) declared: Vec<DeclaredProperty>,
- pub(super) declarations_are_complete: bool,
- pub(super) gated_by_container_query: bool,
-}
-
-#[derive(Clone)]
-
-pub(super) struct PendingRuleDeclarationChange {
- pub(super) rule: RuleID,
- pub(super) old_properties: Vec<u16>,
- pub(super) new_properties: Vec<u16>,
- /// Whether the custom properties the rule declares moved. No winner column holds them, so
- /// no winner delta can show the edit; every node the rule matches reacts to it.
- pub(super) custom_declarations_changed: bool,
-}
-
-#[derive(Clone)]
-pub(super) struct PendingRuleDeclarations {
- pub(super) declared: Vec<DeclaredProperty>,
- pub(super) written_values: Vec<crate::css::style_value::RetainedStyleValueData>,
- pub(super) custom_declarations: Vec<super::program::CustomDeclaration>,
- pub(super) custom_written_values: Vec<crate::css::style_value::RetainedStyleValueData>,
-}
-
-#[derive(Clone)]
-
-pub(super) struct SheetRuleReplacement {
- pub(super) sheet: SheetID,
- pub(super) rules: Vec<ReplacedStyleRule>,
- pub(super) reused: usize,
- pub(super) reuse_disabled: bool,
-}
-
-#[cfg(test)]
-#[derive(Clone, Default)]
-pub(super) struct DiagnosticPlanCapture {
- pub(super) nodes: Vec<u32>,
- pub(super) scoped: bool,
-}
diff --git a/Libraries/LibWeb/Rust/src/css/style/column.rs b/Libraries/LibWeb/Rust/src/css/style/column.rs
index a5136a3e1d3..e75ab305ad5 100644
--- a/Libraries/LibWeb/Rust/src/css/style/column.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/column.rs
@@ -4,7 +4,6 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-use std::cell::RefCell;
use std::ops::{Deref, DerefMut};
/// A directly indexed column whose missing rows all have the same value.
@@ -29,13 +28,6 @@ impl<T: Default> Default for Column<T> {
}
impl<T: Default> Column<T> {
- pub(super) fn new(vacant: fn() -> T) -> Self {
- Self {
- entries: Vec::new(),
- vacant: Some(vacant),
- }
- }
-
/// Ensure that `index` is addressable and return newly allocated bytes.
pub(super) fn ensure(&mut self, index: usize) -> u64 {
if self.entries.len() > index {
@@ -56,11 +48,19 @@ impl<T: Default> Column<T> {
self.entries[index] = value;
growth
}
+}
- /// Return one mutable row, growing the column when it is absent.
- pub(super) fn entry(&mut self, index: usize) -> &mut T {
- self.ensure(index);
- &mut self.entries[index]
+impl<T> Column<T> {
+ /// The bytes of the column's rows, which hold nothing on the heap.
+ pub(super) fn heap_size(&self) -> usize {
+ crate::heap_size::vec_bytes(&self.entries)
+ }
+}
+
+impl<P: PagedColumnPage> PagedColumn<P> {
+ /// The bytes of the column's pages, which hold nothing on the heap.
+ pub(super) fn heap_size(&self) -> usize {
+ crate::heap_size::vec_bytes(&self.pages) + self.pages.iter().flatten().count() * size_of::<P>()
}
}
@@ -87,123 +87,6 @@ impl<T> IntoIterator for Column<T> {
}
}
-/// A directly indexed side table whose rows are invalidated by advancing a stamp instead of being
-/// cleared, and whose storage is borrowed from a thread-local pool instead of allocated.
-///
-/// NB: A side table that one transaction fills and the next discards has two tempting shapes, and
-/// both charge for something other than the batch. A hash map pays one probe per access and
-/// rebuilds its table as the batch grows. A freshly allocated dense column pays to fill the
-/// identity space between the rows it holds, which one high identity widens across the whole
-/// element space. Keeping the storage between transactions removes both: growth is paid once
-/// at the high-water mark, reset is one increment, and a row is one array read.
-#[derive(Clone, Default)]
-pub(super) struct StampedIndex {
- rows: Vec<StampedRow>,
- stamp: u32,
-}
-
-#[derive(Clone, Copy, Default)]
-struct StampedRow {
- /// The stamp this row was written under. Zero is never a live stamp, so rows grown into
- /// existence and rows left by an earlier transaction both read as absent.
- stamp: u32,
- value: u32,
-}
-
-impl StampedIndex {
- /// Abandon every row written under the previous stamp.
- fn begin(&mut self) {
- match self.stamp.checked_add(1) {
- Some(stamp) => self.stamp = stamp,
- // The stamp space is exhausted only after four billion transactions on one buffer.
- // Dropping the rows makes every later row start from the unwritten stamp again.
- None => {
- self.rows.clear();
- self.stamp = 1;
- }
- }
- }
-
- fn get(&self, index: usize) -> Option<u32> {
- self.rows
- .get(index)
- .filter(|row| row.stamp == self.stamp)
- .map(|row| row.value)
- }
-
- fn insert(&mut self, index: usize, value: u32) {
- if self.rows.len() <= index {
- self.rows.resize(index + 1, StampedRow::default());
- }
- self.rows[index] = StampedRow {
- stamp: self.stamp,
- value,
- };
- }
-
- fn capacity_bytes(&self) -> usize {
- self.rows.capacity() * size_of::<StampedRow>()
- }
-}
-
-thread_local! {
- static STAMPED_INDEX_POOL: RefCell<Vec<StampedIndex>> = const { RefCell::new(Vec::new()) };
-}
-
-/// How many buffers one thread keeps between transactions. Concurrently live effect tables are
-/// the contexts a single matching pass has open, not the nodes it visits.
-///
-/// NB: A buffer in the pool is memory the process holds while no owner leases it. These bounds
-/// are what keep that residency small: at most this many buffers, and at most this many bytes
-/// across all of them, since a buffer grows to the highest element identity it was ever asked
-/// for.
-const STAMPED_INDEX_POOL_LIMIT: usize = 8;
-const STAMPED_INDEX_POOL_BYTE_LIMIT: usize = 4 << 20;
-
-/// A [`StampedIndex`] taken from the thread's pool on first write and returned when dropped.
-///
-/// NB: Construction must stay free. Contexts that own one of these are created and discarded
-/// around individual nodes, and most of them never record a row.
-#[derive(Clone, Default)]
-pub(super) struct PooledStampedIndex(Option<StampedIndex>);
-
-impl PooledStampedIndex {
- pub(super) fn get(&self, index: usize) -> Option<u32> {
- self.0.as_ref()?.get(index)
- }
-
- pub(super) fn insert(&mut self, index: usize, value: u32) {
- self.0
- .get_or_insert_with(|| {
- let mut borrowed = STAMPED_INDEX_POOL
- .try_with(|pool| pool.borrow_mut().pop())
- .ok()
- .flatten()
- .unwrap_or_default();
- borrowed.begin();
- borrowed
- })
- .insert(index, value);
- }
-}
-
-impl Drop for PooledStampedIndex {
- fn drop(&mut self) {
- let Some(borrowed) = self.0.take() else {
- return;
- };
- let _ = STAMPED_INDEX_POOL.try_with(|pool| {
- let mut pool = pool.borrow_mut();
- let pooled_bytes: usize = pool.iter().map(StampedIndex::capacity_bytes).sum();
- if pool.len() < STAMPED_INDEX_POOL_LIMIT
- && pooled_bytes + borrowed.capacity_bytes() <= STAMPED_INDEX_POOL_BYTE_LIMIT
- {
- pool.push(borrowed);
- }
- });
- }
-}
-
/// A directly indexed packed boolean column.
#[derive(Clone, Default)]
pub(super) struct BitColumn {
@@ -222,6 +105,10 @@ impl PartialEq for BitColumn {
impl Eq for BitColumn {}
impl BitColumn {
+ pub(super) fn heap_size(&self) -> usize {
+ crate::heap_size::vec_bytes(&self.words)
+ }
+
/// Set one bit and return whether its value changed and newly allocated bytes.
pub(super) fn set(&mut self, index: usize, value: bool) -> (bool, u64) {
let word_index = index / u64::BITS as usize;
@@ -248,10 +135,6 @@ impl BitColumn {
let mask = 1_u64 << (index % u64::BITS as usize);
self.words.get(word).is_some_and(|word| word & mask != 0)
}
-
- pub(super) fn clear(&mut self) {
- self.words.fill(0);
- }
}
/// One specialized page stored by a [`PagedColumn`].
@@ -268,39 +151,6 @@ pub(super) trait RemovablePagedColumnPage: PagedColumnPage {
fn remove(&mut self, index: usize) -> Option<Self::Value>;
}
-pub(super) const PAGED_VALUE_PAGE_SHIFT: usize = 6;
-const PAGED_VALUE_PAGE_SIZE: usize = 1 << PAGED_VALUE_PAGE_SHIFT;
-
-#[derive(Clone)]
-pub(super) struct PagedValuePage<T: Copy + Default> {
- known: u64,
- values: [T; PAGED_VALUE_PAGE_SIZE],
-}
-
-impl<T: Copy + Default> Default for PagedValuePage<T> {
- fn default() -> Self {
- Self {
- known: 0,
- values: [T::default(); PAGED_VALUE_PAGE_SIZE],
- }
- }
-}
-
-impl<T: Copy + Default> PagedColumnPage for PagedValuePage<T> {
- type Value = T;
-
- const SHIFT: usize = PAGED_VALUE_PAGE_SHIFT;
-
- fn get(&self, index: usize) -> Option<T> {
- (self.known & (1 << index) != 0).then_some(self.values[index])
- }
-
- fn insert(&mut self, index: usize, value: T) {
- self.known |= 1 << index;
- self.values[index] = value;
- }
-}
-
/// A sparse column whose directory and page accounting are shared across page layouts.
#[derive(Clone)]
pub(super) struct PagedColumn<P: PagedColumnPage> {
@@ -344,19 +194,10 @@ impl<P: PagedColumnPage> PagedColumn<P> {
(page, page_was_absent)
}
- pub(super) fn pages_mut(&mut self) -> impl Iterator<Item = &mut P> {
- self.pages.iter_mut().flatten().map(Box::as_mut)
- }
-
#[cfg(test)]
pub(super) fn page_count(&self) -> usize {
self.page_count
}
-
- #[cfg(test)]
- pub(super) fn directory_capacity(&self) -> usize {
- self.pages.capacity()
- }
}
impl<P: RemovablePagedColumnPage> PagedColumn<P> {
@@ -368,88 +209,9 @@ impl<P: RemovablePagedColumnPage> PagedColumn<P> {
}
}
-/// Dense marks compared against an externally owned epoch.
-#[derive(Clone, Default)]
-pub(super) struct EpochColumn {
- marks: Vec<u32>,
-}
-
-impl EpochColumn {
- pub(super) fn ensure_len(&mut self, len: usize) {
- if self.marks.len() < len {
- self.marks.resize(len, 0);
- }
- }
-
- pub(super) fn mark(&mut self, index: usize, epoch: u32) -> bool {
- self.ensure_len(index + 1);
- let was_marked = self.marks[index] == epoch;
- self.marks[index] = epoch;
- !was_marked
- }
-
- fn clear(&mut self) {
- self.marks.fill(0);
- }
-}
-
-impl Deref for EpochColumn {
- type Target = Vec<u32>;
-
- fn deref(&self) -> &Self::Target {
- &self.marks
- }
-}
-
-impl DerefMut for EpochColumn {
- fn deref_mut(&mut self) -> &mut Self::Target {
- &mut self.marks
- }
-}
-
-/// Advance a shared epoch, clearing every participating column on wrap.
-pub(super) fn advance_epoch(epoch: &mut u32, step: u32, columns: &mut [&mut EpochColumn]) -> u32 {
- if let Some(next) = epoch.checked_add(step) {
- *epoch = next;
- } else {
- for column in columns {
- column.clear();
- }
- *epoch = step;
- }
- *epoch
-}
-
#[cfg(test)]
mod tests {
use super::BitColumn;
- use super::PooledStampedIndex;
-
- #[test]
- fn stamped_index_rows_do_not_survive_their_owner() {
- let mut first = PooledStampedIndex::default();
- first.insert(4, 7);
- first.insert(9, 11);
- assert_eq!(first.get(4), Some(7));
- assert_eq!(first.get(9), Some(11));
- assert_eq!(first.get(5), None);
- assert_eq!(first.get(4000), None);
- drop(first);
-
- // The pooled rows are still allocated; the advanced stamp is what hides them.
- let mut second = PooledStampedIndex::default();
- assert_eq!(second.get(4), None);
- assert_eq!(second.get(9), None);
- second.insert(9, 3);
- assert_eq!(second.get(9), Some(3));
- assert_eq!(second.get(4), None);
- }
-
- #[test]
- fn stamped_index_costs_nothing_until_it_holds_a_row() {
- let index = PooledStampedIndex::default();
- assert_eq!(index.get(0), None);
- }
#[test]
fn bit_column_equality_ignores_trailing_zero_words() {
diff --git a/Libraries/LibWeb/Rust/src/css/style/dom_reads.rs b/Libraries/LibWeb/Rust/src/css/style/dom_reads.rs
new file mode 100644
index 00000000000..799685beb27
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/dom_reads.rs
@@ -0,0 +1,136 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use super::*;
+
+// The DOM shape layout, painting and style computation read from the style mirror. Every answer
+// is an ID or a value, so readers do not depend on how the mirror stores its relations.
+impl RetainedState {
+ /// The DOM parent of an element, shadow root or the document element: an element, a shadow
+ /// root or the document.
+ #[must_use]
+ pub fn dom_parent(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ self.projection.parent(node)
+ }
+
+ /// The DOM parent of an element, where a shadow root stands for its host.
+ #[must_use]
+ pub fn parent_element_or_host(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ self.projection
+ .parent(node)
+ .map(|parent| self.projection.host_of(parent).unwrap_or(parent))
+ }
+
+ /// The DOM parent of a node, or the host of a shadow root.
+ #[must_use]
+ pub fn parent_or_shadow_host(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ self.projection.parent_or_shadow_host(node)
+ }
+
+ /// The tree scope the element is in.
+ #[must_use]
+ pub fn element_tree_scope(&self, node: StyleNodeID) -> TreeScopeID {
+ self.projection.tree_scope(node)
+ }
+
+ #[must_use]
+ pub fn first_element_child(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ self.projection.first_element_child(node)
+ }
+
+ #[must_use]
+ pub fn next_element_sibling(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ self.projection.next_element_sibling(node)
+ }
+
+ /// Whether the node stands in the mirror only to carry relations, as the document and a
+ /// shadow root do, rather than being an element.
+ #[must_use]
+ pub fn is_relation_only(&self, node: StyleNodeID) -> bool {
+ self.tree.is_relation_only(node)
+ }
+
+ /// Whether `node` is `root` or is under it, crossing into shadow trees.
+ #[must_use]
+ pub fn is_in_shadow_including_subtree_of(&self, node: StyleNodeID, root: StyleNodeID) -> bool {
+ if node == root {
+ return true;
+ }
+ // A text node has no projection row, so it is answered for by the element it is linked
+ // under.
+ let element = match node.text_index() {
+ Some(_) => match self.tree.text_parent(node) {
+ Some(parent) => parent,
+ None => return false,
+ },
+ None => node,
+ };
+ self.projection.is_in_shadow_including_subtree_of(element, root)
+ }
+
+ /// The shadow root the element `host` hosts, if any.
+ #[must_use]
+ pub fn shadow_root_of(&self, host: StyleNodeID) -> Option<StyleNodeID> {
+ self.projection.shadow_root_of(host)
+ }
+
+ /// The host of the shadow root `shadow_root`, or none for any other node.
+ #[must_use]
+ pub fn host_of(&self, shadow_root: StyleNodeID) -> Option<StyleNodeID> {
+ self.projection.host_of(shadow_root)
+ }
+
+ /// The host of the shadow tree the node is in, if any.
+ #[must_use]
+ pub fn shadow_host_of(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ self.projection.shadow_host_of(node)
+ }
+
+ /// The slot the element or text node is assigned to, if any.
+ #[must_use]
+ pub fn assigned_slot_of(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ self.projection.assigned_slot_of(node)
+ }
+
+ /// How many nodes are assigned to the slot.
+ #[must_use]
+ pub fn assigned_node_count(&self, slot: StyleNodeID) -> usize {
+ self.projection.assigned_nodes_of(slot).len()
+ }
+
+ /// The node at `index` among those assigned to the slot, in assignment order.
+ #[must_use]
+ pub fn assigned_node(&self, slot: StyleNodeID, index: usize) -> StyleNodeID {
+ self.projection.assigned_nodes_of(slot)[index]
+ }
+
+ /// The node's DOM children in order, text nodes included.
+ pub fn dom_children(&self, node: StyleNodeID) -> impl Iterator<Item = StyleNodeID> + '_ {
+ self.tree.dom_children(node)
+ }
+
+ #[must_use]
+ pub fn next_sibling_in_dom_order(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ self.tree.next_sibling_in_dom_order(node)
+ }
+
+ #[must_use]
+ pub fn previous_sibling_in_dom_order(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ self.tree.previous_sibling_in_dom_order(node)
+ }
+
+ /// The DOM parent of a text node, or none for anything else.
+ #[must_use]
+ pub fn text_parent(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ self.tree.text_parent(node)
+ }
+
+ /// The element at `index` in the top layer, in the order the elements were added.
+ #[must_use]
+ pub fn top_layer_element(&self, index: usize) -> Option<StyleNodeID> {
+ self.tree.top_layer().get(index).copied()
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/element_declarations.rs b/Libraries/LibWeb/Rust/src/css/style/element_declarations.rs
new file mode 100644
index 00000000000..0f7e69b8d58
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/element_declarations.rs
@@ -0,0 +1,950 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The declarations attached to each element: its inline style, presentational hints and SVG
+//! presentation attributes, each with the values they were written with.
+
+use super::fast_hash::FastSet as HashSet;
+use super::index::StyleAtomID;
+use super::input_types::ElementDeclarationKind;
+use super::pipeline::rule_store::CustomDeclaration;
+use super::tree::StyleNodeID;
+use crate::cow_column::CowVec;
+use crate::css::declaration_block::DeclarationEntry;
+use crate::css::style_value::RetainedStyleValueData;
+
+type Checks = super::pipeline::compute::WrittenValueChecks;
+
+/// One kind of an element's own declarations: what each covers, the value it was written with,
+/// and what the drive checks of that value, borrowed from the element's row.
+#[derive(Clone, Copy, Default)]
+pub struct ElementDeclarations<'a> {
+ declared: &'a [DeclarationEntry],
+ written: &'a [RetainedStyleValueData],
+ checks: &'a [Checks],
+}
+
+impl<'a> ElementDeclarations<'a> {
+ /// The value the declaration at `index` of `declared` was written with.
+ #[must_use]
+ pub fn written(self, index: usize) -> &'a RetainedStyleValueData {
+ &self.written[index]
+ }
+
+ /// The declared property at `index`, parallel to its written value.
+ pub(in crate::css::style) fn declared_property(self, index: usize) -> Option<&'a DeclarationEntry> {
+ self.declared.get(index)
+ }
+
+ pub(in crate::css::style) fn checks(self, index: usize) -> Checks {
+ self.checks[index]
+ }
+
+ /// What each declaration covers.
+ pub(in crate::css::style) fn declared(self) -> &'a [DeclarationEntry] {
+ self.declared
+ }
+
+ pub fn iter(
+ self,
+ ) -> std::iter::Zip<std::slice::Iter<'a, DeclarationEntry>, std::slice::Iter<'a, RetainedStyleValueData>> {
+ self.declared.iter().zip(self.written.iter())
+ }
+}
+
+/// Declarations standing for their written values with the guaranteed-invalid one, for a test
+/// that reads no value.
+#[cfg(test)]
+fn unwritten_declarations(declared: &[DeclarationEntry]) -> Vec<(DeclarationEntry, RetainedStyleValueData)> {
+ declared
+ .iter()
+ .map(|&declared| {
+ (
+ declared,
+ RetainedStyleValueData::from_owned(crate::css::style_value::StyleValueData::GuaranteedInvalid),
+ )
+ })
+ .collect()
+}
+
+/// The custom properties an element's inline style declares, in declaration order, each with
+/// the value it was written with, as its row holds them.
+#[derive(Clone, Copy)]
+pub(in crate::css::style) struct ElementCustomDeclarations<'a> {
+ declared: &'a [CustomDeclaration],
+ written: &'a [RetainedStyleValueData],
+}
+
+impl<'a> ElementCustomDeclarations<'a> {
+ #[must_use]
+ pub(in crate::css::style) fn declared(self) -> &'a [CustomDeclaration] {
+ self.declared
+ }
+
+ /// The values the declarations were written with, parallel to them.
+ pub(in crate::css::style) fn written_values(self) -> &'a [RetainedStyleValueData] {
+ self.written
+ }
+
+ /// The declarations, copied out.
+ fn copy(self) -> Vec<CustomDeclarationWritten> {
+ self.declared
+ .iter()
+ .copied()
+ .zip(self.written.iter().cloned())
+ .collect()
+ }
+}
+
+/// One custom property an element's inline style declares, with the value it was written with,
+/// as a row is built from them.
+type CustomDeclarationWritten = (CustomDeclaration, RetainedStyleValueData);
+
+/// The start of an element's declaration row. Where the row holds custom declarations, a word
+/// counting them follows the header, then two parallel arrays, the values they were written with
+/// and their declarations. The declarations of every kind follow as three parallel arrays, the
+/// values they were written with, their checks and their entries, each kind's declarations after
+/// those of the kinds before it, the narrower arrays last so that none needs padding.
+#[repr(C)]
+struct RowHeader {
+ /// The rows sharing this allocation: copies of a store, as a fork of the render state makes, share every row until
+ /// one of them writes it.
+ references: std::sync::atomic::AtomicU32,
+ /// Where the declarations of each kind end, by `ElementDeclarationKind::index`, the first with
+ /// `CUSTOM_SLOT` set where the custom declarations follow the header.
+ ends: [u32; ElementDeclarationKind::COUNT],
+}
+
+const _: () = assert!(size_of::<RowHeader>() == 16);
+
+/// The bit of a row's first end that says custom declarations follow the header. Only the `style`
+/// attribute declares custom properties, so most rows have none.
+const CUSTOM_SLOT: u32 = 1 << 31;
+
+/// The word that counts a row's custom declarations, where it holds any.
+#[repr(C)]
+struct CustomCount {
+ count: u32,
+ _padding: u32,
+}
+
+// NB: The custom count and the arrays follow the header and one another with no padding between them.
+const _: () = assert!(size_of::<RowHeader>().is_multiple_of(ROW_ALIGNMENT));
+const _: () = assert!(size_of::<CustomCount>() == ROW_ALIGNMENT && align_of::<CustomCount>() <= ROW_ALIGNMENT);
+const _: () = assert!(size_of::<CustomDeclaration>() == 8 && align_of::<CustomDeclaration>() <= ROW_ALIGNMENT);
+const _: () = assert!(size_of::<DeclarationEntry>() == 2);
+const _: () = assert!(size_of::<RetainedStyleValueData>() == 8 && align_of::<RetainedStyleValueData>() <= 8);
+const _: () = assert!(size_of::<Checks>() == 4 && align_of::<Checks>() <= 8);
+
+/// The alignment of a row's allocation, which every word after the header shares.
+const ROW_ALIGNMENT: usize = 8;
+
+/// The bytes one declaration takes in each of the three arrays together.
+const DECLARATION_BYTES: usize =
+ size_of::<DeclarationEntry>() + size_of::<RetainedStyleValueData>() + size_of::<Checks>();
+
+/// The bytes one custom declaration takes in its two arrays together.
+const CUSTOM_DECLARATION_BYTES: usize = size_of::<RetainedStyleValueData>() + size_of::<CustomDeclaration>();
+
+/// The bytes a row's `custom_count` custom declarations take after its header, with their count.
+fn custom_bytes(custom_count: usize) -> usize {
+ match custom_count {
+ 0 => 0,
+ _ => size_of::<CustomCount>() + CUSTOM_DECLARATION_BYTES * custom_count,
+ }
+}
+
+fn row_layout(count: usize, custom_count: usize) -> std::alloc::Layout {
+ std::alloc::Layout::from_size_align(
+ size_of::<RowHeader>() + custom_bytes(custom_count) + DECLARATION_BYTES * count,
+ ROW_ALIGNMENT,
+ )
+ .expect("an element's declarations fit in memory")
+}
+
+/// One of an element's own declarations, as a row is built from them.
+pub(in crate::css::style) type ElementDeclaration = (DeclarationEntry, RetainedStyleValueData);
+
+/// An element's own declarations, of every kind, with the custom properties its inline style
+/// declares, in one allocation.
+pub(in crate::css::style) struct ElementDeclarationRow(std::ptr::NonNull<RowHeader>);
+
+// SAFETY: The row owns its allocation, whose values are shareable across threads.
+unsafe impl Send for ElementDeclarationRow {}
+// SAFETY: As above; nothing mutates a row through a shared reference.
+unsafe impl Sync for ElementDeclarationRow {}
+
+/// An element's inline declaration, taken out of its row while a private demand computes the
+/// element as though it had none.
+pub(super) struct HiddenInlineDeclarations {
+ declarations: Vec<(DeclarationEntry, RetainedStyleValueData, Checks)>,
+ custom: Vec<CustomDeclarationWritten>,
+}
+
+impl ElementDeclarationRow {
+ /// The declarations of each kind, by `ElementDeclarationKind::index`, with the custom
+ /// properties the inline style declares.
+ pub(in crate::css::style) fn new(
+ by_kind: [Vec<ElementDeclaration>; ElementDeclarationKind::COUNT],
+ custom: Vec<CustomDeclarationWritten>,
+ ) -> Self {
+ let mut ends = [0; ElementDeclarationKind::COUNT];
+ let mut end = 0;
+ for (kind, declarations) in by_kind.iter().enumerate() {
+ end += declarations.len();
+ ends[kind] = u32::try_from(end).expect("an element's declarations fit in u32");
+ }
+ Self::build(
+ by_kind.into_iter().flatten().map(|(declared, written)| {
+ let checks = Checks::prepare(declared.property(), &written);
+ (declared, written, checks)
+ }),
+ ends,
+ custom,
+ )
+ }
+
+ /// A row of `declarations`, the declarations of each kind ending where `ends` says.
+ fn build(
+ declarations: impl Iterator<Item = (DeclarationEntry, RetainedStyleValueData, Checks)>,
+ ends: [u32; ElementDeclarationKind::COUNT],
+ custom: Vec<CustomDeclarationWritten>,
+ ) -> Self {
+ let count = ends[ElementDeclarationKind::COUNT - 1] as usize;
+ assert!(
+ ends[0] & CUSTOM_SLOT == 0,
+ "an element's declarations are fewer than its row can count"
+ );
+ let custom_count = custom.len();
+ let layout = row_layout(count, custom_count);
+ // SAFETY: The layout is never zero-sized, as it holds the header.
+ let pointer = unsafe { std::alloc::alloc(layout) }.cast::<RowHeader>();
+ let Some(header) = std::ptr::NonNull::new(pointer) else {
+ std::alloc::handle_alloc_error(layout);
+ };
+ // SAFETY: The allocation holds the header, the custom count and `custom_count` entries of
+ // each custom array, and `count` entries of each other array, which are written once
+ // each, at the alignment of their elements.
+ unsafe {
+ let mut stored_ends = ends;
+ if custom_count != 0 {
+ stored_ends[0] |= CUSTOM_SLOT;
+ }
+ header.write(RowHeader {
+ references: std::sync::atomic::AtomicU32::new(1),
+ ends: stored_ends,
+ });
+ let row = Self(header);
+ if custom_count != 0 {
+ header.add(1).cast::<CustomCount>().write(CustomCount {
+ count: u32::try_from(custom_count).expect("an element's custom declarations fit in u32"),
+ _padding: 0,
+ });
+ let (custom_written, custom_declared) = row.custom_arrays(custom_count);
+ for (index, (declared, written)) in custom.into_iter().enumerate() {
+ custom_declared.cast_mut().add(index).write(declared);
+ custom_written.cast_mut().add(index).write(written);
+ }
+ }
+ let (declared, written, checks) = row.arrays(count);
+ let mut written_count = 0;
+ for (index, entry) in declarations.enumerate() {
+ assert!(index < count, "an element's declarations are as many as its ends say");
+ declared.cast_mut().add(index).write(entry.0);
+ written.cast_mut().add(index).write(entry.1);
+ checks.cast_mut().add(index).write(entry.2);
+ written_count += 1;
+ }
+ assert_eq!(
+ written_count, count,
+ "an element's declarations are as many as its ends say"
+ );
+ row
+ }
+ }
+
+ fn header(&self) -> &RowHeader {
+ // SAFETY: The row owns its allocation, which starts with the header.
+ unsafe { self.0.as_ref() }
+ }
+
+ /// Where the declarations of each kind end.
+ fn ends(&self) -> [u32; ElementDeclarationKind::COUNT] {
+ let mut ends = self.header().ends;
+ ends[0] &= !CUSTOM_SLOT;
+ ends
+ }
+
+ fn count(&self) -> usize {
+ self.ends()[ElementDeclarationKind::COUNT - 1] as usize
+ }
+
+ /// How many custom declarations the row holds.
+ fn custom_count(&self) -> usize {
+ if self.header().ends[0] & CUSTOM_SLOT == 0 {
+ return 0;
+ }
+ // SAFETY: The count follows the header where the header says so.
+ unsafe { (*self.0.as_ptr().add(1).cast::<CustomCount>()).count as usize }
+ }
+
+ /// The starts of the two custom arrays of a row holding `custom_count` custom declarations.
+ fn custom_arrays(&self, custom_count: usize) -> (*const RetainedStyleValueData, *const CustomDeclaration) {
+ // SAFETY: The custom arrays lie within the allocation, one after the other past the header
+ // and the custom count.
+ unsafe {
+ let written = self
+ .0
+ .as_ptr()
+ .add(1)
+ .cast::<CustomCount>()
+ .add(1)
+ .cast::<RetainedStyleValueData>();
+ let declared = written.add(custom_count).cast::<CustomDeclaration>();
+ (written.cast_const(), declared.cast_const())
+ }
+ }
+
+ /// The starts of the three arrays of a row holding `count` declarations.
+ fn arrays(&self, count: usize) -> (*const DeclarationEntry, *const RetainedStyleValueData, *const Checks) {
+ // SAFETY: The arrays lie within the allocation, one after another past the header and the
+ // custom declarations.
+ unsafe {
+ let written = self
+ .0
+ .as_ptr()
+ .add(1)
+ .cast::<u8>()
+ .add(custom_bytes(self.custom_count()))
+ .cast::<RetainedStyleValueData>();
+ let checks = written.add(count).cast::<Checks>();
+ let declared = checks.add(count).cast::<DeclarationEntry>();
+ (declared, written, checks)
+ }
+ }
+
+ /// Every declaration of the row, of every kind.
+ fn all(&self) -> ElementDeclarations<'_> {
+ let count = self.count();
+ let (declared, written, checks) = self.arrays(count);
+ // SAFETY: The row was built with `count` entries in each array, which live as it does.
+ unsafe {
+ ElementDeclarations {
+ declared: ak::slice_from_raw_parts(declared, count),
+ written: ak::slice_from_raw_parts(written, count),
+ checks: ak::slice_from_raw_parts(checks, count),
+ }
+ }
+ }
+
+ /// The declarations of `kind`.
+ pub(in crate::css::style) fn declarations(&self, kind: ElementDeclarationKind) -> ElementDeclarations<'_> {
+ let ends = self.ends();
+ let start = match kind.index() {
+ 0 => 0,
+ index => ends[index - 1] as usize,
+ };
+ let range = start..ends[kind.index()] as usize;
+ let all = self.all();
+ ElementDeclarations {
+ declared: &all.declared[range.clone()],
+ written: &all.written[range.clone()],
+ checks: &all.checks[range],
+ }
+ }
+
+ /// The custom properties the inline style declares, if any.
+ pub(in crate::css::style) fn custom(&self) -> Option<ElementCustomDeclarations<'_>> {
+ let custom_count = self.custom_count();
+ if custom_count == 0 {
+ return None;
+ }
+ let (written, declared) = self.custom_arrays(custom_count);
+ // SAFETY: The row was built with `custom_count` entries in each custom array, which live as it does.
+ unsafe {
+ Some(ElementCustomDeclarations {
+ declared: ak::slice_from_raw_parts(declared, custom_count),
+ written: ak::slice_from_raw_parts(written, custom_count),
+ })
+ }
+ }
+
+ /// The row's custom declarations, copied out.
+ fn copy_custom(&self) -> Vec<CustomDeclarationWritten> {
+ self.custom().map_or_else(Vec::new, ElementCustomDeclarations::copy)
+ }
+
+ /// This row with the declarations of `kind` replaced by `declarations`, and its custom
+ /// declarations by `custom`.
+ fn with(
+ &self,
+ kind: ElementDeclarationKind,
+ declarations: impl ExactSizeIterator<Item = (DeclarationEntry, RetainedStyleValueData, Checks)>,
+ custom: Vec<CustomDeclarationWritten>,
+ ) -> Self {
+ let mut ends = [0; ElementDeclarationKind::COUNT];
+ let mut end = 0;
+ for other in ElementDeclarationKind::ALL {
+ end += match other == kind {
+ true => declarations.len(),
+ false => self.declarations(other).declared.len(),
+ };
+ ends[other.index()] = u32::try_from(end).expect("an element's declarations fit in u32");
+ }
+ let mut declarations = Some(declarations);
+ let entries = ElementDeclarationKind::ALL.into_iter().flat_map(|other| {
+ let (own, replaced) = match other == kind {
+ true => (None, declarations.take()),
+ false => (Some(self.declarations(other)), None),
+ };
+ let own = own.into_iter().flat_map(|own| {
+ (0..own.declared.len())
+ .map(move |index| (own.declared[index], own.written[index].clone(), own.checks[index]))
+ });
+ own.chain(replaced.into_iter().flatten())
+ });
+ Self::build(entries, ends, custom)
+ }
+
+ /// The declarations of `kind`, copied out.
+ fn copy_of(&self, kind: ElementDeclarationKind) -> Vec<(DeclarationEntry, RetainedStyleValueData, Checks)> {
+ let own = self.declarations(kind);
+ (0..own.declared.len())
+ .map(|index| (own.declared[index], own.written[index].clone(), own.checks[index]))
+ .collect()
+ }
+
+ fn storage_bytes(&self) -> usize {
+ row_layout(self.count(), self.custom_count()).size()
+ }
+
+ fn is_empty(&self) -> bool {
+ self.count() == 0 && self.custom().is_none()
+ }
+
+ /// The hash of what the row declares: its declarations of each kind, and its custom ones.
+ fn content_hash(&self) -> u64 {
+ use std::hash::{Hash, Hasher};
+ let mut hasher = crate::fast_hash::fast_hasher();
+ self.ends().hash(&mut hasher);
+ let all = self.all();
+ all.declared.hash(&mut hasher);
+ let custom = self.custom();
+ custom.map(ElementCustomDeclarations::declared).hash(&mut hasher);
+ let custom_written = custom.map_or(&[][..], ElementCustomDeclarations::written_values);
+ for value in all.written.iter().chain(custom_written) {
+ crate::css::style_value::style_value_content_hash(value.optional_data()).hash(&mut hasher);
+ }
+ hasher.finish()
+ }
+
+ /// Whether the two rows declare the same, written with values of equal content.
+ fn declares_the_same_as(&self, other: &Self) -> bool {
+ fn custom_written(row: &ElementDeclarationRow) -> &[RetainedStyleValueData] {
+ row.custom().map_or(&[], ElementCustomDeclarations::written_values)
+ }
+ self.0 == other.0
+ || (self.ends() == other.ends()
+ && self.all().declared == other.all().declared
+ && self.all().written == other.all().written
+ && self.custom().map(ElementCustomDeclarations::declared)
+ == other.custom().map(ElementCustomDeclarations::declared)
+ && custom_written(self) == custom_written(other))
+ }
+}
+
+impl Clone for ElementDeclarationRow {
+ fn clone(&self) -> Self {
+ let references = self
+ .header()
+ .references
+ .fetch_add(1, std::sync::atomic::Ordering::Relaxed);
+ assert!(
+ references < u32::MAX / 2,
+ "element declaration row reference count overflow"
+ );
+ Self(self.0)
+ }
+}
+
+impl Drop for ElementDeclarationRow {
+ fn drop(&mut self) {
+ if self
+ .header()
+ .references
+ .fetch_sub(1, std::sync::atomic::Ordering::Release)
+ != 1
+ {
+ return;
+ }
+ std::sync::atomic::fence(std::sync::atomic::Ordering::Acquire);
+ let count = self.count();
+ let (_, written, _) = self.arrays(count);
+ let custom_count = self.custom_count();
+ let (custom_written, _) = self.custom_arrays(custom_count);
+ // SAFETY: This was the last reference to the allocation and every value in it; nothing reads them after this.
+ unsafe {
+ std::ptr::drop_in_place(std::ptr::slice_from_raw_parts_mut(written.cast_mut(), count));
+ std::ptr::drop_in_place(std::ptr::slice_from_raw_parts_mut(
+ custom_written.cast_mut(),
+ custom_count,
+ ));
+ std::ptr::drop_in_place(self.0.as_ptr());
+ std::alloc::dealloc(self.0.as_ptr().cast(), row_layout(count, custom_count));
+ }
+ }
+}
+
+impl ElementDeclarationRow {
+ /// Replace the row's custom declarations with `custom`.
+ fn set_custom(&mut self, custom: Vec<CustomDeclarationWritten>) {
+ if custom.is_empty() && self.custom_count() == 0 {
+ return;
+ }
+ let all = self.all();
+ *self = Self::build(
+ (0..all.declared.len()).map(|index| (all.declared[index], all.written[index].clone(), all.checks[index])),
+ self.ends(),
+ custom,
+ );
+ }
+}
+
+/// Element-declaration rows addressed directly by dense element identity.
+///
+/// Each directory slot costs one pointer. A populated slot holds one allocation with the
+/// declarations of every kind.
+#[derive(Clone, Default)]
+pub(super) struct ElementDeclarationStore {
+ /// Each element's row, by element index, copied on write in chunks so that a fork shares them.
+ rows: CowVec<Option<ElementDeclarationRow>, ELEMENT_DECLARATION_ROWS_PER_CHUNK>,
+ /// How many rows hold custom declarations: none means no inline style declares one.
+ rows_with_custom_declarations: usize,
+ /// The rows put last, which a row declaring the same is shared with.
+ recent: RecentRows,
+}
+
+/// How many element slots a chunk of the store's rows holds.
+const ELEMENT_DECLARATION_ROWS_PER_CHUNK: usize = 128;
+
+const _: () = assert!(size_of::<Option<ElementDeclarationRow>>() == 8);
+
+/// How many rows the store keeps to share, each in the slot its content hashes to.
+const RECENT_ROWS: usize = 32;
+
+/// The rows an element's declarations were put in last, by the hash of what they declare: an
+/// element whose declarations are the same as one put recently holds that row, so elements
+/// declaring alike share one. A fork shares the slots, as it does the rows.
+#[derive(Clone, Default)]
+struct RecentRows([Option<ElementDeclarationRow>; RECENT_ROWS]);
+
+impl RecentRows {
+ /// The row declaring what `row` declares that was put recently, or `row`, kept to share.
+ fn share(&mut self, row: ElementDeclarationRow) -> ElementDeclarationRow {
+ let slot = &mut self.0[(row.content_hash() % RECENT_ROWS as u64) as usize];
+ if let Some(recent) = slot
+ && recent.declares_the_same_as(&row)
+ {
+ return recent.clone();
+ }
+ *slot = Some(row.clone());
+ row
+ }
+}
+
+impl ElementDeclarationStore {
+ /// The bytes of the store's rows and the declarations they hold, with the values those were
+ /// written with counted aside.
+ pub(super) fn heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {
+ use crate::heap_size::HeapSize;
+ let mut bytes = self.rows.heap_size(sizer, |_, _| 0);
+ for row in self.rows.iter().flatten() {
+ if !sizer.first_sight(row.0.as_ptr()) {
+ continue;
+ }
+ bytes += row.storage_bytes();
+ row.all().written.heap_size(sizer);
+ if let Some(custom) = row.custom() {
+ custom.written.heap_size(sizer);
+ }
+ }
+ bytes
+ }
+
+ fn row(&self, node: StyleNodeID) -> Option<&ElementDeclarationRow> {
+ let index = node.element_index()? as usize;
+ self.rows.get(index)?.as_ref()
+ }
+
+ /// Ask the processor to fetch a node's row, which reading the row's address alone does not.
+ fn prefetch_row(&self, node: StyleNodeID) {
+ if let Some(row) = self.row(node) {
+ prefetch(row.0.as_ptr());
+ }
+ }
+
+ /// Ask the processor to fetch the values a node's declarations were written with, reading the
+ /// row and its declarations.
+ fn prefetch_written_values(&self, node: StyleNodeID) {
+ let Some(row) = self.row(node) else {
+ return;
+ };
+ for written in row.all().written {
+ prefetch(written.pointer());
+ }
+ }
+
+ /// Ask the processor to fetch the declarations a node's row holds, reading the row.
+ fn prefetch_declarations(&self, node: StyleNodeID) {
+ let Some(row) = self.row(node) else {
+ return;
+ };
+ let all = row.all();
+ if !all.declared.is_empty() {
+ prefetch(all.written.as_ptr());
+ prefetch(all.checks.as_ptr());
+ }
+ }
+
+ /// The longhand properties one kind of the node's own declarations covers.
+ #[must_use]
+ pub(super) fn declared_properties(&self, node: StyleNodeID, kind: ElementDeclarationKind) -> &[DeclarationEntry] {
+ self.row(node).map_or(&[], |row| row.declarations(kind).declared)
+ }
+
+ /// One kind of the node's element declarations, with the values they were written with;
+ /// `None` when it has none of any kind.
+ #[must_use]
+ pub(super) fn declarations(
+ &self,
+ node: StyleNodeID,
+ kind: ElementDeclarationKind,
+ ) -> Option<ElementDeclarations<'_>> {
+ self.row(node).map(|row| row.declarations(kind))
+ }
+
+ /// Put `row` in the slot at `index`, or empty the slot where `row` holds nothing.
+ /// `had_custom` says whether the row it replaces held custom declarations.
+ fn put(&mut self, index: usize, row: Option<ElementDeclarationRow>, had_custom: bool) {
+ let row = row.filter(|row| !row.is_empty()).map(|row| self.recent.share(row));
+ let has_custom = row.as_ref().is_some_and(|row| row.custom().is_some());
+ if index >= self.rows.len() {
+ self.rows.resize_with_default(index + 1);
+ }
+ self.rows[index] = row;
+ self.rows_with_custom_declarations =
+ self.rows_with_custom_declarations + usize::from(has_custom) - usize::from(had_custom);
+ }
+
+ /// Record which longhand properties one of an element's own declarations covers, each with
+ /// the value it was written with.
+ pub(super) fn set(
+ &mut self,
+ node: StyleNodeID,
+ kind: ElementDeclarationKind,
+ declarations: Vec<(DeclarationEntry, RetainedStyleValueData)>,
+ ) {
+ let index = node.element_index().expect("only elements carry element declarations") as usize;
+ let declarations = declarations.into_iter().map(|(declared, written)| {
+ let checks = Checks::prepare(declared.property(), &written);
+ (declared, written, checks)
+ });
+ self.replace_kind(index, kind, declarations, None);
+ }
+
+ /// Replace the declarations of `kind` in the row at `index`, and its custom declarations where
+ /// `custom` names them.
+ fn replace_kind(
+ &mut self,
+ index: usize,
+ kind: ElementDeclarationKind,
+ declarations: impl ExactSizeIterator<Item = (DeclarationEntry, RetainedStyleValueData, Checks)>,
+ custom: Option<Vec<CustomDeclarationWritten>>,
+ ) {
+ let (row, had_custom) = match self.rows.get_mut(index).and_then(Option::as_mut) {
+ Some(row) => {
+ let had_custom = row.custom().is_some();
+ let custom = custom.unwrap_or_else(|| row.copy_custom());
+ (row.with(kind, declarations, custom), had_custom)
+ }
+ None => {
+ if declarations.len() == 0 && custom.as_ref().is_none_or(Vec::is_empty) {
+ return;
+ }
+ let mut ends = [0; ElementDeclarationKind::COUNT];
+ let count = u32::try_from(declarations.len()).expect("an element's declarations fit in u32");
+ for other in ElementDeclarationKind::ALL {
+ if other.index() >= kind.index() {
+ ends[other.index()] = count;
+ }
+ }
+ (
+ ElementDeclarationRow::build(declarations, ends, custom.unwrap_or_default()),
+ false,
+ )
+ }
+ };
+ self.put(index, Some(row), had_custom);
+ }
+
+ /// The custom properties the node's inline style declares, with the values they were written
+ /// with.
+ #[must_use]
+ pub(super) fn custom(&self, node: StyleNodeID) -> Option<ElementCustomDeclarations<'_>> {
+ self.row(node)?.custom()
+ }
+
+ /// The custom properties the node's inline style declares, in declaration order.
+ #[must_use]
+ pub(super) fn custom_declarations(&self, node: StyleNodeID) -> &[CustomDeclaration] {
+ self.custom(node).map_or(&[], ElementCustomDeclarations::declared)
+ }
+
+ /// Whether any inline style declares a custom property.
+ #[must_use]
+ pub(super) fn any_declares_custom_properties(&self) -> bool {
+ self.rows_with_custom_declarations != 0
+ }
+
+ /// Record the custom properties the node's inline style declares, each with the value it was
+ /// written with.
+ pub(super) fn set_custom(&mut self, node: StyleNodeID, custom: Vec<CustomDeclarationWritten>) {
+ let index = node.element_index().expect("only elements carry element declarations") as usize;
+ let Some(row) = self.rows.get_mut(index).and_then(Option::as_mut) else {
+ if !custom.is_empty() {
+ let ends = [0; ElementDeclarationKind::COUNT];
+ self.put(
+ index,
+ Some(ElementDeclarationRow::build(std::iter::empty(), ends, custom)),
+ false,
+ );
+ }
+ return;
+ };
+ let had_custom = row.custom().is_some();
+ let has_custom = !custom.is_empty();
+ row.set_custom(custom);
+ self.rows_with_custom_declarations =
+ self.rows_with_custom_declarations + usize::from(has_custom) - usize::from(had_custom);
+ if row.is_empty() {
+ self.rows[index] = None;
+ }
+ }
+
+ /// Drop the node's declarations, before its identity is handed to another element.
+ pub(super) fn forget(&mut self, node: StyleNodeID) {
+ let Some(index) = node.element_index().map(|index| index as usize) else {
+ return;
+ };
+ if let Some(row) = self.rows.get_mut(index).and_then(Option::take)
+ && row.custom().is_some()
+ {
+ self.rows_with_custom_declarations -= 1;
+ }
+ }
+
+ /// Take the node's inline declaration out of its row while a private demand computes the node
+ /// as though it had none. The demand puts it back before it returns.
+ pub(super) fn hide_inline_for_demand(&mut self, node: StyleNodeID) -> Option<HiddenInlineDeclarations> {
+ let index = node.element_index()? as usize;
+ let row = self.rows.get_mut(index)?.as_mut()?;
+ let kind = ElementDeclarationKind::InlineStyle;
+ let hidden = HiddenInlineDeclarations {
+ declarations: row.copy_of(kind),
+ custom: row.copy_custom(),
+ };
+ // NB: The row stays, even where it is empty, for the demand to put the declaration back in.
+ *row = row.with(kind, std::iter::empty(), Vec::new());
+ if !hidden.custom.is_empty() {
+ self.rows_with_custom_declarations -= 1;
+ }
+ Some(hidden)
+ }
+
+ pub(super) fn restore_inline_after_demand(&mut self, node: StyleNodeID, hidden: HiddenInlineDeclarations) {
+ let index = node.element_index().expect("only an element has an inline declaration") as usize;
+ assert!(
+ self.rows.get(index).is_some_and(Option::is_some),
+ "a private demand keeps the element's declaration row"
+ );
+ self.replace_kind(
+ index,
+ ElementDeclarationKind::InlineStyle,
+ hidden.declarations.into_iter(),
+ Some(hidden.custom),
+ );
+ }
+
+ /// Ask the processor to fetch the own declarations of the next elements a traversal styles,
+ /// each a cold pointer further from the dense column than the last: the values of the first,
+ /// the declarations of the second and the row of the third, each of which the call before
+ /// fetched what reading it reads.
+ pub(super) fn prefetch(&self, next: [Option<StyleNodeID>; 3]) {
+ if let Some(node) = next[0] {
+ self.prefetch_written_values(node);
+ }
+ if let Some(node) = next[1] {
+ self.prefetch_declarations(node);
+ }
+ if let Some(node) = next[2] {
+ self.prefetch_row(node);
+ }
+ }
+
+ /// Add the custom property names the declarations hold, returning how many rows and names
+ /// were visited.
+ pub(super) fn collect_atoms(&self, atoms: &mut HashSet<StyleAtomID>) -> u64 {
+ let mut visited = 0_u64;
+ for row in self.rows.iter().flatten() {
+ visited += 1;
+ for declaration in row.custom().into_iter().flat_map(ElementCustomDeclarations::declared) {
+ visited += 1;
+ atoms.insert(declaration.name);
+ }
+ }
+ visited
+ }
+}
+
+/// Ask the processor to fetch the cache line at `address` without waiting for it.
+#[inline]
+fn prefetch<T>(address: *const T) {
+ #[cfg(target_arch = "x86_64")]
+ // SAFETY: A prefetch reads nothing and cannot fault, whatever the address.
+ unsafe {
+ std::arch::x86_64::_mm_prefetch::<{ std::arch::x86_64::_MM_HINT_T0 }>(address.cast());
+ }
+ #[cfg(not(target_arch = "x86_64"))]
+ let _ = address;
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_fork_keeps_the_rows_it_had_when_the_store_writes() {
+ let mut store = ElementDeclarationStore::default();
+ let hints = ElementDeclarationKind::PresentationalHint;
+ let declared =
+ |property| DeclarationEntry::new(property, false, super::super::cascade::CascadeOperator::Declared);
+ let node = StyleNodeID::element(5);
+ store.set(node, hints, unwritten_declarations(&[declared(3)]));
+ let fork = store.clone();
+ store.set(node, hints, unwritten_declarations(&[declared(4)]));
+ assert_eq!(fork.declared_properties(node, hints), &[declared(3)][..]);
+ assert_eq!(store.declared_properties(node, hints), &[declared(4)][..]);
+ }
+
+ #[test]
+ fn elements_declaring_alike_share_one_row() {
+ let mut store = ElementDeclarationStore::default();
+ let hints = ElementDeclarationKind::PresentationalHint;
+ let declared =
+ |property| DeclarationEntry::new(property, false, super::super::cascade::CascadeOperator::Declared);
+ let (first, second, third) = (
+ StyleNodeID::element(1),
+ StyleNodeID::element(2),
+ StyleNodeID::element(3),
+ );
+ store.set(first, hints, unwritten_declarations(&[declared(3)]));
+ store.set(second, hints, unwritten_declarations(&[declared(3)]));
+ store.set(third, hints, unwritten_declarations(&[declared(5)]));
+ let row = |node| store.row(node).expect("the element declares").0;
+ assert_eq!(row(first), row(second));
+ assert_ne!(row(first), row(third));
+
+ // A write to one of them leaves the other's declarations as they were.
+ store.set(second, hints, unwritten_declarations(&[declared(4)]));
+ assert_eq!(store.declared_properties(first, hints), &[declared(3)][..]);
+ assert_eq!(store.declared_properties(second, hints), &[declared(4)][..]);
+ }
+
+ #[test]
+ fn a_row_holds_its_custom_declarations_before_the_others() {
+ use super::super::cascade::CascadeOperator;
+ let mut store = ElementDeclarationStore::default();
+ let inline = ElementDeclarationKind::InlineStyle;
+ let hints = ElementDeclarationKind::PresentationalHint;
+ let declared = |property| DeclarationEntry::new(property, false, CascadeOperator::Declared);
+ let custom = |name| CustomDeclaration::new(StyleAtomID(name), false, CascadeOperator::Declared);
+ let written = |declarations: &[CustomDeclaration]| -> Vec<CustomDeclarationWritten> {
+ declarations
+ .iter()
+ .map(|&declaration| {
+ (
+ declaration,
+ RetainedStyleValueData::from_owned(crate::css::style_value::StyleValueData::GuaranteedInvalid),
+ )
+ })
+ .collect()
+ };
+ let node = StyleNodeID::element(2);
+
+ store.set(node, hints, unwritten_declarations(&[declared(3)]));
+ store.set_custom(node, written(&[custom(7), custom(8)]));
+ store.set(node, inline, unwritten_declarations(&[declared(1), declared(2)]));
+ assert!(store.any_declares_custom_properties());
+ assert_eq!(store.custom_declarations(node), &[custom(7), custom(8)][..]);
+ assert_eq!(store.custom(node).map(|custom| custom.written_values().len()), Some(2));
+ assert_eq!(store.declared_properties(node, inline), &[declared(1), declared(2)][..]);
+ assert_eq!(store.declared_properties(node, hints), &[declared(3)][..]);
+ let row = store.row(node).expect("the element declares");
+ assert_eq!(row.storage_bytes(), 16 + 8 + 2 * 16 + 3 * 14);
+
+ // A private demand takes the inline declarations, custom ones too, out and puts them back.
+ let hidden = store.hide_inline_for_demand(node).expect("the element declares");
+ assert!(!store.any_declares_custom_properties());
+ assert!(store.custom_declarations(node).is_empty());
+ assert_eq!(store.declared_properties(node, hints), &[declared(3)][..]);
+ store.restore_inline_after_demand(node, hidden);
+ assert_eq!(store.custom_declarations(node), &[custom(7), custom(8)][..]);
+ assert_eq!(store.declared_properties(node, inline), &[declared(1), declared(2)][..]);
+
+ store.set_custom(node, Vec::new());
+ assert!(!store.any_declares_custom_properties());
+ assert!(store.custom(node).is_none());
+ assert_eq!(store.declared_properties(node, hints), &[declared(3)][..]);
+ }
+
+ #[test]
+ fn element_declarations_follow_dense_element_identity_slots() {
+ let mut store = ElementDeclarationStore::default();
+ let first = StyleNodeID::element(3);
+ let later = StyleNodeID::element(64);
+ let inline = ElementDeclarationKind::InlineStyle;
+ let hints = ElementDeclarationKind::PresentationalHint;
+ let svg = ElementDeclarationKind::SvgPresentationAttribute;
+ let declared = |property, important| {
+ DeclarationEntry::new(property, important, super::super::cascade::CascadeOperator::Declared)
+ };
+
+ store.set(
+ first,
+ inline,
+ unwritten_declarations(&[declared(1, false), declared(2, true)]),
+ );
+ store.set(first, hints, unwritten_declarations(&[declared(3, false)]));
+ store.set(later, svg, unwritten_declarations(&[declared(4, false)]));
+ store.set(later, inline, Vec::new());
+ assert_eq!(
+ store.declared_properties(first, inline),
+ &[declared(1, false), declared(2, true)][..]
+ );
+ assert_eq!(store.declared_properties(first, hints), &[declared(3, false)][..]);
+ assert_eq!(store.declared_properties(later, svg), &[declared(4, false)][..]);
+ assert!(store.declared_properties(later, inline).is_empty());
+ assert_eq!(store.rows.len(), 65);
+ store.set(first, inline, Vec::new());
+ assert!(store.declared_properties(first, inline).is_empty());
+ assert_eq!(store.declared_properties(first, hints), &[declared(3, false)][..]);
+
+ // Retirement has to clear a row before the dense identity is reused.
+ store.forget(first);
+ assert!(store.declared_properties(first, hints).is_empty());
+ assert_eq!(store.declared_properties(later, svg), &[declared(4, false)][..]);
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/element_host_facts.rs b/Libraries/LibWeb/Rust/src/css/style/element_host_facts.rs
new file mode 100644
index 00000000000..a04d548bb59
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/element_host_facts.rs
@@ -0,0 +1,99 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The facts the host publishes of each element, which style reads beside its records.
+//!
+//! The host states them with each element's arrival and whenever they change. They are not style:
+//! no record holds them, and an element keeps them while its record is replaced or dropped. Few
+//! elements differ in them (the box they ask for and what they are, as the adjustments and the
+//! layout rows read it), so each distinct set is held once, and each element's projection row
+//! holds a small identity of its set.
+
+use super::HashMap;
+use super::bridge::ElementBoxKind;
+
+/// The facts the host publishes of one element.
+#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]
+pub(in crate::css::style) struct HostFactSet {
+ /// The element facts the style computation's adjustments read; see
+ /// `bridge::element_adjustment_fact`.
+ pub(in crate::css::style) adjustment_facts: u32,
+ /// The element facts a layout row built for the element records; see
+ /// `bridge::element_construction_fact`.
+ pub(in crate::css::style) construction_facts: u32,
+ /// The principal box the element asks for, as its raw byte.
+ box_kind: u8,
+ /// One plus the kind of the element-backed pseudo-element of its shadow host the element stands for, or zero
+ /// where it stands for none.
+ pub(in crate::css::style) associated_pseudo_kind_plus_one: u8,
+}
+
+impl HostFactSet {
+ #[must_use]
+ pub(in crate::css::style) fn box_kind(&self) -> ElementBoxKind {
+ ElementBoxKind::from_raw(self.box_kind)
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn associated_pseudo_kind(&self) -> Option<u8> {
+ self.associated_pseudo_kind_plus_one.checked_sub(1)
+ }
+
+ pub(in crate::css::style) fn set_box_kind(&mut self, box_kind: ElementBoxKind) {
+ self.box_kind = box_kind as u8;
+ }
+}
+
+/// The identity of a distinct set of host facts. Identity zero is the empty set.
+#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
+pub(in crate::css::style) struct HostFactSetID(u16);
+
+/// The distinct sets of host facts of a document, which every element holding one shares.
+#[derive(Clone)]
+pub(in crate::css::style) struct HostFactSets {
+ sets: Vec<HostFactSet>,
+ ids: HashMap<HostFactSet, HostFactSetID>,
+}
+
+impl Default for HostFactSets {
+ fn default() -> Self {
+ let mut ids = HashMap::default();
+ ids.insert(HostFactSet::default(), HostFactSetID::default());
+ Self {
+ sets: vec![HostFactSet::default()],
+ ids,
+ }
+ }
+}
+
+impl HostFactSets {
+ #[must_use]
+ pub(in crate::css::style) fn get(&self, id: HostFactSetID) -> HostFactSet {
+ self.sets[usize::from(id.0)]
+ }
+
+ /// The identity of `set`, where it is among the sets held.
+ #[must_use]
+ pub(in crate::css::style) fn id_of(&self, set: &HostFactSet) -> Option<HostFactSetID> {
+ self.ids.get(set).copied()
+ }
+
+ /// The identity of `set`, among the sets held so far, or a new one.
+ pub(in crate::css::style) fn intern(&mut self, set: HostFactSet) -> HostFactSetID {
+ if let Some(&id) = self.ids.get(&set) {
+ return id;
+ }
+ // NB: A set is a combination of the bits of host enums, never of web content, so a document holds few.
+ let id = HostFactSetID(u16::try_from(self.sets.len()).expect("distinct element host fact sets fit in u16"));
+ self.sets.push(set);
+ self.ids.insert(set, id);
+ id
+ }
+
+ pub(in crate::css::style) fn heap_size(&self) -> usize {
+ crate::heap_size::vec_bytes(&self.sets) + crate::heap_size::map_bytes(&self.ids)
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/facts_types.rs b/Libraries/LibWeb/Rust/src/css/style/facts_types.rs
new file mode 100644
index 00000000000..1e866d98577
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/facts_types.rs
@@ -0,0 +1,275 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Atom identities, local feature keys and values, and dispatch keys shared by every reader of
+//! style node facts.
+
+use super::input_types::StateFact;
+
+define_id! {
+ /// Document-local identity of an interned selector-mentioned feature. Obeys the same generation
+ /// and non-reuse rules as [`super::tree::StyleNodeID`].
+ #[repr(transparent)]
+ default pub struct StyleAtomID(pub);
+}
+
+impl StyleAtomID {
+ /// Reserved: no atom. Document-local atoms start at 1.
+ pub const NONE: Self = Self(0);
+
+ #[must_use]
+ pub fn is_none(self) -> bool {
+ self == Self::NONE
+ }
+
+ /// The atoms a list of raw atom words holds, read in place.
+ #[must_use]
+ pub fn slice_of_raw(raw: &[u32]) -> &[Self] {
+ // SAFETY: `StyleAtomID` is a transparent `u32`, and every `u32` is a valid one.
+ unsafe { ak::slice_from_raw_parts(raw.as_ptr().cast(), raw.len()) }
+ }
+}
+
+/// Which local fact of a style node is being described.
+///
+/// Attribute presence and attribute value share one key: changing an attribute changes both facts
+/// at once, and splitting them would let a consumer handle one and miss the other.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub enum LocalFeatureKey {
+ /// The element's qualified name, as a single interned tag/namespace atom.
+ TagName,
+ /// The ASCII-lowercase folding of that name, recorded only when it differs from it. A type
+ /// selector dispatches on its own folded form, so an element whose local name is not already
+ /// lowercase has to be reachable under both.
+ FoldedTagName,
+ /// The element's ID.
+ Id,
+ /// Membership of one class.
+ Class(StyleAtomID),
+ /// Exposure of one shadow part.
+ Part(StyleAtomID),
+ /// Membership of one custom state, which `:state()` tests.
+ CustomState(StyleAtomID),
+ /// Whether the element has no children. A text node arriving changes it and connects no
+ /// element, so it cannot be carried by a tree delta.
+ Emptiness,
+ /// Presence and value of one attribute, named by its interned attribute-name atom.
+ Attribute(StyleAtomID),
+ /// The element's resolved language tag. `:lang()` compares extended language ranges, which a
+ /// single atom cannot express, so the fact is the whole tag and every `:lang()` rule hears any
+ /// change to it. What that costs is bounded by how rare `:lang()` is; what it buys is that the
+ /// region stays exactly the elements whose tag moved.
+ Language,
+ /// The element's resolved directionality, which `:dir()` tests.
+ Directionality,
+ /// The element's computed heading level, which `:heading()` tests.
+ HeadingLevel,
+ /// The outermost host from whose scope a `::part()` rule can address this element.
+ ///
+ /// A part name says nothing on its own about how far out it reaches: `exportparts` forwards it
+ /// through a host under a name that is often the same one, so the names an element carries can
+ /// stay exactly as they were while the scopes able to address it change. The value is compared
+ /// only against its own previous value, never against anything a selector names.
+ PartExposure,
+}
+
+/// The value of a local fact.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]
+pub enum FeatureValue {
+ /// The fact does not hold: no such class, no such attribute, no ID.
+ Absent,
+ /// The fact holds, but its payload is not internable, so an exact test reads the live DOM
+ /// after cheaper atom and name checks have already passed.
+ Present,
+ /// The fact holds and its payload is not the one it held before. Distinct from [`Self::Present`]
+ /// so that a value change is a change: a delta reporting presence on both sides cancels, which
+ /// is right for a fact nothing can distinguish and wrong for one that moved.
+ ChangedValue,
+ /// The fact holds with an interned value.
+ Atom(StyleAtomID),
+ /// The fact holds with a numeric value.
+ Number(u32),
+}
+
+impl FeatureValue {
+ #[must_use]
+ pub fn holds(self) -> bool {
+ !matches!(self, Self::Absent)
+ }
+}
+
+/// Element or document states, packed one bit per fact. One word covers every boolean
+/// pseudo-class the parser can produce.
+#[derive(Clone, Copy, Debug, Default, Hash, PartialEq, Eq)]
+pub struct StateSet(pub u64);
+
+impl StateSet {
+ /// The facts this set holds, for routing an element that announced them all at once.
+ pub fn facts(self) -> impl Iterator<Item = StateFact> {
+ let valid_bits = 1_u64
+ .checked_shl(u32::try_from(StateFact::ALL.len()).expect("state fact count exceeds u32"))
+ .map_or(u64::MAX, |limit| limit - 1);
+ let mut bits = self.0 & valid_bits;
+ std::iter::from_fn(move || {
+ if bits == 0 {
+ return None;
+ }
+ let index = bits.trailing_zeros() as usize;
+ bits &= bits - 1;
+ Some(StateFact::ALL[index])
+ })
+ }
+
+ #[must_use]
+ pub fn contains(self, fact: StateFact) -> bool {
+ self.0 & (1_u64 << fact as u32) != 0
+ }
+
+ pub fn insert(&mut self, fact: StateFact) {
+ self.0 |= 1_u64 << fact as u32;
+ }
+
+ pub fn remove(&mut self, fact: StateFact) {
+ self.0 &= !(1_u64 << fact as u32);
+ }
+}
+
+/// One attribute of one style node.
+///
+/// `value` is the interned value when the value was worth interning. Derived name forms and value
+/// text live once in the batch's shared atom catalog rather than once per element.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+#[repr(C)]
+pub struct AttributeFact {
+ pub name: StyleAtomID,
+ pub value: StyleAtomID,
+}
+
+const _: () = assert!(size_of::<AttributeFact>() == size_of::<[u32; 2]>());
+const _: () = assert!(align_of::<AttributeFact>() == align_of::<[u32; 2]>());
+
+impl AttributeFact {
+ /// The attributes a list of raw (name, value) atom words holds, read in place.
+ #[must_use]
+ pub fn slice_of_raw(raw: &[[u32; 2]]) -> &[Self] {
+ // SAFETY: `AttributeFact` is two `StyleAtomID`s, each a transparent `u32`, laid out as `[u32; 2]`, as the
+ // asserts above check, and any two `u32`s make a valid one.
+ unsafe { ak::slice_from_raw_parts(raw.as_ptr().cast(), raw.len()) }
+ }
+}
+
+/// The other names one attribute-name atom answers to.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct AttributeNameForms {
+ pub local: StyleAtomID,
+ pub folded_name: StyleAtomID,
+ pub folded_local: StyleAtomID,
+}
+
+/// One compact key for selector dispatch and relational arrival keys.
+///
+/// Every atom-bearing variant has the same `(kind: u8, atom: u32)` representation. Variants without
+/// an atom retain the distinctions needed by routing and dispatch without introducing another key
+/// vocabulary or a conversion between equal semantic features.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
+#[repr(u8)]
+pub enum FeatureKey {
+ Part(StyleAtomID),
+ CustomState(StyleAtomID),
+ TagName(StyleAtomID),
+ Id(StyleAtomID),
+ Class(StyleAtomID),
+ AttributeName(StyleAtomID),
+ Directionality(StyleAtomID),
+ Root,
+ State(StateFact),
+ Heading,
+ Universal,
+ Structural,
+ Language,
+}
+
+impl FeatureKey {
+ pub(crate) fn atom(self) -> Option<StyleAtomID> {
+ match self {
+ Self::Part(atom)
+ | Self::CustomState(atom)
+ | Self::TagName(atom)
+ | Self::Id(atom)
+ | Self::Class(atom)
+ | Self::AttributeName(atom)
+ | Self::Directionality(atom) => Some(atom),
+ Self::Root | Self::State(_) | Self::Heading | Self::Universal | Self::Structural | Self::Language => None,
+ }
+ }
+}
+
+/// The rightmost distinguishing feature of one selector entry.
+pub type DispatchKey = FeatureKey;
+
+/// One lossy bit for a dispatch key.
+///
+/// A Bloom summary is used only to reject a selector when a necessary key is definitely absent.
+/// Collisions admit extra exact evaluation and can never change a selector answer.
+#[must_use]
+pub fn dispatch_bloom_bit(key: DispatchKey) -> u64 {
+ 1_u64 << (dispatch_key_hash(key) & 63)
+}
+
+/// One well-mixed hash of a dispatch key, which both Bloom summaries take their bit positions from.
+#[must_use]
+fn dispatch_key_hash(key: DispatchKey) -> u64 {
+ let (kind, value) = match key {
+ DispatchKey::Part(atom) => (1_u64, u64::from(atom.0)),
+ DispatchKey::CustomState(atom) => (2, u64::from(atom.0)),
+ DispatchKey::Id(atom) => (3, u64::from(atom.0)),
+ DispatchKey::Class(atom) => (4, u64::from(atom.0)),
+ DispatchKey::AttributeName(atom) => (5, u64::from(atom.0)),
+ DispatchKey::TagName(atom) => (6, u64::from(atom.0)),
+ DispatchKey::Directionality(atom) => (7, u64::from(atom.0)),
+ DispatchKey::Root => (8, 0),
+ DispatchKey::State(fact) => (9, fact as u64),
+ DispatchKey::Heading => (10, 0),
+ DispatchKey::Universal => (11, 0),
+ _ => unreachable!("non-dispatch feature key"),
+ };
+ let mut hash = value ^ kind.wrapping_mul(0x9e37_79b9_7f4a_7c15);
+ hash = (hash ^ (hash >> 30)).wrapping_mul(0xbf58_476d_1ce4_e5b9);
+ hash = (hash ^ (hash >> 27)).wrapping_mul(0x94d0_49bb_1331_11eb);
+ hash ^ (hash >> 31)
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn states_pack_into_one_word() {
+ let mut states = StateSet::default();
+ states.insert(StateFact::Hover);
+ states.insert(StateFact::Checked);
+ assert!(states.contains(StateFact::Hover));
+ assert!(states.contains(StateFact::Checked));
+ assert!(!states.contains(StateFact::Focus));
+ assert_eq!(
+ states.facts().collect::<Vec<_>>(),
+ vec![StateFact::Checked, StateFact::Hover]
+ );
+ states.remove(StateFact::Hover);
+ assert!(!states.contains(StateFact::Hover));
+ assert_eq!(size_of::<StateSet>(), 8);
+ }
+
+ #[test]
+ fn attribute_facts_keep_only_their_name_and_value_atoms() {
+ assert_eq!(size_of::<AttributeFact>(), 8);
+ }
+
+ #[test]
+ fn selector_feature_keys_are_eight_bytes() {
+ assert_eq!(size_of::<FeatureKey>(), 8);
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/fnv.rs b/Libraries/LibWeb/Rust/src/css/style/fnv.rs
deleted file mode 100644
index fb40357a5ce..00000000000
--- a/Libraries/LibWeb/Rust/src/css/style/fnv.rs
+++ /dev/null
@@ -1,14 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-pub(super) fn fnv1a64<T: Into<u64>>(values: impl IntoIterator<Item = T>) -> u64 {
- let mut hash = 0xcbf2_9ce4_8422_2325;
- for value in values {
- hash ^= value.into();
- hash = hash.wrapping_mul(0x0000_0100_0000_01b3);
- }
- hash
-}
diff --git a/Libraries/LibWeb/Rust/src/css/style/host_atoms.rs b/Libraries/LibWeb/Rust/src/css/style/host_atoms.rs
index b05bcd07b27..d1097ac1201 100644
--- a/Libraries/LibWeb/Rust/src/css/style/host_atoms.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/host_atoms.rs
@@ -11,9 +11,11 @@
use super::atoms::{AtomLease, ReclaimedStyleAtom};
use super::engine_calls::{EngineWrite, with_engine};
use super::index::{AttributeNameForms, StyleAtomID};
+use crate::css::declaration_block::SharedDeclarationBlock;
use crate::css::ffi_support::{FfiUtf16View, ascii_lowercase};
-use crate::css::parser::arbitrary_substitution::attr_may_read_name;
+use crate::css::parser::arbitrary_substitution::AttrNamesRead;
use crate::css::retained_fly_string::RetainedUtf16FlyString;
+use crate::css::style_value::StyleValueData;
use crate::fast_hash::{FastMap, FastSet};
use crate::render_state::{ArenaChange, BegunRead, DocumentHost};
@@ -35,6 +37,22 @@ pub(crate) struct HostAtoms {
/// `value_text_requirements`.
names_with_unread_value_text: FastSet<StyleAtomID>,
value_text_requirements: u64,
+ /// The values the host withheld the text of, by the attribute name they were published under, each by its atom with
+ /// the raw identity of what it spells, which `names` holds a reference to while the atom lives: what the host hands
+ /// the engine for exactly the names something comes to read, without asking the document again.
+ withheld_value_texts: FastMap<StyleAtomID, FastMap<StyleAtomID, usize>>,
+ /// The attribute names something reads the value text of. What selectors and `attr()`s read only grows, so this
+ /// holds until the engine reclaims a name.
+ names_with_read_value_text: FastSet<StyleAtomID>,
+ /// The attribute names something reads. What selectors and `attr()`s read only grows, so this holds until the
+ /// engine reclaims a name.
+ names_read: FastSet<StyleAtomID>,
+ /// The attribute names the host knows nothing reads, as of the selectors its last job left, which the host forgets
+ /// when they move, and as of the `attr()` names read generation `names_unread_attr_generation`.
+ names_known_unread: FastSet<StyleAtomID>,
+ names_unread_attr_generation: u64,
+ /// What the `attr()`s of the declarations the host handed the engine can read.
+ attr_names_read: AttrNamesRead,
}
/// The other names an attribute name answers to, and the local name an `attr()` reads it by where it is in no namespace.
@@ -44,16 +62,37 @@ struct PublishedAttributeName {
}
impl HostAtoms {
+ /// The bytes the atoms' tables hold on the heap, but for the names, which the host's strings hold.
+ pub(crate) fn heap_size(&self) -> usize {
+ use crate::heap_size::{map_bytes, set_bytes};
+ map_bytes(&self.names)
+ + self.attr_names_read.heap_size()
+ + set_bytes(&self.languages_with_text)
+ + map_bytes(&self.attribute_names)
+ + map_bytes(&self.published_attribute_names)
+ + self
+ .published_attribute_names
+ .values()
+ .filter_map(|name| name.substitution_name.as_deref())
+ .map(size_of_val::<[u16]>)
+ .sum::<usize>()
+ + set_bytes(&self.names_with_unread_value_text)
+ + map_bytes(&self.withheld_value_texts)
+ + self.withheld_value_texts.values().map(map_bytes).sum::<usize>()
+ + set_bytes(&self.names_with_read_value_text)
+ + set_bytes(&self.names_read)
+ + set_bytes(&self.names_known_unread)
+ }
+
/// Forgets the atoms the engine reclaimed, whose numbers may name other names from now on.
pub(crate) fn forget(&mut self, reclaimed: &[ReclaimedStyleAtom]) {
if reclaimed.is_empty() {
return;
}
for reclaimed in reclaimed {
- // The engine names the raw identity of each name the host interned.
- if reclaimed.raw != 0 {
- let forgotten = self.names.remove(&reclaimed.raw);
- debug_assert_eq!(forgotten.map(|(atom, _)| atom), Some(reclaimed.atom));
+ // NB: The engine names the raw identity of every name it reclaimed, whether or not the host interned it.
+ if let Some((atom, _)) = self.names.remove(&reclaimed.raw) {
+ debug_assert_eq!(atom, reclaimed.atom);
}
}
let reclaimed: FastSet<StyleAtomID> = reclaimed.iter().map(|reclaimed| reclaimed.atom).collect();
@@ -65,6 +104,13 @@ impl HostAtoms {
.retain(|name, _| !reclaimed.contains(name));
self.names_with_unread_value_text
.retain(|name| !reclaimed.contains(name));
+ self.names_with_read_value_text.retain(|name| !reclaimed.contains(name));
+ self.withheld_value_texts.retain(|name, values| {
+ values.retain(|value, _| !reclaimed.contains(value));
+ !reclaimed.contains(name) && !values.is_empty()
+ });
+ self.names_read.retain(|name| !reclaimed.contains(name));
+ self.names_known_unread.retain(|name| !reclaimed.contains(name));
self.generation += 1;
}
}
@@ -82,7 +128,7 @@ pub(crate) unsafe fn intern(host: &DocumentHost, raw: usize) -> StyleAtomID {
// SAFETY: Guaranteed by the caller.
let (lease, name) = unsafe {
(
- AtomLease::acquire_raw(raw),
+ AtomLease::acquire_raw(host.style_atoms(), raw),
RetainedUtf16FlyString::from_borrowed_raw(raw),
)
};
@@ -93,7 +139,7 @@ pub(crate) unsafe fn intern(host: &DocumentHost, raw: usize) -> StyleAtomID {
/// The atom of `name` qualified by `namespace`, which the engine adopts as it does a name's.
fn intern_qualified(host: &DocumentHost, namespace: StyleAtomID, name: StyleAtomID) -> StyleAtomID {
- adopt(host, AtomLease::acquire_qualified(namespace, name))
+ adopt(host, AtomLease::acquire_qualified(host.style_atoms(), namespace, name))
}
/// Queues the engine's adoption of the atom `lease` holds, and answers the atom.
@@ -133,17 +179,15 @@ pub extern "C" fn style_engine_set_element_language(host: &DocumentHost, node: u
.borrow_mut()
.languages_with_text
.insert(StyleAtomID(language));
- let text: Box<[u16]> = if tag_is_new {
- text.to_utf16().unwrap_or_default().into()
- } else {
- Box::default()
- };
- if node != 0 || !text.is_empty() {
- host.queue_change(ArenaChange::Engine(EngineWrite::ElementLanguage {
- node,
- language,
- text,
- }));
+ let mut projection = host.engine_memo().projection.borrow_mut();
+ let mut writes = projection.writes();
+ if tag_is_new {
+ // A range is not a name, so `:lang()` compares against the tag itself. It is recorded once per language
+ // rather than once per element.
+ writes.set_language_text(StyleAtomID(language), &text.to_utf16().unwrap_or_default());
+ }
+ if let Some(node) = super::tree::StyleNodeID::from_raw(node) {
+ writes.set_element_language(node, StyleAtomID(language));
}
}
@@ -214,11 +258,13 @@ pub unsafe extern "C" fn document_host_intern_attribute_name(
}
// An attr() reads an attribute in no namespace by its local name.
let substitution_name = namespace.is_none().then_some(local_name);
- host.queue_change(ArenaChange::Engine(EngineWrite::AttributeNameForms {
- name,
- forms,
- substitution_name: substitution_name.clone(),
- }));
+ {
+ let mut projection = host.engine_memo().projection.borrow_mut();
+ projection.note_attribute_name_forms(name, forms);
+ if let Some(local_name) = &substitution_name {
+ projection.note_attribute_substitution_name(name, local_name);
+ }
+ }
let mut atoms = host.engine_memo().atoms.borrow_mut();
atoms.published_attribute_names.insert(
name,
@@ -243,35 +289,39 @@ pub unsafe extern "C" fn document_host_intern_attribute_value(host: &DocumentHos
// SAFETY: Guaranteed by the caller.
let atom = unsafe { intern(host, value) };
let name = StyleAtomID(name);
- if !value_text_is_known_unread(host, name) {
+ if value_text_is_known_unread(host, name) {
+ // NB: The atom's entry in `names` holds what it spells for as long as the atom lives.
+ host.engine_memo()
+ .atoms
+ .borrow_mut()
+ .withheld_value_texts
+ .entry(name)
+ .or_default()
+ .insert(atom, value);
+ } else {
// SAFETY: Guaranteed by the caller.
let text = unsafe { RetainedUtf16FlyString::from_borrowed_raw(value) };
- host.queue_change(ArenaChange::Engine(EngineWrite::AttributeValueText {
- name,
- value: atom,
- text,
- }));
+ host.engine_memo()
+ .projection
+ .borrow_mut()
+ .set_attribute_value_text(atom, text);
}
atom.0
}
-/// Whether the host knows that nothing reads what the values of the attribute name `name` spell, which spares it the
-/// value's text.
-#[unsafe(no_mangle)]
-pub extern "C" fn document_host_attribute_value_text_is_known_unread(host: &DocumentHost, name: u32) -> bool {
- value_text_is_known_unread(host, StyleAtomID(name))
-}
-
/// Whether the host knows that nothing reads what the values of the attribute name `name` spell: no selector of the
/// engine, by `name` or the other forms the host published with it, and no `attr()`, by its local name if it has one.
-/// The host knows what the selectors read where it queued no rule since its last job; what `attr()`s read is the
-/// process's. Where it does not know, the host hands the engine each value's text, which the engine keeps only where
+/// The host knows what the selectors read where it queued no rule since its last job, and what `attr()`s read always,
+/// as it hands the engine every declaration. Where it does not know, the host hands the engine each value's text, which the engine keeps only where
/// something reads it.
fn value_text_is_known_unread(host: &DocumentHost, name: StyleAtomID) -> bool {
let atoms = host.engine_memo().atoms.borrow();
if atoms.names_with_unread_value_text.contains(&name) {
return true;
}
+ if atoms.names_with_read_value_text.contains(&name) {
+ return false;
+ }
// The host interned every name it asks about, with its forms. Where it knows none, it hands the text over.
let Some(PublishedAttributeName {
forms,
@@ -280,55 +330,240 @@ fn value_text_is_known_unread(host: &DocumentHost, name: StyleAtomID) -> bool {
else {
return false;
};
- let unread = !substitution_name.as_deref().is_some_and(attr_may_read_name)
- && host.known_selectors_read_value_text_of(&[name, forms.local, forms.folded_name, forms.folded_local])
- == Some(false);
+ let read_by_attr = substitution_name
+ .as_deref()
+ .is_some_and(|name| atoms.attr_names_read.may_read(name));
+ let read_by_selectors =
+ host.known_selectors_read_value_text_of(&[name, forms.local, forms.folded_name, forms.folded_local]);
drop(atoms);
+ let mut atoms = host.engine_memo().atoms.borrow_mut();
+ if read_by_attr || read_by_selectors == Some(true) {
+ atoms.names_with_read_value_text.insert(name);
+ return false;
+ }
+ let unread = read_by_selectors == Some(false);
if unread {
- host.engine_memo()
- .atoms
- .borrow_mut()
- .names_with_unread_value_text
- .insert(name);
+ atoms.names_with_unread_value_text.insert(name);
}
unread
}
+/// Brings what the host knows of the engine's selectors up to date with the writes it queued, where a rule it queued
+/// since its last job left it not knowing: the host asks the engine, which applies them first.
+#[unsafe(no_mangle)]
+pub extern "C" fn document_host_learn_selector_requirements(host: &DocumentHost, read: &BegunRead) {
+ if host.known_selectors_test_local_link().is_none() {
+ host.ask(read, |_| ());
+ }
+}
+
+/// Whether the host knows that no selector of the engine tests `:local-link`, which spares it resolving the URL of each
+/// link that arrives.
+#[unsafe(no_mangle)]
+pub extern "C" fn document_host_local_link_is_known_untested(host: &DocumentHost) -> bool {
+ host.known_selectors_test_local_link() == Some(false)
+}
+
/// Whether the host knows that nothing of the engine reads the attribute name `name`: no selector tests it, by `name` or
/// the other forms the host published with it, and no `attr()` reads it, by its local name if it has one. Where it does
/// not know, the host hands the engine each change to the attribute.
#[unsafe(no_mangle)]
pub extern "C" fn document_host_attribute_is_known_unread(host: &DocumentHost, name: u32) -> bool {
- let atoms = host.engine_memo().atoms.borrow();
+ let name = StyleAtomID(name);
+ // The host knows nothing of the selectors where it queued a rule since its last job.
+ if host
+ .known_selector_attribute_value_text_requirements_version()
+ .is_none()
+ {
+ return false;
+ }
+ let mut atoms = host.engine_memo().atoms.borrow_mut();
+ let attr_generation = atoms.attr_names_read.generation();
+ if atoms.names_read.contains(&name) {
+ return false;
+ }
+ if atoms.names_unread_attr_generation != attr_generation {
+ atoms.names_unread_attr_generation = attr_generation;
+ atoms.names_known_unread.clear();
+ } else if atoms.names_known_unread.contains(&name) {
+ return true;
+ }
let Some(PublishedAttributeName {
forms,
substitution_name,
- }) = atoms.published_attribute_names.get(&StyleAtomID(name))
+ }) = atoms.published_attribute_names.get(&name)
else {
return false;
};
- !substitution_name.as_deref().is_some_and(attr_may_read_name)
- && host.known_selectors_test_attribute(&[StyleAtomID(name), forms.local, forms.folded_name, forms.folded_local])
- == Some(false)
+ let read = substitution_name
+ .as_deref()
+ .is_some_and(|name| atoms.attr_names_read.may_read(name))
+ || host.known_selectors_test_attribute(&[name, forms.local, forms.folded_name, forms.folded_local])
+ != Some(false);
+ if read {
+ atoms.names_read.insert(name);
+ } else {
+ atoms.names_known_unread.insert(name);
+ }
+ !read
}
-/// Whether the engine's requirements of attribute value text moved since the host last asked, which makes the host ask
-/// again about the names it knew nothing read.
-#[unsafe(no_mangle)]
-pub extern "C" fn document_host_refresh_attribute_value_text_requirements(
+/// Notes what the `attr()`s of the declarations `change` hands the engine can read. Every write of the host goes through
+/// here on its way into the queue, and the matches name each write, so that a new write holding declarations has to say
+/// so: an `attr()` nothing noted reads an attribute the host never handed over, as if it were absent.
+pub(crate) fn note_attr_names_read_by_change(host: &DocumentHost, change: &ArenaChange) {
+ use super::engine_calls::EngineWrite as Engine;
+ use super::rule_writes::RuleWrite as Rule;
+ match change {
+ ArenaChange::Rule(write) => match write {
+ Rule::PublishRules { rules, .. } => {
+ for declarations in rules.iter().filter_map(|rule| rule.declarations.as_ref()) {
+ note_attr_names_read_by_block(host, declarations);
+ }
+ }
+ Rule::RuleDeclarations {
+ declarations: Some(declarations),
+ ..
+ } => note_attr_names_read_by_block(host, declarations),
+ Rule::RuleDeclarations { declarations: None, .. }
+ | Rule::AddSheet { .. }
+ | Rule::AddUserAgentSheet { .. }
+ | Rule::BeginSheetRulesReplacement(_)
+ | Rule::ReplaceSelectors { .. }
+ | Rule::RemoveRules(_)
+ | Rule::RuleConditions(_)
+ | Rule::LayerOrder { .. } => {}
+ },
+ ArenaChange::Engine(write) => match write {
+ Engine::InlineStyle { data: Some(data), .. } => note_attr_names_read_by_block(host, data),
+ Engine::PresentationalHints { properties, .. } => {
+ note_attr_names_read_by(host, properties.iter().map(|property| &*property.value));
+ }
+ Engine::AnimationEffectDescriptions { effects, .. } => {
+ for effect in effects {
+ note_attr_names_read_by(host, effect.declared_values());
+ }
+ }
+ Engine::PositionTryRules { row, .. } => {
+ for rule in row.values() {
+ note_attr_names_read_by_block(host, rule.declarations());
+ }
+ }
+ Engine::InlineStyle { data: None, .. }
+ | Engine::PublishFontFaces { .. }
+ | Engine::ElementCustomPropertyData { .. }
+ | Engine::PseudoElementCustomPropertyData { .. }
+ | Engine::MintStyleNodes(_)
+ | Engine::ElementUniqueNodeIds(_)
+ | Engine::TextArrivals(_)
+ | Engine::EndStyleUpdate { .. }
+ | Engine::Publish(_)
+ | Engine::MoveHover(_)
+ | Engine::ShadowRoot { .. }
+ | Engine::SlotAssignedNodes
+ | Engine::TopLayerMove { .. }
+ | Engine::BoxKindChange { .. }
+ | Engine::RetireTexts(_)
+ | Engine::TreeScopeRoot { .. }
+ | Engine::TextData { .. }
+ | Engine::AdoptAtom(_)
+ | Engine::ParkRandomBaseValues { .. }
+ | Engine::UnparkRandomBaseValues { .. }
+ | Engine::NoteCustomPropertyEnvironment { .. }
+ | Engine::AnimationKeyframes { .. }
+ | Engine::AnimationEffectTimings { .. } => {}
+ },
+ _ => {}
+ }
+}
+
+/// Moves with every name an `attr()` the host handed the engine can newly read.
+pub(crate) fn attr_names_read_generation(host: &DocumentHost) -> u64 {
+ host.engine_memo().atoms.borrow().attr_names_read.generation()
+}
+
+/// Notes what the `attr()`s of `values`, which the host is handing the engine, can read.
+pub(crate) fn note_attr_names_read_by<'v>(host: &DocumentHost, values: impl Iterator<Item = &'v StyleValueData>) {
+ for value in values {
+ if let Some(unresolved) = super::custom_property_cascade::unresolved_reading_attributes(value) {
+ host.engine_memo()
+ .atoms
+ .borrow_mut()
+ .attr_names_read
+ .note(unresolved.components().as_ref());
+ }
+ }
+}
+
+/// Notes what the `attr()`s of the declarations of `block`, which the host is handing the engine, can read.
+pub(crate) fn note_attr_names_read_by_block(host: &DocumentHost, block: &SharedDeclarationBlock) {
+ note_attr_names_read_by(
+ host,
+ block
+ .properties()
+ .values()
+ .iter()
+ .chain(block.custom_properties().values())
+ .map(|value| &**value),
+ );
+}
+
+/// Notes what the `attr()`s of `values`, tokens the host is handing the engine, can read.
+pub(crate) fn note_attr_names_read_by_tokens(
host: &DocumentHost,
- read: &BegunRead,
-) -> bool {
+ values: &[crate::css::parser::component_value::ComponentValue],
+) {
+ host.engine_memo().atoms.borrow_mut().attr_names_read.note(values);
+}
+
+/// Forgets which attribute names the host knew nothing reads, once the engine's selectors test other names.
+pub(crate) fn forget_attribute_names_known_unread(host: &DocumentHost) {
+ host.engine_memo().atoms.borrow_mut().names_known_unread.clear();
+}
+
+/// Brings what the host knows of the engine's requirements of attribute value text up to date, and hands the engine
+/// the text of every value the host withheld under a name something reads now: only those values, rather than every attribute
+/// of the document again.
+#[unsafe(no_mangle)]
+pub extern "C" fn document_host_refresh_attribute_value_text_requirements(host: &DocumentHost, read: &BegunRead) {
// The host knows where the requirements are where it queued no rule since its last job.
- let requirements = match host.known_selector_attribute_value_text_requirements_version() {
- Some(version) => super::inputs::with_attr_names_read(version),
- None => with_engine(read, host, |engine| engine.attribute_value_text_requirements_version()),
+ let selector_requirements = match host.known_selector_attribute_value_text_requirements_version() {
+ Some(version) => version,
+ None => with_engine(read, host, |engine| {
+ engine.selector_attribute_value_text_requirements_version()
+ }),
};
- let mut atoms = host.engine_memo().atoms.borrow_mut();
- if requirements == atoms.value_text_requirements {
- return false;
+ let withheld_names: Vec<StyleAtomID> = {
+ let mut atoms = host.engine_memo().atoms.borrow_mut();
+ let requirements = selector_requirements.wrapping_add(atoms.attr_names_read.generation());
+ if requirements == atoms.value_text_requirements {
+ return;
+ }
+ atoms.value_text_requirements = requirements;
+ atoms.names_with_unread_value_text.clear();
+ atoms.withheld_value_texts.keys().copied().collect()
+ };
+ for name in withheld_names {
+ if value_text_is_known_unread(host, name) {
+ continue;
+ }
+ let texts: Vec<(StyleAtomID, RetainedUtf16FlyString)> = {
+ let mut atoms = host.engine_memo().atoms.borrow_mut();
+ let Some(values) = atoms.withheld_value_texts.remove(&name) else {
+ continue;
+ };
+ values
+ .into_iter()
+ .filter_map(|(value, raw)| {
+ let (atom, text) = atoms.names.get(&raw)?;
+ debug_assert_eq!(*atom, value, "a withheld value's atom lives as long as its name entry");
+ Some((value, text.clone()))
+ })
+ .collect()
+ };
+ let mut projection = host.engine_memo().projection.borrow_mut();
+ for (value, text) in texts {
+ projection.set_attribute_value_text(value, text);
+ }
}
- atoms.value_text_requirements = requirements;
- atoms.names_with_unread_value_text.clear();
- true
}
diff --git a/Libraries/LibWeb/Rust/src/css/style/identities.rs b/Libraries/LibWeb/Rust/src/css/style/identities.rs
index 1a9dc8306ee..b6108a9af4e 100644
--- a/Libraries/LibWeb/Rust/src/css/style/identities.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/identities.rs
@@ -13,7 +13,6 @@
//! reused in is the one the engine kept when it owned the space.
use super::tree::StyleNodeID;
-use crate::css::ffi_support::OwnedBox;
/// The identities of one document's style nodes, in two spaces: elements (with shadow roots and the document), and
/// text nodes.
@@ -68,6 +67,13 @@ impl StyleNodeIdAllocator {
StyleNodeID::text(self.texts.mint())
}
+ /// Mints an identity into each slot of `out`: text identities where `text`, otherwise element ones.
+ pub fn mint(&mut self, text: bool, out: &mut [u32]) {
+ for slot in out {
+ *slot = if text { self.mint_text() } else { self.mint_element() }.raw();
+ }
+ }
+
/// Takes back the identities a transaction's finish released, in the order it released them.
pub fn release(&mut self, released: &[u32]) {
for node in released.iter().filter_map(|&raw| StyleNodeID::from_raw(raw)) {
@@ -79,34 +85,6 @@ impl StyleNodeIdAllocator {
}
}
-/// Creates the identity space of a new document.
-#[unsafe(no_mangle)]
-pub extern "C" fn style_node_id_allocator_create() -> *mut StyleNodeIdAllocator {
- Box::into_raw(Box::default())
-}
-
-#[unsafe(no_mangle)]
-pub extern "C" fn style_node_id_allocator_destroy(allocator: OwnedBox<StyleNodeIdAllocator>) {
- drop(allocator);
-}
-
-/// Mints an identity into each slot of `out`: text identities where `text`, otherwise element ones.
-#[unsafe(no_mangle)]
-pub extern "C" fn style_node_id_allocator_mint(
- allocator: &mut StyleNodeIdAllocator,
- text: bool,
- out: ak::SpanMut<'_, u32>,
-) {
- for slot in out.into_slice() {
- *slot = if text {
- allocator.mint_text()
- } else {
- allocator.mint_element()
- }
- .raw();
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
diff --git a/Libraries/LibWeb/Rust/src/css/style/input_routing.rs b/Libraries/LibWeb/Rust/src/css/style/input_routing.rs
deleted file mode 100644
index 6e9702c462e..00000000000
--- a/Libraries/LibWeb/Rust/src/css/style/input_routing.rs
+++ /dev/null
@@ -1,93 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-//! Mapping normalized inputs to selector routing keys.
-//!
-//! The routing registry indexes immutable transpose routes by the semantic facts they read. A
-//! normalized transaction input publishes the corresponding keys so planning can ask whether an
-//! attached selector observes that input.
-
-use smallvec::SmallVec;
-
-use super::index::FeatureValue;
-use super::index::LocalFeatureKey;
-use super::selector::RoutingKey;
-use super::transaction::InputKey;
-use super::transaction::InputValue;
-use super::transaction::NormalizedInput;
-
-/// The routing keys one normalized input publishes.
-#[must_use]
-pub(super) fn routing_keys_for_input(input: &NormalizedInput) -> SmallVec<[RoutingKey; 4]> {
- let mut keys = SmallVec::new();
- for_each_routing_key(input, |key| keys.push(key));
- keys
-}
-
-fn for_each_routing_key(input: &NormalizedInput, mut publish: impl FnMut(RoutingKey)) {
- match input.key {
- InputKey::LocalFeature(_, feature) => for_each_feature_routing_key(feature, input.old, input.new, publish),
- InputKey::State(_, fact) => publish(RoutingKey::State(fact)),
- _ => {}
- }
-}
-
-/// The routing keys one local-feature change publishes.
-///
-/// A tag or ID change publishes both its old and new atom, because a selector mentioning either can
-/// change truth. A class or attribute key already names its atom. Attribute routes share the name
-/// lookup, then classify presence and value truth from the selector node without another directory
-/// probe.
-fn for_each_feature_routing_key(
- feature: LocalFeatureKey,
- old: InputValue,
- new: InputValue,
- mut publish: impl FnMut(RoutingKey),
-) {
- let atom_of = |value: InputValue| match value {
- InputValue::Feature(FeatureValue::Atom(atom)) => Some(atom),
- _ => None,
- };
- match feature {
- LocalFeatureKey::TagName | LocalFeatureKey::FoldedTagName => {
- if let Some(atom) = atom_of(old) {
- publish(RoutingKey::TagName(atom));
- }
- if let Some(atom) = atom_of(new) {
- publish(RoutingKey::TagName(atom));
- }
- }
- LocalFeatureKey::Id => {
- if let Some(atom) = atom_of(old) {
- publish(RoutingKey::Id(atom));
- }
- if let Some(atom) = atom_of(new) {
- publish(RoutingKey::Id(atom));
- }
- }
- LocalFeatureKey::Class(class) => publish(RoutingKey::Class(class)),
- LocalFeatureKey::Part(part) => publish(RoutingKey::Part(part)),
- LocalFeatureKey::CustomState(state) => publish(RoutingKey::CustomState(state)),
- // Routed to the element directly rather than through a transpose route.
- LocalFeatureKey::PartExposure => {}
- // Every `:lang()` entry registers under one key, because a range is not an atom.
- LocalFeatureKey::Language => publish(RoutingKey::Language),
- LocalFeatureKey::Directionality => {
- if let Some(atom) = atom_of(old) {
- publish(RoutingKey::Directionality(atom));
- }
- if let Some(atom) = atom_of(new) {
- publish(RoutingKey::Directionality(atom));
- }
- }
- LocalFeatureKey::HeadingLevel => publish(RoutingKey::Structural),
- LocalFeatureKey::Emptiness => publish(RoutingKey::Structural),
- // The facts an arrival folded onto one key are read back off the element by the engine,
- // which has the fact store this function does not.
- LocalFeatureKey::ArrivingFacts => {}
- LocalFeatureKey::Attribute(name) => publish(RoutingKey::AttributeName(name)),
- }
-}
diff --git a/Libraries/LibWeb/Rust/src/css/style/input_types.rs b/Libraries/LibWeb/Rust/src/css/style/input_types.rs
new file mode 100644
index 00000000000..58c1cbc2f21
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/input_types.rs
@@ -0,0 +1,358 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Typed semantic inputs, and the element inputs a transaction takes beside the projection's
+//! changes. Typing matters: treating every change as a generic version bump would move work from
+//! mutation time into an unnecessarily broad lazy validation later, which is exactly the
+//! amplification this engine exists to avoid.
+
+use std::collections::BTreeMap;
+use std::collections::BTreeSet;
+
+#[cfg(test)]
+use super::index::FeatureValue;
+use super::index::LocalFeatureKey;
+use super::index::StyleAtomID;
+use super::instrumentation::Counter;
+use super::pipeline::rule_store::DeclarationBlockID;
+use super::tree::StyleNodeID;
+use super::tree::TreeScopeID;
+
+/// Monotonic identity of one normalized style update published by a document.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
+pub struct StyleUpdateVersion(pub u64);
+
+// -- Typed semantic inputs -------------------------------------------------------------------
+
+// An element or document state fact.
+//
+// States are semantic facts rather than bespoke invalidation entry points, so a transition
+// publishes an old and a new value and only operators depending on that state receive it.
+//
+// Every boolean pseudo-class the parser can produce has an entry here. That exhaustiveness is the
+// point: a pseudo-class with no fact would compile to something the engine cannot route, and a
+// selector that cannot be routed cannot be invalidated. Facts whose value is a parameter rather
+// than a boolean - `:dir()`, `:lang()`, `:state()`, `:heading()` - are operators instead, because
+// a bitset cannot carry their argument.
+include!(concat!(env!("OUT_DIR"), "/style_state_fact_generated.rs"));
+
+impl StateFact {
+ /// Whether the elements in this state are enumerated by a feature posting.
+ ///
+ /// A state a user interaction puts an element in holds on a handful of elements at a time: the
+ /// focused element and the ancestors focus is within, the hovered chain, the activated chain,
+ /// the top layer. A subject compound carrying nothing but such a state names its subjects as
+ /// well as an ID does, so a change elsewhere in the selector reaches those subjects rather than
+ /// every element its combinators could lead to. A state an element's nature decides, such as
+ /// being a link or enabled, holds on most of a document and is left to the compound's names.
+ #[must_use]
+ pub fn has_selector_posting(self) -> bool {
+ matches!(
+ self,
+ Self::Active
+ | Self::Focus
+ | Self::FocusVisible
+ | Self::FocusWithin
+ | Self::Fullscreen
+ | Self::Hover
+ | Self::Modal
+ | Self::PictureInPicture
+ | Self::PopoverOpen
+ | Self::Target
+ )
+ }
+}
+
+/// Declarations sourced from one style node rather than a stylesheet rule. Each kind keeps its
+/// language-defined cascade placement: presentational hints do not masquerade as inline style, and
+/// none of them enter the rule index merely because their source syntax is an attribute.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
+#[repr(u8)]
+pub enum ElementDeclarationKind {
+ /// The `style` attribute.
+ InlineStyle,
+ /// An HTML presentational-hint attribute.
+ PresentationalHint,
+ /// An SVG presentation attribute such as `fill` or `stroke`.
+ SvgPresentationAttribute,
+}
+
+impl ElementDeclarationKind {
+ pub const COUNT: usize = Self::SvgPresentationAttribute as usize + 1;
+ pub const ALL: [Self; Self::COUNT] = [
+ Self::InlineStyle,
+ Self::PresentationalHint,
+ Self::SvgPresentationAttribute,
+ ];
+
+ #[must_use]
+ pub const fn index(self) -> usize {
+ self as usize
+ }
+}
+
+/// The tree relations of one style node, as of one side of a mutation.
+///
+/// This is the minimum old-side information the applicable transpose rules need. It is not a
+/// traversable old DOM and does not copy unchanged descendant fields: old-side facts exist to
+/// establish a complete impact region, not to reconstruct history.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub struct TreeRelations {
+ pub parent: Option<StyleNodeID>,
+ pub previous_element_sibling: Option<StyleNodeID>,
+ pub next_element_sibling: Option<StyleNodeID>,
+ pub tree_scope: TreeScopeID,
+ pub assigned_slot: Option<StyleNodeID>,
+}
+
+impl TreeRelations {
+ /// Relations of a node with no parent, slot, or host: the shape a node has before insertion and
+ /// after removal.
+ #[must_use]
+ #[cfg(test)]
+ pub fn detached(tree_scope: TreeScopeID) -> Self {
+ Self {
+ parent: None,
+ previous_element_sibling: None,
+ next_element_sibling: None,
+ tree_scope,
+ assigned_slot: None,
+ }
+ }
+}
+
+/// An input the host publishes: a style-node identity plus the typed fact or relation it describes.
+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
+pub enum InputKey {
+ TreeRelations(StyleNodeID),
+ LocalFeature(StyleNodeID, LocalFeatureKey),
+ State(StyleNodeID, StateFact),
+ ElementDeclaration(StyleNodeID, ElementDeclarationKind),
+ /// A non-selector style input owned by the element changed. This is an edge-triggered action,
+ /// not retained fact state; its value says only which reaction is pending. A test records one directly.
+ #[cfg(test)]
+ ElementStyleInput(StyleNodeID),
+ /// A registration made through `CSS.registerProperty()`, which has no stylesheet rule identity.
+ CustomPropertyRegistration(StyleAtomID),
+}
+
+pub const STYLE_REACTION_PUBLISHED_STYLE: u8 = 1 << 0;
+pub const STYLE_REACTION_RECOMPUTE_STYLE: u8 = 1 << 1;
+pub const STYLE_REACTION_RECOMPUTE_DESCENDANT_STYLES: u8 = 1 << 4;
+pub const STYLE_REACTION_PSEUDO_INPUTS_MAY_HAVE_CHANGED: u8 = 1 << 6;
+/// The element's font environment moved: a face its font cascade names became available, failed
+/// or changed. The `@font-face` table that decides the cascade is published to the engine and
+/// versioned by the font-environment generation. The element computes again from the rules it
+/// matched, which no font decides: alone, this asks for no rematch, unlike `STYLE_REACTION_RECOMPUTE_STYLE`.
+pub const STYLE_REACTION_FONT_INPUTS_CHANGED: u8 = 1 << 7;
+
+impl InputKey {
+ /// What the engine counts an input of this key as.
+ #[must_use]
+ #[cfg_attr(
+ not(test),
+ expect(
+ clippy::unnecessary_wraps,
+ reason = "only a test records an element style input, which counts nothing"
+ )
+ )]
+ pub fn counter(self) -> Option<Counter> {
+ match self {
+ Self::TreeRelations(..) => Some(Counter::TreeDeltas),
+ Self::LocalFeature(..) => Some(Counter::LocalFeatureDeltas),
+ Self::State(..) => Some(Counter::StateDeltas),
+ Self::ElementDeclaration(..) => Some(Counter::ElementDeclarationDeltas),
+ #[cfg(test)]
+ Self::ElementStyleInput(..) => None,
+ Self::CustomPropertyRegistration(..) => Some(Counter::ProgramDeltas),
+ }
+ }
+}
+
+/// The value of an input on one side of a mutation.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub enum InputValue {
+ /// A local fact, which the host writes into the projection rather than records; a test records one directly.
+ #[cfg(test)]
+ Feature(FeatureValue),
+ /// `None` means no declaration block of that kind exists on that side.
+ ElementDeclaration(Option<DeclarationBlockID>),
+ #[cfg(test)]
+ ElementStyleInput { reaction: u8, inherited_style_groups: u8 },
+ /// Whether a custom property registration is pending.
+ Flag(bool),
+}
+
+/// An element style input's pending reaction, and the inherited style groups it names.
+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
+pub struct ElementStyleInput {
+ pub reaction: u8,
+ pub inherited_style_groups: u8,
+}
+
+/// Parts of the document's environment an element's style may compute from beside its matches,
+/// its parent and the document's published inputs: what a transaction says moved of them, and
+/// what a record says its computation read of them.
+#[derive(Clone, Copy, Default, PartialEq, Eq, Debug)]
+pub struct StyleEnvironment(u8);
+
+impl StyleEnvironment {
+ /// The used color scheme: the user's preferred one and the schemes the document supports,
+ /// which `color-scheme`, `light-dark()` and the system colors resolve against.
+ pub const COLOR_SCHEME: Self = Self(1 << 0);
+ /// The device pixel ratio, which widths snapped as border widths and `image-set()` read.
+ pub const DEVICE_PIXEL_RATIO: Self = Self(1 << 1);
+ /// The media features a value's `if()` or custom function may test.
+ pub const MEDIA_FEATURES: Self = Self(1 << 2);
+ /// The viewport's width, which viewport-relative lengths may resolve against.
+ pub const VIEWPORT_WIDTH: Self = Self(1 << 3);
+ /// The viewport's height.
+ pub const VIEWPORT_HEIGHT: Self = Self(1 << 4);
+ /// Both axes of the viewport.
+ pub const VIEWPORT: Self = Self(Self::VIEWPORT_WIDTH.0 | Self::VIEWPORT_HEIGHT.0);
+ /// Every part.
+ pub const ALL: Self =
+ Self(Self::COLOR_SCHEME.0 | Self::DEVICE_PIXEL_RATIO.0 | Self::MEDIA_FEATURES.0 | Self::VIEWPORT.0);
+
+ /// The parts the host names by `bits`, as `StyleEnvironmentChange` bits.
+ pub fn from_bits(bits: u8) -> Self {
+ Self(bits & Self::ALL.0)
+ }
+
+ #[must_use]
+ pub fn is_empty(self) -> bool {
+ self.0 == 0
+ }
+
+ /// Whether this and `other` share a part.
+ #[must_use]
+ pub fn intersects(self, other: Self) -> bool {
+ self.0 & other.0 != 0
+ }
+
+ /// The parts this and `other` share.
+ #[must_use]
+ pub fn intersection(self, other: Self) -> Self {
+ Self(self.0 & other.0)
+ }
+}
+
+impl std::ops::BitOr for StyleEnvironment {
+ type Output = Self;
+ fn bitor(self, other: Self) -> Self {
+ Self(self.0 | other.0)
+ }
+}
+
+impl std::ops::BitOrAssign for StyleEnvironment {
+ fn bitor_assign(&mut self, other: Self) {
+ self.0 |= other.0;
+ }
+}
+
+/// The inputs the host published since the last transaction that the projection holds no row
+/// for: which elements' own declarations moved, which elements owe a style reaction, what moved
+/// of the document's environment, and whether something moved that can restyle any element. The
+/// projection says every change to the elements' facts and relations itself.
+#[derive(Clone, Default)]
+pub struct PendingElementInputs {
+ declarations: BTreeSet<StyleNodeID>,
+ style_inputs: BTreeMap<StyleNodeID, ElementStyleInput>,
+ environment: StyleEnvironment,
+ restyles_everything: bool,
+}
+
+impl PendingElementInputs {
+ #[must_use]
+ pub fn is_empty(&self) -> bool {
+ self.declarations.is_empty()
+ && self.style_inputs.is_empty()
+ && self.environment.is_empty()
+ && !self.restyles_everything
+ }
+
+ /// Whether the next transaction restyles elements for something of the document's environment
+ /// that moved, or every element.
+ #[must_use]
+ pub fn moves_environment(&self) -> bool {
+ !self.environment.is_empty() || self.restyles_everything
+ }
+
+ /// Note that `moved` of the document's environment moved, which restyles the elements whose
+ /// records read it in the next transaction.
+ pub fn note_environment_moved(&mut self, moved: StyleEnvironment) {
+ self.environment |= moved;
+ }
+
+ /// Restyle every element in the next transaction: an input moved that can reach any of them.
+ pub fn restyle_everything(&mut self) {
+ self.restyles_everything = true;
+ }
+
+ pub fn note_declaration(&mut self, node: StyleNodeID) {
+ self.declarations.insert(node);
+ }
+
+ /// Note a reaction requested for an element, beside every other one requested for it since
+ /// the last transaction.
+ pub fn note_style_input(&mut self, node: StyleNodeID, input: ElementStyleInput) {
+ let pending = self.style_inputs.entry(node).or_default();
+ pending.reaction |= input.reaction;
+ pending.inherited_style_groups |= input.inherited_style_groups;
+ }
+
+ /// The elements an input is pending for.
+ pub fn nodes(&self) -> impl Iterator<Item = StyleNodeID> + '_ {
+ self.declarations.iter().chain(self.style_inputs.keys()).copied()
+ }
+
+ /// Take the pending inputs into a transaction, in element order.
+ pub fn take_transaction(&mut self) -> StyleUpdate {
+ let Self {
+ declarations,
+ style_inputs,
+ environment,
+ restyles_everything,
+ } = std::mem::take(self);
+ StyleUpdate {
+ declarations: declarations.into_iter().collect(),
+ style_inputs: style_inputs.into_iter().collect(),
+ environment,
+ restyles_everything,
+ rule_changes: Default::default(),
+ }
+ }
+}
+
+/// What one transaction takes beside the projection's changes, in element order.
+#[derive(Default)]
+#[must_use]
+pub struct StyleUpdate {
+ /// The elements whose own declarations moved.
+ pub declarations: Vec<StyleNodeID>,
+ /// The elements that owe a style reaction, each with every reaction requested for it.
+ pub style_inputs: Vec<(StyleNodeID, ElementStyleInput)>,
+ /// What moved of the document's environment, which restyles the elements reading it.
+ pub environment: StyleEnvironment,
+ /// Whether the transaction restyles every element, from the facts as they are.
+ pub restyles_everything: bool,
+ /// What the transaction changed of the rules.
+ pub(crate) rule_changes: super::pipeline::rule_store::RuleChanges,
+}
+
+impl StyleUpdate {
+ /// Release the transaction's scratch charge. Called once the transaction has been consumed.
+ pub fn release(self) {}
+
+ /// Whether the transaction names no element and restyles nothing by itself.
+ #[must_use]
+ pub fn has_no_element_inputs(&self) -> bool {
+ self.declarations.is_empty()
+ && self.style_inputs.is_empty()
+ && self.environment.is_empty()
+ && !self.restyles_everything
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/inputs.rs b/Libraries/LibWeb/Rust/src/css/style/inputs.rs
index a904ce439f8..7751728d79f 100644
--- a/Libraries/LibWeb/Rust/src/css/style/inputs.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/inputs.rs
@@ -4,9 +4,10 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-use smallvec::SmallVec;
-
use super::*;
+use crate::css::selector::SelectorListRef;
+#[cfg(test)]
+use projection_writes::ProjectionWrites;
/// What the style mirror publishes about a text node's characters. The characters are shared with
/// the document rather than copied. The language tag is the one the text node's DOM parent element
@@ -108,147 +109,119 @@ pub struct PublishedContentFacts {
pub opens_or_closes_quotes: bool,
}
-unsafe extern "C" {
- fn web_css_custom_property_data_reference(data: *const std::ffi::c_void);
- fn web_css_custom_property_data_unreference(data: *const std::ffi::c_void);
-}
-
-/// A `Web::CSS::CustomPropertyData`, which Rust only names by pointer.
-#[repr(C)]
-pub(crate) struct CustomPropertyDataObject {
- _opaque: [u8; 0],
- _not_send_or_sync: std::marker::PhantomData<*const ()>,
-}
-
-// SAFETY: The data is immutable once built and counts its references atomically, so a shared
-// reference to it may be read and taken on any thread. The StyleLayout thread leaves giving one up
-// to the host (see `RetainedCustomPropertyData`'s `Drop`).
-unsafe impl Sync for CustomPropertyDataObject {}
-
-/// The custom-property environment one element holds, a `Web::CSS::CustomPropertyData` the engine
-/// keeps a reference to. The element keeps no copy of its own.
+/// The custom-property environment one element holds: the store the host holds as the environment,
+/// which the engine keeps a reference to. The element keeps no copy of its own.
+#[derive(Clone)]
pub(crate) struct RetainedCustomPropertyData {
- data: crate::css::host_shared::HostShared<CustomPropertyDataObject>,
+ store: std::sync::Arc<crate::css::custom_properties::CustomPropertyStore>,
}
impl RetainedCustomPropertyData {
/// # Safety
- /// `data` must be a live `Web::CSS::CustomPropertyData`.
+ /// `data` must be a live `Web::CSS::CustomPropertyData`, which is a store the host holds a
+ /// reference to.
pub(super) unsafe fn retain(data: *const std::ffi::c_void) -> Self {
- unsafe { web_css_custom_property_data_reference(data) };
+ let store = data.cast::<crate::css::custom_properties::CustomPropertyStore>();
+ // SAFETY: Guaranteed by the caller: the store lives in an Arc.
+ unsafe { std::sync::Arc::increment_strong_count(store) };
Self {
- data: crate::css::host_shared::HostShared::new(data.cast()),
+ store: unsafe { std::sync::Arc::from_raw(store) },
}
}
pub(crate) fn data(&self) -> *const std::ffi::c_void {
- self.data.as_ptr().cast()
+ std::sync::Arc::as_ptr(&self.store).cast()
}
}
-/// The custom-property environment an element or one of its synthetic pseudo-elements holds, with
-/// what a move of the environment it inherits reads of it.
-#[derive(Clone)]
-pub(crate) struct HeldCustomPropertyEnvironment {
- /// The identity the host's object names the environment by.
- pub(crate) identity: u64,
- /// For the element's animation overlay, the environment its style resolved to, which its
- /// animations sampled their custom properties over.
- pub(crate) sampled_over: Option<u64>,
- /// Whether the environment the style resolves to declares custom properties of its own, over
- /// the one it inherits.
- pub(crate) declares: bool,
- pub(crate) data: RetainedCustomPropertyData,
+/// The style record each element holds, by element index, as the host reports every record it
+/// installs or clears: what the host holds, which lags what the engine assigned until the host
+/// takes an installation, and which it clears under `display: none`. The column holds a reference
+/// to each, which keeps the record, and the identity naming it, until the host reports another.
+/// Nearly every element holds one, so a dense column takes less than a map would.
+///
+/// The column is copied on write in chunks: a fork shares it whole, and a host write while a fork
+/// lives copies only the chunk it lands in.
+#[derive(Clone, Default)]
+pub(crate) struct HeldStyleRecords {
+ by_element: crate::cow_column::CowColumn<HeldRecord, HELD_STYLE_RECORDS_PER_CHUNK>,
}
-/// A fork's environment holds its own reference.
-impl Clone for RetainedCustomPropertyData {
- fn clone(&self) -> Self {
- // SAFETY: The row holds a reference, so the data is live.
- unsafe { Self::retain(self.data()) }
- }
-}
+/// A row of [`HeldStyleRecords`], which compares by the record it holds.
+#[derive(Clone, Default)]
+struct HeldRecord(Option<std::sync::Arc<super::pipeline::Record>>);
-impl Drop for RetainedCustomPropertyData {
- fn drop(&mut self) {
- // The last reference destroys the data, which gives up its references to its values, counted without atomics
- // on the host's thread. The StyleLayout thread, which lets go of an environment beside the host's task as a
- // fork or a streamed write does, leaves it to the host.
- if crate::stage_thread::is_on_style_layout_thread() {
- CUSTOM_PROPERTY_DATA_LET_GO_BESIDE_THE_HOST
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner)
- .push(self.data() as usize);
- return;
+impl PartialEq for HeldRecord {
+ fn eq(&self, other: &Self) -> bool {
+ match (&self.0, &other.0) {
+ (Some(record), Some(other)) => std::sync::Arc::ptr_eq(record, other),
+ (None, None) => true,
+ _ => false,
}
- // SAFETY: The row owns exactly one reference, taken in `retain`.
- unsafe { web_css_custom_property_data_unreference(self.data()) };
}
}
-/// The references to custom-property environments the StyleLayout thread let go of, which the host gives up.
-static CUSTOM_PROPERTY_DATA_LET_GO_BESIDE_THE_HOST: std::sync::Mutex<Vec<usize>> = std::sync::Mutex::new(Vec::new());
-
-/// Gives up the references to custom-property environments the StyleLayout thread let go of. On the host's thread, or
-/// in a job the host waits for.
-pub(crate) fn give_up_custom_property_data_let_go_beside_the_host(_: &crate::stage::MainThread) {
- let let_go = std::mem::take(
- &mut *CUSTOM_PROPERTY_DATA_LET_GO_BESIDE_THE_HOST
- .lock()
- .unwrap_or_else(std::sync::PoisonError::into_inner),
- );
- for data in let_go {
- // SAFETY: Each entry is a reference a dropped environment owned.
- unsafe { web_css_custom_property_data_unreference(data as *const std::ffi::c_void) };
+/// How many elements' records a chunk of [`HeldStyleRecords`] holds: a host write while a fork
+/// lives copies this many.
+const HELD_STYLE_RECORDS_PER_CHUNK: usize = 64;
+
+impl HeldStyleRecords {
+ /// The record `node` holds.
+ #[must_use]
+ pub(crate) fn get(&self, node: StyleNodeID) -> Option<&std::sync::Arc<super::pipeline::Record>> {
+ self.by_element.get(node.element_index()? as usize)?.0.as_ref()
}
-}
-/// Compile one rule's selectors, interning the names they test through `atoms`.
-pub(super) fn compile_selector_program(
- atoms: &mut DocumentAtoms,
- fold_id_and_class_name_case: bool,
- html_element_namespace: StyleAtomID,
- selectors: &[&CompiledSelector],
- namespaces: NamespaceScope,
- scope: &ScopeChain<'_>,
- counters: &Counters,
-) -> SelectorProgram {
- let mut intern = |raw: usize, namespace: Option<StyleAtomID>| -> StyleAtomID {
- let local = atoms.intern_raw(raw);
- let Some(namespace) = namespace else {
- return local;
- };
- atoms.intern_qualified(namespace, local)
- };
- let mut compiler = SelectorCompiler::new(
- &mut intern,
- fold_id_and_class_name_case,
- html_element_namespace,
- namespaces,
- );
- let count_entry = |compiled: &compiler::CompiledEntry, counters: &Counters| {
- if let Some(counter) = compiled.marker.and_then(|marker| marker.counter()) {
- counters.bump(counter);
- }
- counters.bump(Counter::ExactSelectorEntries);
- };
- for selector in selectors {
- count_entry(&compiler.compile_in_scope(selector, scope), counters);
- if selector.styles_every_search_text_match() {
- count_entry(
- &compiler.compile_in_scope_for_current_search_text_match(selector, scope),
- counters,
- );
- }
+ #[must_use]
+ pub(crate) fn contains(&self, node: StyleNodeID) -> bool {
+ self.get(node).is_some()
}
- compiler.finish()
-}
-impl RetainedState {
- pub(super) fn push_pending_region(&mut self, regions: &mut Vec<ImpactRegion>, region: ImpactRegion) {
- regions.push(region);
+ /// Note that `node` holds `record`, or none, answering the one it held.
+ pub(crate) fn set(
+ &mut self,
+ node: StyleNodeID,
+ record: Option<std::sync::Arc<super::pipeline::Record>>,
+ ) -> Option<std::sync::Arc<super::pipeline::Record>> {
+ let index = node.element_index().expect("only elements hold style records") as usize;
+ if self.by_element.len() <= index {
+ record.as_ref()?;
+ self.by_element.grow_to(index + 1);
+ }
+ self.by_element
+ .replace(index, HeldRecord(record))
+ .expect("the column holds every element below its length")
+ .0
+ }
+
+ /// Every element holding a record, with the record.
+ pub(crate) fn iter(&self) -> impl Iterator<Item = (StyleNodeID, &std::sync::Arc<super::pipeline::Record>)> + '_ {
+ (0..self.by_element.len()).filter_map(|index| {
+ let record = self.by_element.get(index)?.0.as_ref()?;
+ Some((
+ StyleNodeID::element(u32::try_from(index).expect("element index exceeds u32")),
+ record,
+ ))
+ })
}
+ pub(crate) fn heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {
+ self.by_element.heap_size(sizer, |_, _| 0)
+ }
+}
+
+/// The custom-property environment an element or one of its synthetic pseudo-elements holds.
+#[derive(Clone)]
+pub(crate) struct HeldCustomPropertyEnvironment {
+ /// The identity the host's object names the environment by.
+ pub(crate) identity: u64,
+ /// For the element's animation overlay, the environment its style resolved to, which its
+ /// animations sampled their custom properties over.
+ pub(crate) sampled_over: Option<u64>,
+ pub(crate) data: RetainedCustomPropertyData,
+}
+
+impl RetainedState {
/// Says whether the document matches id and class selectors ASCII case-insensitively.
///
/// A document only learns its mode while it is still empty - a parser reads it from the doctype
@@ -259,6 +232,14 @@ impl RetainedState {
self.fold_id_and_class_name_case = fold;
}
+ /// What matching selectors in the document needs to know of it.
+ pub(super) fn document_matching(&self) -> super::component_matching::DocumentMatching {
+ super::component_matching::DocumentMatching {
+ html_namespace: self.html_element_namespace,
+ fold_ids_and_classes: self.fold_id_and_class_name_case,
+ }
+ }
+
/// The HTML namespace, for an HTML document, or none for any other kind. It is what decides
/// whether an attribute name from the legacy list compares its value case-insensitively.
pub fn set_html_element_namespace(&mut self, namespace: StyleAtomID) {
@@ -266,7 +247,7 @@ impl RetainedState {
}
#[must_use]
- pub fn tree(&self) -> &StyleNodeTree {
+ pub fn tree(&self) -> &HostTree {
&self.tree
}
@@ -277,26 +258,8 @@ impl RetainedState {
#[must_use]
#[cfg(test)]
- pub(super) fn program(&self) -> &StyleSheetProgram {
- &self.program
- }
-
- pub(super) fn add_routing_rule(&mut self, rule: RuleID, program: SelectorProgramID) {
- // A detached sheet's routes were shed, and reattachment restores the current routes of
- // every live rule in the sheet, so routes added for a rule edited while its sheet is
- // detached would come back twice. The exclusion covers the edit until the sheet reattaches.
- if self
- .sheets_excluded_from_routing
- .contains(self.program.rule_sheet(rule).0 as usize)
- {
- return;
- }
- if let Some(deferred) = &mut self.deferred_user_agent_routes {
- deferred.push((rule, program));
- return;
- }
- let routing = Arc::make_mut(&mut self.routing);
- routing.add_rule(rule, program, &self.programs);
+ pub(super) fn rules(&self) -> &RuleStore {
+ &self.rules
}
/// The process-global atom for one interned name identity.
@@ -305,7 +268,7 @@ impl RetainedState {
/// same word but assigning their own sequences would compare unequal for the same name, which
/// is a silent failure to match rather than a loud one.
pub fn intern_atom(&mut self, raw: usize) -> StyleAtomID {
- self.atoms.intern_cpp_raw(raw)
+ self.atoms.intern_raw(raw)
}
/// The document-local atom for a name qualified by a namespace.
@@ -321,8 +284,8 @@ impl RetainedState {
///
/// # Safety
/// `raw` must be zero or a live `AK::Utf16FlyString` raw representation.
- pub unsafe fn note_custom_property_name(&mut self, name: StyleAtomID, raw: usize, text: &[u16]) {
- if unsafe { self.custom_property_environments.note_name(name, raw, text) } {
+ pub unsafe fn note_custom_property_name(&mut self, name: StyleAtomID, raw: usize) {
+ if unsafe { self.custom_property_environments.note_name(name, raw) } {
self.counters.bump(Counter::CustomPropertyNamesPublished);
}
}
@@ -344,69 +307,55 @@ impl RetainedState {
self.declaration_block_version = versions;
}
- pub(super) fn compile_selectors(
+ /// Record the attribute names `selectors`, inside the `@scope` levels `scope`, test, those whose values they read
+ /// as text, and whether they test `:local-link`, which is all the host asks of an element's attributes that a
+ /// selector may not read, and what an arrival has to carry to reach the anchor of one of their `:has()`.
+ pub(super) fn note_selectors(
&mut self,
- selectors: &[&CompiledSelector],
- namespaces: NamespaceScope,
- scope: &ScopeChain<'_>,
- reusable: Option<SelectorProgramID>,
- ) -> SelectorProgramID {
- let compiled = compile_selector_program(
- &mut self.atoms,
- self.fold_id_and_class_name_case,
- self.html_element_namespace,
- selectors,
- namespaces,
- scope,
- &self.counters,
- );
- self.note_selector_attribute_names(&compiled);
- if let Some(reusable) = reusable
- && self.programs.get(reusable) == &compiled
- {
- return reusable;
- }
- self.note_relational_arrival_keys(&compiled);
- let program = self.programs.add(compiled);
- self.selector_programs_need_sweep |= reusable.is_some();
+ selectors: &SelectorListRef,
+ scope: Option<&super::bridge::BoundScopeChain>,
+ ) {
+ self.note_selector_summary(super::selector_analysis::SelectorSummary::of(selectors.view(), scope));
+ }
- program
+ /// What the selectors the engine noted test, summed up.
+ pub(super) fn selector_summary(&self) -> super::selector_analysis::SelectorSummary {
+ super::selector_analysis::SelectorSummary {
+ tested_attribute_names: self.tested_attribute_names.iter().copied().collect(),
+ attribute_value_text_names: self.attribute_value_text_names.iter().copied().collect(),
+ tests_local_link: self.selectors_test_local_link,
+ relational_arrival_keys: self.unresolved_relational_arrival_keys.iter().copied().collect(),
+ }
}
- /// Record the attribute names `program` tests, and those whose values it reads as text.
- pub(super) fn note_selector_attribute_names(&mut self, program: &SelectorProgram) {
- if !program
- .tested_attribute_names()
- .all(|name| self.tested_attribute_names.contains(&name))
+ /// Note what the selectors `summary` sums up test, which the engine's fact projection reads.
+ pub(super) fn note_selector_summary(&mut self, summary: super::selector_analysis::SelectorSummary) {
+ self.selectors_test_local_link |= summary.tests_local_link;
+ if !summary
+ .tested_attribute_names
+ .iter()
+ .all(|name| self.tested_attribute_names.contains(name))
{
- Arc::make_mut(&mut self.tested_attribute_names).extend(program.tested_attribute_names());
+ Arc::make_mut(&mut self.tested_attribute_names).extend(summary.tested_attribute_names.iter().copied());
}
- if program
- .attribute_value_text_names()
- .all(|name| self.attribute_value_text_names.contains(&name))
+ for key in summary.relational_arrival_keys {
+ if !self.relational_arrival_keys.keys.contains(&key) {
+ self.unresolved_relational_arrival_keys.insert(key);
+ }
+ }
+ if summary
+ .attribute_value_text_names
+ .iter()
+ .all(|name| self.attribute_value_text_names.contains(name))
{
return;
}
- Arc::make_mut(&mut self.attribute_value_text_names).extend(program.attribute_value_text_names());
+ Arc::make_mut(&mut self.attribute_value_text_names).extend(summary.attribute_value_text_names);
self.attribute_value_text_requirements_version += 1;
}
- /// Record what an arrival has to carry to reach the anchor of one of `program`'s `:has()` arguments.
- pub(super) fn note_relational_arrival_keys(&mut self, program: &SelectorProgram) {
- if !program.contains_relational_selector() {
- return;
- }
- for entry in 0..program.entries().len() {
- program.collect_transpose_entry_points(entry, |site| {
- if site.anchor.is_some() && !self.relational_arrival_keys.keys.contains(&site.key) {
- self.unresolved_relational_arrival_keys.insert(site.key);
- }
- });
- }
- }
-
/// Starts the keys over from `keys`, as a sweep that reclaimed some of their atoms leaves them.
- pub(super) fn replace_relational_arrival_keys(&mut self, keys: HashSet<RoutingKey>) {
+ pub(super) fn replace_relational_arrival_keys(&mut self, keys: HashSet<DispatchKey>) {
self.relational_arrival_keys = Arc::default();
self.unresolved_relational_arrival_keys = keys;
self.relational_arrival_keys_version += 1;
@@ -425,11 +374,11 @@ impl RetainedState {
continue;
}
match key {
- RoutingKey::TagName(atom)
- | RoutingKey::Id(atom)
- | RoutingKey::Class(atom)
- | RoutingKey::AttributeName(atom) => name_atoms.push(atom),
- RoutingKey::State(fact) => resolved.states.push(fact as u8),
+ DispatchKey::TagName(atom)
+ | DispatchKey::Id(atom)
+ | DispatchKey::Class(atom)
+ | DispatchKey::AttributeName(atom) => name_atoms.push(atom),
+ DispatchKey::State(fact) => resolved.states.push(fact as u8),
_ => resolved.reached_by_any_arrival = true,
}
}
@@ -451,12 +400,6 @@ impl RetainedState {
&self.relational_arrival_keys
}
- /// Moves whenever an attribute name comes to require its value text: a selector's here, or an
- /// `attr()`'s anywhere in the process.
- pub fn attribute_value_text_requirements_version(&self) -> u64 {
- with_attr_names_read(self.selector_attribute_value_text_requirements_version())
- }
-
/// Moves whenever an attribute name comes to require its value text for a selector here.
pub fn selector_attribute_value_text_requirements_version(&self) -> u64 {
self.attribute_value_text_requirements_version
@@ -467,30 +410,16 @@ impl RetainedState {
&self.attribute_value_text_names
}
+ /// Whether a selector here tests `:local-link`.
+ pub(crate) fn selectors_test_local_link(&self) -> bool {
+ self.selectors_test_local_link
+ }
+
/// The attribute names a selector here tests in any way.
pub(crate) fn selector_tested_attribute_names(&self) -> &SelectorAttributeNames {
&self.tested_attribute_names
}
- /// Whether the host records what the values of an attribute name spell: for a selector whose
- /// operator an atom cannot answer, or for an `attr()`, which reads an attribute in no namespace
- /// by its local name.
- #[must_use]
- pub fn attribute_name_requires_value_text(&self, name: StyleAtomID) -> bool {
- self.facts
- .attribute_name_keys(name)
- .any(|key| self.attribute_value_text_names.contains(&key))
- || self
- .facts
- .attribute_substitution_name(name)
- .is_some_and(crate::css::parser::arbitrary_substitution::attr_may_read_name)
- }
-
- /// Whether the last transaction planned nothing but derived child reactions, read once.
- pub fn take_only_derived_child_reactions(&mut self) -> bool {
- std::mem::take(&mut self.last_transaction_only_derived_child_reactions)
- }
-
/// Apply an accepted input to the authoritative fact arrangement.
///
/// A fact exists in the store exactly because a mutation published it, which is what lets the
@@ -498,221 +427,94 @@ impl RetainedState {
/// element".
pub(super) fn apply_to_facts_without_settling(&mut self, key: InputKey, new: InputValue) {
match (key, new) {
- (InputKey::LocalFeature(node, feature), InputValue::Feature(value)) => match feature {
- LocalFeatureKey::TagName => {
- if let FeatureValue::Atom(atom) = value {
- self.facts.set_tag(node, atom);
- }
- }
- LocalFeatureKey::PartExposure => self.facts.set_part_exposure(
- node,
- match value {
- FeatureValue::Atom(atom) => atom,
- _ => StyleAtomID::NONE,
- },
- ),
- LocalFeatureKey::Language => self.facts.set_language(
- node,
- match value {
- FeatureValue::Atom(atom) => atom,
- _ => StyleAtomID::NONE,
- },
- ),
- LocalFeatureKey::Directionality => self.facts.set_directionality(
- node,
- match value {
- FeatureValue::Atom(atom) => atom,
- _ => StyleAtomID::NONE,
- },
- ),
- LocalFeatureKey::HeadingLevel => self.facts.set_heading_level(
- node,
- match value {
- FeatureValue::Number(level) => level as u8,
- _ => 0,
- },
- ),
- LocalFeatureKey::FoldedTagName => self.facts.set_folded_tag(
- node,
- match value {
- FeatureValue::Atom(atom) => atom,
- _ => StyleAtomID::NONE,
- },
- ),
- // Parts and custom states are published as complete sets after their individual
- // journal deltas have been recorded. Arrival is only a routing key.
- LocalFeatureKey::Part(_) | LocalFeatureKey::CustomState(_) | LocalFeatureKey::ArrivingFacts => {}
- // A text node is not a style node, so nothing in the tree can say it is there.
- // `Present` on this key means the element is empty.
- LocalFeatureKey::Emptiness => self.facts.set_has_text_content(node, !value.holds()),
- LocalFeatureKey::Id => self.facts.set_id(
- node,
- match value {
- FeatureValue::Atom(atom) => atom,
- _ => StyleAtomID::NONE,
- },
- ),
- LocalFeatureKey::Class(class) => self.facts.set_class(node, class, value.holds()),
- LocalFeatureKey::Attribute(name) => {
- // The value's atom rides on the same delta. Presence is what routing reads; the
- // value is what an exact test compares, and a cold pass has no DOM to ask.
- let atom = match value {
- FeatureValue::Atom(atom) => atom,
- _ => StyleAtomID::NONE,
- };
- self.facts.set_attribute(node, name, atom, value.holds());
- }
- },
- (InputKey::State(node, fact), InputValue::State(value)) => {
- self.facts.set_state(node, fact, value);
+ #[cfg(test)]
+ (InputKey::LocalFeature(node, feature), InputValue::Feature(value)) => {
+ self.write_projection_for_test(|writes| writes.apply_feature(node, feature, value));
}
_ => {}
}
}
- /// The routing keys of every fact an arriving element announced, read back off the element.
- ///
- /// A fact is in the store by the time routing runs, so this is what the individual inputs would
- /// have published between them - a class each, the tag, the id, each attribute name.
- #[must_use]
- pub(super) fn routing_keys_of_arriving_facts(&self, node: StyleNodeID) -> SmallVec<[RoutingKey; 4]> {
- let mut keys = SmallVec::new();
-
- let tag = self.facts.tag_of_node(node);
- if !tag.is_none() {
- keys.push(RoutingKey::TagName(tag));
- }
- let folded_tag = self.facts.folded_tag_of_node(node);
- if !folded_tag.is_none() && folded_tag != tag {
- keys.push(RoutingKey::TagName(folded_tag));
- }
- let id = self.facts.id_of_node(node);
- if !id.is_none() {
- keys.push(RoutingKey::Id(id));
- }
- for &class in self.facts.classes_of_node(node) {
- keys.push(RoutingKey::Class(class));
- }
- for attribute in self.facts.attributes_of_node(node) {
- for key in self.facts.attribute_name_keys(attribute) {
- keys.push(RoutingKey::AttributeName(key));
- }
- }
- if !self.facts.language_of(node).is_none() {
- keys.push(RoutingKey::Language);
- }
- let directionality = self.facts.directionality_of(node);
- if !directionality.is_none() {
- keys.push(RoutingKey::Directionality(directionality));
- }
- if let Some(row) = self.facts.primary().row_of(node) {
- for &part in self.facts.primary().parts_of(row) {
- keys.push(RoutingKey::Part(part));
- }
- for &state in self.facts.primary().custom_states_of(row) {
- keys.push(RoutingKey::CustomState(state));
- }
- }
- for fact in self.facts.states_of_node(node).facts() {
- keys.push(RoutingKey::State(fact));
+ /// Write the projection as a test's host, publishing the writes to it at once and counting them.
+ #[cfg(test)]
+ pub(super) fn write_projection_for_test<R>(&mut self, write: impl FnOnce(&mut ProjectionWrites<'_>) -> R) -> R {
+ let (answer, counts) = self.projection.write_for_test(|writer| write(&mut writer.writes()));
+ for (counter, count) in counts {
+ self.counters.add(counter, count);
}
- // An element arrives empty or not, and either way that is a positional truth about it that
- // nothing else in this transaction says.
- keys.push(RoutingKey::Structural);
-
- keys
+ answer
}
+ /// How `node` stands in the tree as the last transaction committed it: detached in its tree
+ /// scope where it stood in no tree then.
pub(super) fn settled_tree_relations(&self, node: StyleNodeID) -> TreeRelations {
- TreeRelations {
- parent: self.tree.parent(node),
- previous_element_sibling: self.tree.previous_element_sibling(node),
- next_element_sibling: self.tree.next_element_sibling(node),
- tree_scope: self.tree.tree_scope(node),
- assigned_slot: self.tree.assigned_slot_of(node),
- }
+ self.projection
+ .committed_relations(node)
+ .unwrap_or_else(|| TreeRelations {
+ parent: None,
+ previous_element_sibling: None,
+ next_element_sibling: None,
+ tree_scope: self.projection.tree_scope(node),
+ assigned_slot: None,
+ })
}
- pub(super) fn depth_recompute_nodes(
- &self,
- staged_rows: &[(StyleNodeID, Option<TreeRelations>, Option<TreeRelations>)],
- ) -> HashSet<StyleNodeID> {
- staged_rows
+ /// Of the elements whose links were written, those under which the deepest element may have deepened: those that
+ /// arrived, and those standing under another parent than the last transaction committed.
+ pub(super) fn depth_recompute_nodes(&self, nodes: &[StyleNodeID]) -> HashSet<StyleNodeID> {
+ nodes
.iter()
- .filter_map(|&(node, before, relations)| {
- let relations = relations?;
- (before.is_none() || self.tree.parent(node) != relations.parent).then_some(node)
+ .copied()
+ .filter(|&node| {
+ self.projection.written_relations(node).is_some_and(|relations| {
+ self.projection
+ .committed_relations(node)
+ .is_none_or(|committed| committed.parent != relations.parent)
+ })
})
.collect()
}
- pub(super) fn link(&mut self, node: StyleNodeID, new: TreeRelations) {
- self.tree.set_parent(node, new.parent);
- self.tree.set_next_element_sibling(node, new.next_element_sibling);
- self.tree
- .set_previous_element_sibling(node, new.previous_element_sibling);
- if let Some(next) = new.next_element_sibling {
- self.tree.set_previous_element_sibling(next, Some(node));
- }
- match new.previous_element_sibling {
- Some(previous) => self.tree.set_next_element_sibling(previous, Some(node)),
- None => {
- if let Some(parent) = new.parent {
- self.tree.set_first_element_child(parent, Some(node));
- }
- }
- }
-
- if new.tree_scope != TreeScopeID::DOCUMENT {
- self.tree.enable_tree_scopes();
- }
- if self.tree.has_tree_scopes() {
- self.tree.set_tree_scope(node, new.tree_scope);
- }
-
- // The slot a slottable is assigned to is its parent in the flat tree, and `::slotted()`
- // walks back along it. A slot name change reassigns it with no DOM mutation at all, so the
- // relation has to be carried by the delta rather than derived from the tree.
- self.tree.set_assigned_slot(node, new.assigned_slot);
- }
-
- /// A fact whose value is an atom is absent when the atom is, so the two are one conversion.
- pub(super) fn atom_or_absent(atom: StyleAtomID) -> FeatureValue {
- match atom.is_none() {
- true => FeatureValue::Absent,
- false => FeatureValue::Atom(atom),
+ /// The depth of `node` in the tree as its links were written, which walks its ancestors.
+ #[must_use]
+ pub(super) fn element_depth(&self, node: StyleNodeID) -> u32 {
+ let written_parent = |node| {
+ self.projection
+ .written_relations(node)
+ .and_then(|relations| relations.parent)
+ };
+ let mut depth = 0;
+ let mut ancestor = written_parent(node);
+ while let Some(parent) = ancestor {
+ depth += 1;
+ ancestor = written_parent(parent);
}
+ depth
}
/// Report the element's resolved language tag.
/// Record the element's namespace.
///
- /// An element's namespace is fixed when it is created, so this is a fact the store holds rather
- /// than an input that moves: nothing routes from it, and no journal entry is needed.
+ /// An element's namespace is fixed when it is created, so this is a fact the projection holds
+ /// rather than an input that moves: nothing routes from it, and no transaction notes it.
#[cfg(test)]
pub fn set_element_namespace(&mut self, node: StyleNodeID, namespace: StyleAtomID) {
- self.facts.set_namespace(node, namespace);
- }
-
- /// Replace the element facts the style computation's adjustments read.
- pub fn set_element_adjustment_facts(&mut self, node: StyleNodeID, facts: u32) {
- self.computed_group_sets.set_adjustment_facts(node, facts);
+ self.projection.set_namespace(node, namespace);
}
- /// The element facts the store holds, as `bridge::element_adjustment_fact` names them. A text
- /// node and a retired identity hold none.
+ /// The element facts the host published, as `bridge::element_adjustment_fact` names them. A text node and an
+ /// identity minted again hold none.
#[must_use]
pub fn element_adjustment_facts(&self, node: StyleNodeID) -> u32 {
- self.computed_group_sets.adjustment_facts(node)
- }
-
- /// Replace the element facts a layout row built for the element records.
- pub fn set_element_construction_facts(&mut self, node: StyleNodeID, facts: u32) {
- self.computed_group_sets.set_construction_facts(node, facts);
+ self.projection.adjustment_facts(node)
}
/// Record what the element gives the natural size of its replaced content.
pub fn set_element_replaced_content_input(&mut self, node: StyleNodeID, input: ReplacedContentInput) {
+ // NB: A fork shares the table until either side writes it, so an input that moves nothing writes nothing.
+ if self.element_replaced_content_input(node) == input {
+ return;
+ }
if input == ReplacedContentInput::None {
self.replaced_content_inputs.remove(&node);
} else {
@@ -726,13 +528,16 @@ impl RetainedState {
self.replaced_content_inputs.get(&node).copied().unwrap_or_default()
}
- /// Record which principal box the element asks for.
- pub fn set_element_box_kind(&mut self, node: StyleNodeID, box_kind: super::bridge::ElementBoxKind) {
- if self.element_box_kind(node) == box_kind {
- return;
- }
- self.computed_group_sets.set_box_kind(node, box_kind);
- if let Some(&style_record) = self.held_style_records.get(&node) {
+ /// The identity of the record the host holds for the element `node`.
+ #[must_use]
+ pub(crate) fn held_style_record(&self, node: StyleNodeID) -> Option<u64> {
+ let identity = bridge::host_record_identity(self.held_style_records.get(node)?);
+ (identity != 0).then_some(identity)
+ }
+
+ /// The element asks for another principal box, as its published host facts say.
+ pub(crate) fn note_box_kind_change(&mut self, node: StyleNodeID) {
+ if let Some(style_record) = self.held_style_record(node) {
self.set_element_container_query_inputs(node, style_record);
}
}
@@ -741,7 +546,7 @@ impl RetainedState {
/// nothing in particular.
#[must_use]
pub(crate) fn element_box_kind(&self, node: StyleNodeID) -> super::bridge::ElementBoxKind {
- self.computed_group_sets.box_kind(node)
+ self.projection.box_kind(node)
}
/// The facts a layout row built for the node records, as `bridge::element_construction_fact`
@@ -756,7 +561,7 @@ impl RetainedState {
0
};
}
- self.computed_group_sets.construction_facts(node)
+ self.projection.construction_facts(node)
}
/// The record the element published, which its box is built from: the one a clock frame shows in its place, the
@@ -767,7 +572,7 @@ impl RetainedState {
let shown = self.tick_shown.element(node);
shown
.map(computed::FinalStyleRecordID::raw)
- .or_else(|| self.held_style_records.get(&node).copied())
+ .or_else(|| self.held_style_record(node))
.or_else(|| {
self.computed_group_sets
.assigned_style_record(node)
@@ -835,15 +640,12 @@ impl RetainedState {
/// over a node that is not an element.
#[must_use]
pub(crate) fn has_inclusive_ancestor_with_display_none_ignoring_animations(&self, node: StyleNodeID) -> bool {
- std::iter::successors(Some(node), |&current| self.tree.parent_or_shadow_host(current)).any(|ancestor| {
+ std::iter::successors(Some(node), |&current| self.projection.parent_or_shadow_host(current)).any(|ancestor| {
self.computed_group_sets
.assigned_style_record(ancestor)
.and_then(|record| self.computed_group_sets.style_record_view(record.raw()))
.is_some_and(|view| {
- !view.base_payloads.is_empty()
- && crate::css::computed_value_views::ComputedValuesView::new(SharedPayload::as_pointer_slice(
- view.base_payloads,
- ))
+ crate::css::computed_value_views::ComputedValuesView::of(view.base_payloads)
.display()
.is_none()
})
@@ -853,7 +655,7 @@ impl RetainedState {
/// Whether the element is a `<slot>`, whose children the flat tree takes elsewhere.
#[must_use]
pub fn element_is_slot(&self, node: StyleNodeID) -> bool {
- self.facts.is_slot(node)
+ self.projection.written_facts(node).is_some_and(|facts| facts.is_slot())
}
fn published_box_facts(&self, style_record: Option<computed::FinalStyleRecordID>) -> Option<PublishedBoxFacts> {
@@ -864,7 +666,7 @@ impl RetainedState {
#[must_use]
pub fn style_record_box_facts(&self, style_record: u64) -> Option<PublishedBoxFacts> {
let payloads = self.computed_group_sets.style_record_payloads(style_record)?;
- let view = crate::css::computed_value_views::ComputedValuesView::new(SharedPayload::as_pointer_slice(payloads));
+ let view = crate::css::computed_value_views::ComputedValuesView::of(payloads);
Some(PublishedBoxFacts {
display: view.display(),
content_visibility: view.content_visibility(),
@@ -879,10 +681,10 @@ impl RetainedState {
#[must_use]
pub fn text_style_parent_facts(&self, node: StyleNodeID) -> TextStyleParentFacts {
let parent = self
- .tree
+ .projection
.assigned_slot_of(node)
.or_else(|| self.tree.text_parent(node))
- .filter(|parent| self.tree.host_of(*parent).is_none() && !self.tree.is_relation_only(*parent));
+ .filter(|parent| self.projection.host_of(*parent).is_none() && !self.tree.is_relation_only(*parent));
let Some(parent) = parent else {
return TextStyleParentFacts::default();
};
@@ -936,7 +738,7 @@ impl RetainedState {
/// The element's resolved language tag, empty where it has none.
#[must_use]
pub fn element_language_tag(&self, node: StyleNodeID) -> &[u16] {
- self.facts.language_tag_of(node)
+ self.projection.language_tag_of(node)
}
/// The language tag a text node's transform reads: the one its DOM parent element resolves to.
@@ -944,17 +746,17 @@ impl RetainedState {
pub(crate) fn text_language_tag(&self, node: StyleNodeID) -> &[u16] {
self.tree
.text_parent(node)
- .filter(|&parent| self.tree.host_of(parent).is_none() && !self.tree.is_relation_only(parent))
- .map_or(&[], |parent| self.facts.language_tag_of(parent))
+ .filter(|&parent| self.projection.host_of(parent).is_none() && !self.tree.is_relation_only(parent))
+ .map_or(&[], |parent| self.projection.language_tag_of(parent))
}
/// Text directly under a shadow root uses its host's language for line breaking.
pub(crate) fn text_line_break_language_tag(&self, node: StyleNodeID) -> &[u16] {
self.tree
.text_parent(node)
- .map(|parent| self.tree.host_of(parent).unwrap_or(parent))
+ .map(|parent| self.projection.host_of(parent).unwrap_or(parent))
.filter(|&parent| !self.tree.is_relation_only(parent))
- .map_or(&[], |parent| self.facts.language_tag_of(parent))
+ .map_or(&[], |parent| self.projection.language_tag_of(parent))
}
/// Record the text node's whitespace-only state, as its data now spells it.
@@ -1022,8 +824,8 @@ impl RetainedState {
/// tree takes the document's styles, which looks names up in the document's scope instead.
#[must_use]
pub(crate) fn counter_style_tree_scope(&self, node: StyleNodeID) -> u32 {
- let tree_scope = self.tree.tree_scope(node);
- if self.program.scope_uses_document_sheets(tree_scope) {
+ let tree_scope = self.projection.tree_scope(node);
+ if self.rules.scope_uses_document_sheets(tree_scope) {
TreeScopeID::DOCUMENT.0
} else {
tree_scope.0
@@ -1064,16 +866,13 @@ impl RetainedState {
.style_record_dependency_flags(style_record.raw())
}
- /// The computed longhand table of the published style record `raw_style_record` names, which
- /// keeps what the record's values were specified as. `None` for zero, which names no record.
+ /// The longhands of the published style record `raw_style_record` names, which keep what the
+ /// record's values were specified as. `None` for zero, which names no record.
#[must_use]
- pub(crate) fn published_record_longhand_table(
- &self,
- raw_style_record: u64,
- ) -> Option<&crate::css::computed_longhand_table::ComputedLonghandTable> {
+ pub(crate) fn published_record_longhands(&self, raw_style_record: u64) -> Option<computed::ViewLonghands<'_>> {
let style_record = computed::FinalStyleRecordID::from_raw(raw_style_record)?;
let view = self.computed_group_sets.style_record_view(style_record.raw())?;
- view.longhand_table
+ Some(view.longhands())
}
pub(super) fn published_style_record_view(
@@ -1081,32 +880,19 @@ impl RetainedState {
style_record: Option<computed::FinalStyleRecordID>,
) -> Option<crate::css::computed_value_views::ComputedValuesView<'_>> {
let payloads = self.computed_group_sets.style_record_payloads(style_record?.raw())?;
- Some(crate::css::computed_value_views::ComputedValuesView::new(
- SharedPayload::as_pointer_slice(payloads),
- ))
- }
-
- /// Record what an attribute-value atom spells, for the operators an atom cannot answer and for
- /// `attr()`.
- pub fn set_attribute_value_text(&mut self, value: StyleAtomID, text: &[u16]) {
- self.facts.set_attribute_value_text(value, text);
- }
-
- #[must_use]
- #[cfg(test)]
- pub fn has_attribute_value_text(&self, value: StyleAtomID) -> bool {
- self.facts.has_attribute_value_text(value)
+ Some(crate::css::computed_value_views::ComputedValuesView::of(payloads))
}
/// Record what a language atom spells, so `:lang()` can compare its ranges against the tag.
+ #[cfg(test)]
pub fn set_element_language_text(&mut self, language: StyleAtomID, text: &[u16]) {
- self.counters.bump(Counter::LanguageTextsPublished);
- self.facts.set_language_text(language, text);
+ self.write_projection_for_test(|writes| writes.set_language_text(language, text));
}
- /// See `ElementFactStore::note_attribute_name_forms`.
+ /// See [`pipeline::projection::Projection::note_attribute_name_forms`].
+ #[cfg(test)]
pub fn note_attribute_name_forms(&mut self, name: StyleAtomID, forms: index::AttributeNameForms) {
- self.facts.note_attribute_name_forms(name, forms);
+ self.write_projection_for_test(|writes| writes.projection.note_attribute_name_forms(name, forms));
}
/// Record the id an element answers to, or clear it with atom zero.
@@ -1117,17 +903,19 @@ impl RetainedState {
/// The first element in tree order that answers to `name` inside `tree_scope`.
#[must_use]
pub fn element_by_id(&self, tree_scope: TreeScopeID, name: StyleAtomID) -> Option<StyleNodeID> {
- self.tree.element_by_id(tree_scope, name)
+ self.tree.element_by_id(&self.projection, tree_scope, name)
}
- /// The style group payloads the element's published record holds, for a reader that reaches an
- /// element by identity rather than through a layout row. `None` while the element has no
- /// record.
+ /// The computed style of the element's published record, for a reader that reaches an element
+ /// by identity rather than through a layout row. `None` while the element has no record.
#[must_use]
- pub fn element_published_style_payloads(&self, node: StyleNodeID) -> Option<&[*const std::ffi::c_void]> {
+ pub(crate) fn element_published_style(
+ &self,
+ node: StyleNodeID,
+ ) -> Option<crate::css::computed_value_views::ComputedValuesView<'_>> {
let record = self.published_element_record(node)?;
let payloads = self.computed_group_sets.style_record_payloads(record.raw())?;
- Some(SharedPayload::as_pointer_slice(payloads))
+ Some(crate::css::computed_value_views::ComputedValuesView::of(payloads))
}
/// Keep the atom a layout publication names live for as long as the publication does.
@@ -1144,19 +932,10 @@ impl RetainedState {
self.atoms.release_published(atom);
}
- /// See `ElementFactStore::note_attribute_substitution_name`.
- pub fn note_attribute_substitution_name(&mut self, name: StyleAtomID, local_name: &[u16]) {
- self.facts.note_attribute_substitution_name(name, local_name);
- }
-
- pub fn set_shadow_root(&mut self, host: StyleNodeID, shadow_root: StyleNodeID) {
- self.tree.set_shadow_root(host, shadow_root);
- }
-
/// Replace the ordered list of nodes a slot has assigned to it, text nodes included.
+ #[cfg(test)]
pub fn set_slot_assigned_nodes(&mut self, slot: StyleNodeID, nodes: &[StyleNodeID]) {
- self.counters.bump(Counter::SlotAssignedNodeListsPublished);
- self.tree.set_assigned_nodes(slot, nodes);
+ self.write_projection_for_test(|writes| writes.set_slot_assigned_nodes(slot, nodes));
}
/// Replace the document's top layer, in the order its members were added.
@@ -1164,8 +943,11 @@ impl RetainedState {
self.tree.set_top_layer(members);
}
- /// Retire text identities as their nodes disconnect.
+ /// Retire text identities as their nodes disconnect. The host drops them from the slots they were assigned to.
pub fn retire_text_style_nodes(&mut self, nodes: impl IntoIterator<Item = StyleNodeID>) {
+ let nodes: Vec<StyleNodeID> = nodes.into_iter().collect();
+ #[cfg(test)]
+ self.write_projection_for_test(|writes| writes.projection.retire_texts(nodes.iter().copied()));
self.tree.retire_texts(nodes);
}
@@ -1197,62 +979,38 @@ impl RetainedState {
// -- Stylesheet program ------------------------------------------------------------------
//
- // Every CSSOM mutation maps to a precise typed delta. None of them produces a generic document
- // invalidation, and the granularity is what makes that true: a declaration edit journals the
- // declaration field alone, so selector truth is untouched by an edit that cannot change it.
+ // Every CSSOM mutation changes the rules it touches and no others. None of them produces a
+ // generic document invalidation: the transaction names the rules that moved, and the rule
+ // index tells what each of them decides.
- pub fn add_sheet(&mut self, object: StyleSheetObjectID, origin: CascadeOrigin) -> SheetID {
+ pub fn add_sheet(&mut self, origin: CascadeOrigin) -> SheetID {
// Reserving an unattached sheet identity cannot change any scope's semantic program.
- let sheet = self.program.add_sheet(object, origin);
- self.settle_program();
+ self.rules.add_sheet(origin)
+ }
+
+ /// Add a sheet standing for the sheet the process published from the native sheet
+ /// `source_identity`, whose rules the document reads from the process.
+ pub(crate) fn add_user_agent_sheet(&mut self, source_identity: u64) -> SheetID {
+ let rules = self.process_style.user_agent_rules();
+ let published = rules
+ .sheet_of_source(source_identity)
+ .expect("the host publishes a user agent sheet before a document adds it");
+ self.note_selector_summary((*rules.selector_summary(published)).clone());
+ let sheet = self.rules.add_sheet(CascadeOrigin::UserAgent);
+ self.rules.bind_user_agent_sheet(sheet, rules, published);
sheet
}
- /// Whether a sheet's rules keep their routing entry points: it is attached somewhere, or the host keeps it for
- /// reattachment.
- pub(super) fn sheet_keeps_routing(&self, sheet: SheetID) -> bool {
- self.program.sheet_is_attached_somewhere(sheet) || self.sheets_kept_for_reattachment.contains(sheet.0 as usize)
- }
-
- /// Note that the host keeps a detached sheet compiled for reattachment, or no longer does.
- pub(super) fn set_sheet_kept_for_reattachment(&mut self, sheet: SheetID, kept: bool) {
- if !self.sheets_kept_for_reattachment.set(sheet.0 as usize, kept).0 {
- return;
- }
- if kept {
- self.restore_routing_for_reattached_sheet(sheet);
- } else {
- self.routing_needs_detachment_sweep = true;
- }
- }
-
- /// A sheet whose routes were shed while it was detached contributes routes again the moment
- /// it reattaches. The registry must be whole before the attachment's transaction plans, so
- /// this runs at recording time rather than waiting for the next sweep.
- pub(super) fn restore_routing_for_reattached_sheet(&mut self, sheet: SheetID) {
- if !self.sheets_excluded_from_routing.set(sheet.0 as usize, false).0 {
+ /// Keep whether the keyframes of the animations of `node`, as the host sampled them, say
+ /// `inherit` for a property that does not inherit.
+ pub(crate) fn note_keyframes_read_parent_reset_values(&mut self, node: StyleNodeID, reads: bool) {
+ if reads == self.keyframes_reading_parent_reset_values.contains(&node) {
return;
}
- let rules = self
- .program
- .rules_in_sheet(sheet)
- .into_iter()
- .filter(|&rule| self.program.rule_is_live(rule))
- .filter_map(|rule| Some((rule, self.program.rule_version(rule).selector_program?)));
- let programs = &self.programs;
- let routing = Arc::make_mut(&mut self.routing);
- for (rule, program) in rules {
- routing.add_rule(rule, program, programs);
- }
- }
-
- /// Record the animation names an element's computed style references.
- ///
- /// This is an index, not an input: an element whose `animation-name` changed was already
- /// recomputed by whatever changed it. What the index is for is the other direction - a
- /// `@keyframes` rule finding the elements running the animation it describes.
- pub fn set_element_animation_names(&mut self, node: StyleNodeID, names: &[StyleAtomID]) {
- self.facts.set_animation_names(node, names);
+ match reads {
+ true => self.keyframes_reading_parent_reset_values.insert(node),
+ false => self.keyframes_reading_parent_reset_values.remove(&node),
+ };
}
/// Keep the custom-property environment an element now holds; a null `data` is none. Only
@@ -1265,7 +1023,6 @@ impl RetainedState {
data: Option<RetainedCustomPropertyData>,
identity: u64,
sampled_over: Option<u64>,
- declares: bool,
) {
let Some(data) = data else {
self.element_custom_property_data.remove(&node);
@@ -1283,29 +1040,30 @@ impl RetainedState {
HeldCustomPropertyEnvironment {
identity,
sampled_over,
- declares,
data,
},
);
}
- /// The custom-property environment an element holds, or null.
- pub(crate) fn element_custom_property_data(&self, node: StyleNodeID) -> *const std::ffi::c_void {
- self.element_custom_property_data
+ /// Whether the animations of a pseudo-element of `node` sampled custom properties.
+ pub(crate) fn pseudo_element_samples_custom_properties(&self, node: StyleNodeID) -> bool {
+ self.pseudo_element_custom_property_data
.get(&node)
- .map_or(std::ptr::null(), |held| held.data.data())
+ .is_some_and(|environments| environments.iter().any(|(_, held)| held.sampled_over.is_some()))
}
/// Keep the custom-property environment one of an element's synthetic pseudo-elements now
/// holds; a null `data` is none.
///
- /// `data`, if any, is the environment named by `identity`.
+ /// `data`, if any, is the environment named by `identity`, and the animation overlay over the
+ /// one `sampled_over` names where that is some.
pub(crate) fn set_pseudo_element_custom_property_data(
&mut self,
node: StyleNodeID,
pseudo: u8,
data: Option<RetainedCustomPropertyData>,
identity: u64,
+ sampled_over: Option<u64>,
) {
// Clearing is the common install, and must not make an entry only to drop it again.
let Some(data) = data else {
@@ -1320,8 +1078,7 @@ impl RetainedState {
};
let held = HeldCustomPropertyEnvironment {
identity,
- sampled_over: None,
- declares: false,
+ sampled_over,
data,
};
let environments = self.pseudo_element_custom_property_data.entry(node).or_default();
@@ -1332,48 +1089,16 @@ impl RetainedState {
}
}
- /// The custom-property environments an element's synthetic pseudo-elements hold, by kind.
- pub(crate) fn pseudo_element_custom_property_environments(
- &self,
- node: StyleNodeID,
- ) -> impl Iterator<Item = (u8, *const std::ffi::c_void)> + '_ {
- self.pseudo_element_custom_property_data
- .get(&node)
- .into_iter()
- .flatten()
- .map(|(kind, environment)| (*kind, environment.data.data()))
- }
-
- /// Record whether the element's style reads its custom-property environment other than through
- /// `var()`: through `if()`, `inherit()`, a custom function or a style container query. A moved
- /// environment computes such an element again rather than handing it the moved one.
- pub fn set_element_recomputes_on_environment_move(&mut self, node: StyleNodeID, recomputes: bool) {
- if recomputes {
- self.environment_move_recompute_nodes.insert(node);
- } else {
- self.environment_move_recompute_nodes.remove(&node);
- }
- }
-
- #[must_use]
- pub fn element_recomputes_on_environment_move(&self, node: StyleNodeID) -> bool {
- self.environment_move_recompute_nodes.contains(&node)
- }
-
- /// Record the element-backed pseudo-element kind an element in its host's shadow tree stands
- /// for, one plus the kind, or zero for none.
- pub fn set_element_associated_pseudo_kind(&mut self, node: StyleNodeID, pseudo_kind_plus_one: u8) {
- self.computed_group_sets
- .set_associated_pseudo_kind(node, pseudo_kind_plus_one);
- self.tree
- .set_backing_pseudo_kind(node, pseudo_kind_plus_one.checked_sub(1).map(u16::from));
- if pseudo_kind_plus_one != 0
- && let Some(host) = self.tree.shadow_host_of(node)
+ /// Note that an element in its host's shadow tree stands for one of the host's element-backed pseudo-elements,
+ /// as its published row says.
+ pub fn note_backing_element(&mut self, node: StyleNodeID) {
+ if let Some(host) = self.projection.written_shadow_host_of(node)
+ && !self
+ .backing_elements
+ .get(&host)
+ .is_some_and(|backing_elements| backing_elements.contains(&node))
{
- let backing_elements = self.backing_elements.entry(host).or_default();
- if !backing_elements.contains(&node) {
- backing_elements.push(node);
- }
+ self.backing_elements.entry(host).or_default().push(node);
}
}
@@ -1386,9 +1111,9 @@ impl RetainedState {
.flatten()
.copied()
.filter(move |&node| {
- self.tree.shadow_host_of(node) == Some(host)
+ self.projection.shadow_host_of(node) == Some(host)
&& self
- .computed_group_sets
+ .projection
.associated_pseudo_kind(node)
.is_some_and(|kind| kinds & 1_u64.checked_shl(u32::from(kind)).unwrap_or(0) != 0)
})
@@ -1408,17 +1133,58 @@ impl RetainedState {
!self.layout_style_snapshots.is_empty()
}
- /// Take the box geometry a completed layout commit gathered, keeping each row's scroll state.
- pub(crate) fn apply_layout_style_snapshot_commit(
+ /// Take the box geometry a completed layout commit gathered, keeping each row's scroll state, and answer the
+ /// containers it resized along an axis their container types query.
+ pub(super) fn take_layout_style_snapshot_rows(
&mut self,
rows: &[crate::layout::style_snapshot::CommittedGeometry],
- ) {
+ ) -> Vec<StyleNodeID> {
+ let mut resized = Vec::new();
for geometry in rows {
let row = self.layout_style_snapshots.entry(geometry.node).or_default();
- row.content_width_raw = geometry.content_width_raw;
- row.content_height_raw = geometry.content_height_raw;
+ // NB: A box the layout tree rebuilt has no earlier size for its commit to compare, and its loss said nothing
+ // of one. The row keeps the size the last box had, so what queried the container is told here, as a
+ // commit tells of a box that stayed.
+ let (width, height) = (row.content_width_raw, row.content_height_raw);
+ let moved = !row.has_committed_box
+ && geometry.has_committed_box
+ && (width != 0 || height != 0)
+ && (width != geometry.content_width_raw || height != geometry.content_height_raw);
+ if geometry.has_committed_box {
+ row.content_width_raw = geometry.content_width_raw;
+ row.content_height_raw = geometry.content_height_raw;
+ }
row.has_committed_box = geometry.has_committed_box;
+ if moved && self.size_container_query_axis_moved(geometry, width, height) {
+ resized.push(geometry.node);
+ }
}
+ resized
+ }
+
+ /// Whether a box moved from `width` and `height` to `geometry` along an axis its element's container type queries.
+ fn size_container_query_axis_moved(
+ &self,
+ geometry: &crate::layout::style_snapshot::CommittedGeometry,
+ width: i32,
+ height: i32,
+ ) -> bool {
+ let Some(payloads) = self
+ .held_style_record(geometry.node)
+ .and_then(|record| self.computed_group_sets.style_record_payloads(record))
+ else {
+ return false;
+ };
+ let view = crate::css::computed_value_views::ComputedValuesView::of(payloads);
+ let size = |width_raw, height_raw| crate::layout::used_values::FfiCssPixelSize {
+ width: crate::css::css_pixels::CssPixels::from_raw(width_raw),
+ height: crate::css::css_pixels::CssPixels::from_raw(height_raw),
+ };
+ crate::layout::commit::content_size_change_affects_container_queries(
+ view,
+ size(width, height),
+ size(geometry.content_width_raw, geometry.content_height_raw),
+ )
}
/// Record the scroll state a scroll-state container's queries read, as the host snapshots it
@@ -1440,107 +1206,82 @@ impl RetainedState {
/// Record the identity of the counter-style registry a tree scope's style scope has now.
pub fn set_counter_style_environment_identity(&mut self, tree_scope: TreeScopeID, identity: u64) {
- self.counter_style_environment_identities.insert(tree_scope, identity);
+ if self.counter_style_environment_identities.get(&tree_scope) != Some(&identity) {
+ self.counter_style_environment_identities.insert(tree_scope, identity);
+ self.note_counter_style_environment_moved();
+ }
}
- /// Record the style record an element holds; zero is none. Only elements that hold one have an
- /// entry. Keep it alive until the host replaces it, even when the engine publishes a newer
- /// assignment. Whether the element is a query container is what that record says.
- pub fn set_held_style_record(&mut self, node: StyleNodeID, style_record: u64) {
- let previous = if style_record == 0 {
- self.held_style_records.remove(&node)
- } else {
- self.held_style_records.insert(node, style_record)
- };
+ /// Record the style record an element holds, or none. Keep it, and its identity, until the host
+ /// replaces it, even when the engine publishes a newer assignment. Whether the element is a query
+ /// container is what that record says.
+ pub(crate) fn set_held_style_record(
+ &mut self,
+ node: StyleNodeID,
+ record: Option<std::sync::Arc<super::pipeline::Record>>,
+ ) {
+ let style_record = record.as_deref().map_or(0, bridge::host_record_identity);
+ let previous = self.held_style_records.set(node, record);
// NB: Font-relative size queries can change even when the container's box keeps the same dimensions.
+ let font_group = crate::css::table_group_builder::group_index::FONT;
let font_inputs_changed = self.size_container_queries.is_queried_container(node)
&& previous.is_some_and(|previous| {
- let Some(previous) = self.computed_group_sets.style_record_payloads(previous) else {
- return false;
- };
- let Some(current) = self.computed_group_sets.style_record_payloads(style_record) else {
- return false;
- };
- let font_group = crate::css::computed_value_types::STYLE_GROUP_INDEX_FONT;
- previous.get(font_group) != current.get(font_group)
+ self.held_style_records.get(node).is_some_and(|current| {
+ previous.payloads[font_group].as_ptr() != current.payloads[font_group].as_ptr()
+ })
});
- if previous != Some(style_record) {
- if style_record != 0 {
- self.computed_group_sets.pin_style_record(style_record);
- }
- if let Some(previous) = previous {
- self.computed_group_sets.unpin_style_record(previous);
- }
- }
self.set_element_container_query_inputs(node, style_record);
if font_inputs_changed {
self.size_container_queries.note_font_input_change(node);
}
// A `rem` the host resolves reads the font of the record it holds for the document element,
// which it can install in the middle of a style update.
- if self.computed_group_sets.adjustment_facts(node) & bridge::element_adjustment_fact::IS_DOCUMENT_ELEMENT != 0 {
+ if self.projection.adjustment_facts(node) & bridge::element_adjustment_fact::IS_DOCUMENT_ELEMENT != 0 {
self.held_root_font_inputs = computed::FinalStyleRecordID::from_raw(style_record)
.and_then(|record| self.root_font_inputs_from_record(record));
}
}
/// Record the style record the pseudo-element of `pseudo_kind` of an element holds; zero is
- /// none. Keep it alive until the host replaces it, as an element's, even when the engine
+ /// none. The host's reference to the record keeps its identity naming it, even when the engine
/// publishes a newer assignment.
pub fn set_held_pseudo_style_record(&mut self, node: StyleNodeID, pseudo_kind: u8, style_record: u64) {
let held = self.held_pseudo_style_records.entry(node).or_default();
let slot = held.iter().position(|&(kind, _)| kind == pseudo_kind);
- let previous = match slot {
- Some(slot) if style_record == 0 => Some(held.swap_remove(slot).1),
- Some(slot) => Some(std::mem::replace(&mut held[slot].1, style_record)),
- None if style_record == 0 => None,
- None => {
- held.push((pseudo_kind, style_record));
- None
+ match slot {
+ Some(slot) if style_record == 0 => {
+ held.swap_remove(slot);
}
- };
+ Some(slot) => held[slot].1 = style_record,
+ None if style_record == 0 => {}
+ None => held.push((pseudo_kind, style_record)),
+ }
if held.is_empty() {
self.held_pseudo_style_records.remove(&node);
}
- if previous == Some(style_record) {
- return;
- }
- if style_record != 0 {
- self.computed_group_sets.pin_style_record(style_record);
- }
- if let Some(previous) = previous {
- self.computed_group_sets.unpin_style_record(previous);
- }
}
- /// Record that a child of an element or shadow root explicitly inherits a non-inherited
- /// property, as the host marks the node. The mark lasts as long as the node's identity.
- pub fn note_children_explicitly_inherit(&mut self, node: StyleNodeID, groups: u32) {
- *self.children_explicitly_inherit_marks.entry(node).or_default() |= groups;
+ /// The record an element is a query container as: the one the engine assigned it last, which
+ /// the host installs, or else the one the host holds.
+ pub(super) fn container_style_record(&self, node: StyleNodeID) -> Option<u64> {
+ self.computed_group_sets
+ .assigned_style_record(node)
+ .map(|record| record.raw())
+ .or_else(|| self.held_style_record(node))
}
- /// Whether, and as what, an element is a query container.
- pub(super) fn container_query_inputs(&self, node: StyleNodeID) -> Option<&tree::ContainerQueryInputRow> {
- self.container_query_inputs.get(node)
+ /// Whether, and as what, an element is a query container, as its record says.
+ pub(super) fn container_query_inputs(&self, node: StyleNodeID) -> Option<tree::ContainerQueryInputs<'_>> {
+ self.container_query_input_row(node, self.container_style_record(node)?, false)
}
- /// Refresh whether, and as what, an element is a query container from a record it is published
- /// with. A record without its box group makes it none, and so does one naming no container
- /// type or name: such an element holds no row.
+ /// Follow whether an element answers size queries as a record it is published with says. A
+ /// record without its box group makes it answer none, and so does one naming no container type.
pub(super) fn set_element_container_query_inputs(&mut self, node: StyleNodeID, style_record: u64) {
- let supports_size_queries = |row: &tree::ContainerQueryInputRow| {
- row.size_queries_available && (row.is_size_container || row.is_inline_size_container)
- };
- let was_available = self.container_query_inputs(node).is_some_and(supports_size_queries);
- let row = self.container_query_input_row(node, style_record, false);
- let is_available = row.as_ref().is_some_and(supports_size_queries);
- match row {
- Some(row) => self.container_query_inputs.set(node, row),
- None => self.container_query_inputs.clear(node),
- }
- if was_available != is_available {
- self.size_container_queries.note_availability_change(node);
- }
+ let is_available = self
+ .container_query_input_row(node, style_record, false)
+ .is_some_and(|row| row.supports_size_queries());
+ self.size_container_queries.set_availability(node, is_available);
}
/// What a record says of its element as a query container: none for a record without its box
@@ -1551,13 +1292,22 @@ impl RetainedState {
node: StyleNodeID,
style_record: u64,
any_element: bool,
- ) -> Option<tree::ContainerQueryInputRow> {
- let payloads = self
- .computed_group_sets
- .style_record_payloads(style_record)
- .filter(|payloads| payloads.len() > crate::css::computed_value_types::STYLE_GROUP_INDEX_BOX)?;
- let values =
- crate::css::computed_value_views::ComputedValuesView::new(SharedPayload::as_pointer_slice(payloads));
+ ) -> Option<tree::ContainerQueryInputs<'_>> {
+ let payloads = self.computed_group_sets.style_record_payloads(style_record)?;
+ self.container_query_input_row_of_payloads(node, payloads, style_record, any_element)
+ }
+
+ /// What a style's groups say of its element as a query container, as
+ /// `container_query_input_row` says for a record, for a style installed as `style_record`, or
+ /// as none yet.
+ pub(super) fn container_query_input_row_of_payloads<'a>(
+ &self,
+ node: StyleNodeID,
+ payloads: &'a crate::css::computed_values::StyleGroups,
+ style_record: u64,
+ any_element: bool,
+ ) -> Option<tree::ContainerQueryInputs<'a>> {
+ let values = crate::css::computed_value_views::ComputedValuesView::of(payloads);
let box_values = values.box_values();
if !any_element
&& !box_values.is_size_container
@@ -1567,17 +1317,7 @@ impl RetainedState {
{
return None;
}
- let names = box_values
- .container_name
- .raws()
- .iter()
- .map(|raw| match unsafe { ak::utf16_string_units(raw) } {
- ak::Utf16StringUnits::Ascii(units) | ak::Utf16StringUnits::Latin1(units) => {
- units.iter().copied().map(u16::from).collect()
- }
- ak::Utf16StringUnits::Utf16(units) => units.to_vec(),
- })
- .collect();
+ let names = box_values.container_name.raws();
use super::bridge::ElementBoxKind;
let display = values.display();
let box_kind = self.element_box_kind(node);
@@ -1617,7 +1357,7 @@ impl RetainedState {
&& !display.is_table_inside()
&& !(display.is_internal() && !display.is_table_caption())
&& !non_atomic_inline;
- Some(tree::ContainerQueryInputRow {
+ Some(tree::ContainerQueryInputs {
style_record,
size_queries_available,
names,
@@ -1636,7 +1376,7 @@ impl RetainedState {
node: StyleNodeID,
slot: animations::AnimationSlot,
names: Box<[crate::css::css_string::CssString]>,
- definitions: &[super::bridge::FfiAppliedAnimationDefinition],
+ definitions: Box<[animations::HeldAppliedAnimationDefinition]>,
) {
self.css_defined_animations.set(node, slot, names, definitions);
}
@@ -1719,20 +1459,6 @@ impl RetainedState {
}
}
- /// Record the custom properties an element declares or references. Also an index rather than an
- /// input, and for the same reason: it answers which elements an `@property` registration reaches.
- pub fn set_element_custom_property_names(
- &mut self,
- node: StyleNodeID,
- names: &[StyleAtomID],
- uses_unnamed: bool,
- uses_custom_functions: bool,
- ) {
- self.facts.set_custom_property_names(node, names);
- self.facts.set_uses_unnamed_custom_properties(node, uses_unnamed);
- self.facts.set_uses_custom_functions(node, uses_custom_functions);
- }
-
pub fn set_tree_scope_root(&mut self, tree_scope: TreeScopeID, root: StyleNodeID) {
if tree_scope == TreeScopeID::DOCUMENT {
return;
@@ -1745,171 +1471,17 @@ impl RetainedState {
}
self.scope_roots.insert(index, Some(root));
self.scope_by_root.insert(root, tree_scope);
- // The root is a node selectors reach and nothing publishes features for, so this is where it
- // gets a row of its own.
- self.facts.ensure_row(root);
+ // NB: The root is a node selectors reach and nothing publishes features for, so the host gives it a row of its
+ // own as it names it.
+ #[cfg(test)]
+ self.write_projection_for_test(|writes| writes.projection.ensure_facts(root));
}
pub(super) fn scope_root(&self, tree_scope: TreeScopeID) -> Option<StyleNodeID> {
self.scope_roots.get(tree_scope.0 as usize).copied().flatten()
}
- /// Everything a sheet attached to these scopes can decide.
- ///
- /// A scope-local sheet reaches the tree it is attached to, and out of it only through `:host`,
- /// `::slotted()` and `::part()` - which reach the host and the nodes slotted into it. So a sheet
- /// in a shadow root can be bounded even when its rules dispatch on nothing enumerable, where the
- /// document's own scope has no bound narrower than the document.
- /// Where a sheet decides, taking in both the scopes it is attached to now and the ones it was
- /// attached to when the transaction began.
- pub(super) fn scopes_of_sheet(
- &self,
- sheet: SheetID,
- departed_sheet_scopes: &[(SheetID, TreeScopeID)],
- ) -> Vec<TreeScopeID> {
- let mut scopes = self.program.sheet_scopes(sheet);
- for &(departed_sheet, scope) in departed_sheet_scopes {
- if departed_sheet == sheet && !scopes.contains(&scope) {
- scopes.push(scope);
- }
- }
- scopes
- }
-
- pub(super) fn regions_reachable_from_scopes(
- &self,
- scopes: &[TreeScopeID],
- subject_leaves_scope: bool,
- host_is_a_subject: bool,
- ) -> Option<Vec<ImpactRegion>> {
- if scopes.is_empty() {
- return None;
- }
- let mut regions = Vec::new();
- for &scope in scopes {
- let root = match self.scope_root(scope) {
- Some(root) => root,
- // The document's own scope records no root and has no bound narrower than itself,
- // which is a different thing from a shadow scope that has not named one yet.
- None if scope == TreeScopeID::DOCUMENT => return None,
- // A shadow scope whose root has never been named holds no element the engine knows
- // about: every element in a shadow tree takes its place in the style tree through
- // that root, so a scope that has not named one has nothing inside it for a sheet
- // attached there to decide. Attaching a sheet to a shadow root numbers its scope
- // without populating it, which is what `attachShadow` immediately followed by
- // `adoptedStyleSheets` does, and answering that with the document restyles the page
- // once per component.
- //
- // A program that leaves its scope reaches the host instead, so it needs the root to
- // find one, and a scope with no root names no host either.
- None if !subject_leaves_scope => continue,
- None => continue,
- };
- match subject_leaves_scope {
- // `:host` and `::slotted()` describe the host and what is slotted into it, which are
- // in the host's own tree and not in the one the sheet is attached to. A rule using
- // them says nothing about the shadow tree, so naming it would be the widest part of
- // the answer for the narrowest reason.
- // A root with no host is a shadow tree whose host has not taken its place in the
- // style tree, so the tree hangs off nothing the engine can reach and the rule
- // decides for no element that exists. The host computes its style from scratch when
- // it does arrive, which is what makes saying so safe rather than optimistic.
- true => match self.tree.host_of(root) {
- Some(host) => {
- if host_is_a_subject {
- regions.push(ImpactRegion::Node(host));
- }
- regions.push(ImpactRegion::StrictSubtree(host));
- }
- None => continue,
- },
- false => regions.push(ImpactRegion::Subtree(root)),
- }
- }
- Some(regions)
- }
-
- /// Everything a named rule in these scopes can reach through its consumers.
- ///
- /// Unlike a selector program, a named rule has no one subject position: an `@keyframes` or
- /// `@property` rule can be referenced both inside its shadow tree and by a declaration matching
- /// `:host` or `::slotted()`. The consumer index identifies the exact nodes when it is complete;
- /// these regions bound that index, and are also the conservative answer when it is not.
- pub(super) fn regions_reachable_for_named_consumers(&self, scopes: &[TreeScopeID]) -> Option<Vec<ImpactRegion>> {
- let mut regions = self.regions_reachable_from_scopes(scopes, false, false)?;
- let outside_regions = self.regions_reachable_from_scopes(scopes, true, true)?;
- regions.extend(outside_regions);
- Some(regions)
- }
-
- /// Where an entry with no dispatch key can have subjects, when its own shape still says.
- ///
- /// Three things narrow an entry the dispatch buckets gave up on. `:root` matches the document's
- /// root element and nothing else, whatever else its compound tests. A child combinator names
- /// what the subject's parent must be, which does have postings to enumerate - one lookup per
- /// parent candidate reaches every subject the entry can have, where the alternative is every
- /// element in the document. And a descendant combinator says the same thing more weakly: the
- /// subject is somewhere under a named ancestor rather than directly beneath a named parent.
- ///
- /// A relative query the subject has to satisfy is the fourth: `:has(.error)` names no feature of
- /// its own, but it can only match an anchor of that query, and the witness compound does have a
- /// posting to enumerate.
- ///
- /// `None` means the entry says nothing, and the caller falls back to the scope. Every answer here
- /// is a superset of the true subject set, which is what a plan is allowed to be.
- pub(super) fn regions_from_subject_position(
- &self,
- compiled: &SelectorProgram,
- entry: usize,
- document_root: StyleNodeID,
- bounding_scopes: Option<&[TreeScopeID]>,
- ) -> Option<Vec<ImpactRegion>> {
- if compiled.subject_is_only_the_root(entry) {
- return Some(vec![ImpactRegion::Node(document_root)]);
- }
-
- // The sets below are disjunctions: the constrained relative is reachable by at least one of
- // the keys, so the union over all of them covers it. An empty set is no constraint at all.
- //
- // A parent is the tightest, so it is asked for first; an ancestor is consulted when there is
- // no child combinator, and a relative query only when the subject's own position says nothing.
- let (keys, region): (_, fn(StyleNodeID) -> ImpactRegion) = match compiled.subject_parent_dispatch(entry) {
- keys if !keys.is_empty() => (keys, ImpactRegion::Children),
- _ => match compiled.subject_ancestor_dispatch(entry) {
- keys if !keys.is_empty() => (keys, ImpactRegion::StrictSubtree),
- _ => match compiled.subject_relative_anchor(entry) {
- Some((axis, keys)) if !keys.is_empty() => (keys, anchor_region_for(axis)?),
- _ => return None,
- },
- },
- };
- if keys.is_empty() {
- return None;
- }
- let mut regions = Vec::new();
- for key in keys {
- if !key.has_selector_posting() {
- return None;
- }
- match self.facts.postings().lookup(key) {
- Lookup::Known(posting) => {
- for relative in posting.candidates() {
- if bounding_scopes
- .is_some_and(|scopes| scopes.binary_search(&self.tree.tree_scope(relative)).is_err())
- {
- continue;
- }
- regions.push(region(relative));
- }
- }
- Lookup::KnownAbsent => {}
- Lookup::Missing(_) => return None,
- }
- }
- Some(regions)
- }
-
- /// Record that a rule sits in a cascade layer.
+ /// Record that a rule sits in a cascade layer.
///
/// Said as the rule is compiled rather than as an input: which layer a rule is in is part of what
/// the rule is, and a rule that moves between layers is recompiled.
@@ -1921,157 +1493,85 @@ impl RetainedState {
&mut self,
node: StyleNodeID,
kind: ElementDeclarationKind,
- declarations: Vec<(DeclaredProperty, RetainedStyleValueData)>,
+ declarations: Vec<(DeclarationEntry, RetainedStyleValueData)>,
custom_declarations: Vec<(CustomDeclaration, RetainedStyleValueData)>,
) {
debug_assert!(custom_declarations.is_empty() || kind == ElementDeclarationKind::InlineStyle);
- if matches!(
- kind,
- ElementDeclarationKind::PresentationalHint | ElementDeclarationKind::SvgPresentationAttribute
- ) {
- verify_cascade_winners(self, |_| {
- let mut properties: Vec<u16> = declarations.iter().map(|(declared, _)| declared.property).collect();
- properties.sort_unstable();
- assert!(
- properties.windows(2).all(|pair| pair[0] != pair[1]),
- "element-attached declarations repeat a property"
- );
- });
- }
- let current_declared = self.facts.element_declared_properties(node, kind);
- let current_custom_declarations = match kind {
- ElementDeclarationKind::InlineStyle => self.facts.element_custom_declarations(node),
- _ => &[],
+ let current = self.element_declarations.declarations(node, kind).unwrap_or_default();
+ let current_custom = match kind {
+ ElementDeclarationKind::InlineStyle => self.element_declarations.custom(node),
+ _ => None,
};
- if current_declared
+ let current_custom_declarations = current_custom.map_or(&[][..], |custom| custom.declared());
+ let current_custom_values = current_custom.map_or(&[][..], |custom| custom.written_values());
+ if current
.iter()
- .eq(declarations.iter().map(|(declared, _)| declared))
+ .eq(declarations.iter().map(|(declared, written)| (declared, written)))
&& current_custom_declarations
.iter()
- .eq(custom_declarations.iter().map(|(declared, _)| declared))
+ .zip(current_custom_values)
+ .eq(custom_declarations
+ .iter()
+ .map(|(declared, written)| (declared, written)))
{
return;
}
- // Custom properties never reach the winner columns, so winners repaired from the
- // declarations alone hold only for an element whose style declared none.
- let repair_inputs = current_custom_declarations
- .is_empty()
- .then(|| {
- let previous = self
- .current_winner_groups()
- .token_for(WinnerGroupKey::current(node, self.program.version()))
- .sparse()
- .ok()
- .map(|(_, state)| state)?;
- let retained = self.current_answer_identity(node)?;
- self.match_answers.answer(retained)?;
- Some((previous, retained, current_declared.to_vec()))
+ // An element's declarations are its own allocations, but every value equal to one also has
+ // a canonical one, which elements declaring the same text then share, and the caches over
+ // computed values see as the same value. A value taking part in a substitution keeps its
+ // own: the longhands a shorthand awaiting substitution expands to name it by identity.
+ let declarations = declarations
+ .into_iter()
+ .map(|(declared, written)| {
+ use crate::css::style_value::StyleValueData;
+ let takes_part_in_substitution = matches!(
+ written.optional_data(),
+ Some(
+ StyleValueData::Unresolved { .. }
+ | StyleValueData::PendingSubstitution { .. }
+ | StyleValueData::Shorthand { .. }
+ )
+ );
+ if takes_part_in_substitution || written.optional_data().is_none() {
+ return (declared, written);
+ }
+ (declared, self.canonical_value(&written.into_arc()))
})
- .flatten();
- self.facts.set_element_declared_properties(node, kind, declarations);
- if kind == ElementDeclarationKind::InlineStyle {
- self.facts.set_element_custom_declarations(node, custom_declarations);
- }
- let Some((previous, retained, previous_declared)) = repair_inputs else {
- return;
- };
- let declared = self.facts.element_declared_properties(node, kind);
- let mut changed_properties: Vec<u16> = previous_declared
- .iter()
- .chain(declared)
- .map(|declared| declared.property)
.collect();
- changed_properties.sort_unstable();
- changed_properties.dedup();
- changed_properties.retain(|&property| {
- previous_declared.iter().find(|declared| declared.property == property)
- != declared.iter().find(|declared| declared.property == property)
- });
- if !changed_properties.is_empty() {
- self.apply_element_declaration_winner_updates(node, previous, retained, &changed_properties);
- }
- }
-
- /// Repair the exact properties whose element-attached declaration inventory changed.
- ///
- /// Presentational hints are published while the legacy cascade builds its input, after the
- /// transaction has already reused the selector answer. Re-reducing only their changed
- /// properties here keeps the retained top-1 relation current without matching the element.
- pub(super) fn apply_element_declaration_winner_updates(
- &mut self,
- node: StyleNodeID,
- previous: CascadeStateID,
- retained: MatchAnswerID,
- properties: &[u16],
- ) {
- let Some(retained) = self.match_answers.answer(retained) else {
- return;
- };
- let matches = retained
- .iter()
- .copied()
- .filter(|entry| {
- !self.program.declarations_are_complete_for(entry.rule)
- || self
- .program
- .declared_properties_of(entry.rule)
- .iter()
- .any(|declared| properties.binary_search(&declared.property).is_ok())
- })
- .map(|entry| entry.materialize(node, &self.programs, 0))
- .collect::<Option<Vec<_>>>();
- let Some(matches) = matches else {
- return;
- };
- self.counters
- .add(Counter::ElementDeclarationRepairMatches, matches.len() as u64);
- let Some(updates) = self.exact_cascade_winner_updates_for_properties(node, &matches, None, properties) else {
- return;
- };
- let (state, _) =
- self.with_cascade_interning_counters(|groups| groups.apply_property_updates(previous, &updates));
- let published = if let Some(traversal) = self.batch_matching_traversal.as_mut() {
- traversal
- .answer_effects
- .winners
- .set(&mut self.winner_groups, node, state, self.program.version())
- } else {
- let mut effects = super::cascade::WinnerEffects::default();
- let published = effects.set(&mut self.winner_groups, node, state, self.program.version());
- self.install_winner_effects(effects);
- published
- };
-
- if published {
- self.counters.bump(Counter::CascadeNodeHandlesPublished);
+ self.element_declarations.set(node, kind, declarations);
+ if kind == ElementDeclarationKind::InlineStyle {
+ self.element_declarations.set_custom(node, custom_declarations);
}
}
}
impl StyleEngine {
+ /// Have the engine share the style data and atoms of the process, as a document's does, which the selectors it
+ /// matches name their names by.
+ #[cfg(test)]
+ pub(super) fn share_the_process_style_for_test(&mut self) {
+ let process = Arc::clone(crate::render_state::process_style());
+ self.retained.atoms = crate::fork::ForkShared::new(DocumentAtoms::for_process_engine(process.atoms()));
+ self.retained.process_style = process;
+ }
+
#[must_use]
pub(crate) fn new() -> Self {
- let tree = StyleNodeTree::new();
+ let tree = HostTree::new();
+ let process_style = Arc::<super::ProcessStyle>::default();
Self {
retained: RetainedState {
counters: Counters::new(),
- deferred_pseudo_elements: 0,
+ highlight_observers: Default::default(),
tree: crate::fork::ForkShared::new(tree),
- program: crate::fork::ForkShared::new(StyleSheetProgram::new()),
- native_rules: Default::default(),
+ deepest_element: Arc::default(),
+ rules: crate::fork::ForkShared::new(RuleStore::new()),
+ process_style: Arc::clone(&process_style),
declaration_block_version: Arc::new(std::sync::atomic::AtomicU32::new(1)),
- last_transaction_only_derived_child_reactions: false,
- sheets_excluded_from_routing: BitColumn::default(),
- sheets_kept_for_reattachment: BitColumn::default(),
- routing_needs_detachment_sweep: false,
- match_workspace: MatchScratch::default(),
- exact_covered_scratch: Vec::new(),
- cascade_compaction_scratch: ordering::CascadeCompactionWorkspace::default(),
-
- next_style_transaction_version: StyleTransactionVersion(1),
+
+ next_style_update_version: StyleUpdateVersion(1),
document_style_computation_inputs: Default::default(),
- driven_viewport: (0.0, 0.0),
document_resource_contexts: Default::default(),
document_media: Default::default(),
document_functions: Default::default(),
@@ -2086,38 +1586,21 @@ impl StyleEngine {
),
),
font_resolution: None,
- layer_topology_version: 0,
- sheet_order_version: 0,
- specified_values: crate::fork::ForkShared::new(SpecifiedValues::new()),
- winner_groups: crate::fork::ForkShared::new(WinnerGroups::new()),
+ canonical_values: crate::fork::ForkShared::new(CanonicalValues::default()),
computed_group_sets: Default::default(),
style_record_view_epoch_depth: 0,
custom_property_environments: Default::default(),
- nodes_with_substituted_records: HashSet::default(),
- custom_declaration_reads: HashMap::default(),
- custom_property_environments_by_answer: HashMap::default(),
- last_custom_property_environment_memoizable: false,
- custom_declaration_custom_property_reads: HashMap::default(),
- custom_property_reads_by_declarations: Default::default(),
- nodes_with_tree_counting_records: HashMap::default(),
- nodes_with_rolled_back_records: HashMap::default(),
- nodes_with_element_relative_substitutions: HashMap::default(),
element_custom_property_data: Default::default(),
pseudo_element_custom_property_data: Default::default(),
- environment_move_recompute_nodes: HashSet::default(),
+ keyframes_reading_parent_reset_values: Default::default(),
container_effects_for_host: Default::default(),
- published_container_verdicts: HashMap::default(),
- container_gates_unheld: HashSet::default(),
- row_inputs_moved: flush::RowInputsMoved::default(),
- container_query_inputs: Default::default(),
layout_style_snapshots: HashMap::default(),
size_container_queries: Default::default(),
- counter_style_environment_identities: HashMap::default(),
+ counter_style_environment_identities: Default::default(),
held_style_records: Default::default(),
held_pseudo_style_records: Default::default(),
tick_shown: Default::default(),
- backing_elements: HashMap::default(),
- children_explicitly_inherit_marks: HashMap::default(),
+ backing_elements: Default::default(),
css_defined_animations: Default::default(),
animation_keyframes: Default::default(),
position_try_rules: Default::default(),
@@ -2125,83 +1608,42 @@ impl StyleEngine {
hover: Default::default(),
held_root_font_inputs: None,
random_base_values: Default::default(),
- replaced_content_inputs: HashMap::default(),
+ replaced_content_inputs: Default::default(),
transition_baselines: Default::default(),
custom_property_registrations_changed: false,
- engine_computed_records_pending: HashMap::default(),
- demand_records: HashMap::default(),
- flush_stamp: 0,
- engine_pseudo_record_cache: HashMap::default(),
- batch_answers_complete_but_for_custom_properties: HashMap::default(),
- batch_custom_property_matches: HashMap::default(),
- batch_custom_property_answers: HashMap::default(),
- batch_backing_pseudo_matches: HashMap::default(),
- shadow_host_backing_pseudo_matches: HashMap::default(),
- engine_cold_record_cache: Default::default(),
- engine_cold_record_donors: Default::default(),
-
- style_invalidation_cache: HashMap::default(),
+ demand_records: Default::default(),
+
html_element_namespace: StyleAtomID::NONE,
- match_answers: Default::default(),
- selector_truth_sets: SelectorTruthSetCatalog::default(),
- retained_match_answers: Default::default(),
- retained_selector_incidences: RetainedSelectorIncidences::default(),
- selector_incidence_is_current: false,
- batch_matching_traversal: None,
- route_pruning_states: crate::fork::ForkReset::new(Mutex::new(RoutePruningStateCache::default())),
sibling_positions: crate::fork::ForkReset::default(),
- prefix_caches: std::sync::Arc::default(),
- #[cfg(test)]
- force_bounded_prefix_completion: false,
- prepared_batch_matching_traversal: None,
- published_match_answers: PublishedMatchAnswers::default(),
- transaction_fact_view: None,
- facts: crate::fork::ForkShared::new(ElementFactStore::new()),
- programs: SelectorPrograms::for_live_engine(),
+ cold_pass_report: [0; pipeline::ReportField::COUNT],
+ live_style: None,
+ live_style_may_start: crate::fork::ForkReset::original(),
+ cold_passes: std::sync::Arc::default(),
+ live_counters: Default::default(),
+ style_pool: None,
+ substituted_font_values: std::sync::Arc::default(),
+ element_declarations: Default::default(),
+ projection: Default::default(),
attribute_value_text_names: Arc::default(),
tested_attribute_names: Arc::default(),
attribute_value_text_requirements_version: 0,
+ selectors_test_local_link: false,
relational_arrival_keys: Arc::default(),
unresolved_relational_arrival_keys: HashSet::default(),
relational_arrival_keys_version: 0,
- selector_programs_need_sweep: false,
- routing: Arc::new(RoutingRegistry::new()),
- deferred_user_agent_routes: None,
- selector_truth_changes: SelectorTruthChanges::default(),
- already_planned_selector_truth: DeltaBatch::default(),
- selector_truth_changes_active: false,
- relational_witnesses: RelationalWitnesses::default(),
- pending_witness_effects: Vec::new(),
-
- scope_roots: Column::default(),
+
+ scope_roots: Default::default(),
scope_by_root: Default::default(),
- scope_programs: intern_table::InternTable::default(),
- vacant_scope_programs: Vec::new(),
- scope_dispatch_templates: HashMap::default(),
- scope_cascade_templates: HashMap::default(),
- ancestor_dispatch_templates: Default::default(),
- retired_scope_templates: Vec::new(),
- scope_templates_need_sweep: false,
- scope_program_by_scope: Column::default(),
- atoms: crate::fork::ForkShared::new(DocumentAtoms::for_live_engine()),
+ atoms: crate::fork::ForkShared::new(DocumentAtoms::for_live_engine(process_style.atoms())),
fold_id_and_class_name_case: false,
- #[cfg(test)]
- diagnostic_plan_capture: None,
},
host: HostState {
- suspended_style_pass: None,
+ hover_seal: Default::default(),
font_resolver: None,
- journal: NormalizationJournal::new(),
- deferred_geometry_journal: NormalizationJournal::new(),
- flushing_deferred_geometry_journal: false,
+ element_inputs: PendingElementInputs::default(),
deferred_element_style_inputs: Default::default(),
deferred_element_style_inputs_moved: false,
deferred_element_style_inputs_are_pending: false,
- environment_move_changed_names: Default::default(),
-
- initial_tree_batch_applied: false,
- initial_tree_bulk_load_is_pending: false,
- tree_staging: TreeRelationStaging::default(),
program_staging: ProgramStaging::default(),
sheet_occurrences: HashMap::default(),
@@ -2209,89 +1651,56 @@ impl StyleEngine {
sheet_rule_replacement: None,
reclaimed_style_atoms: Vec::new(),
defers_atom_sweep: false,
+ reinherited_records: None,
+ released_style_nodes: Vec::new(),
},
}
}
- /// Record a change to style inputs which are properties of the document environment rather
- /// than of an element or stylesheet rule.
- pub fn record_environment_change(&mut self) {
- self.discard_prepared_batch_matching_traversal();
- self.host
- .journal
- .record_complete_scope_action(InputKind::Environment, &self.retained.counters);
- }
-
- /// Whether the first tree batch can be installed directly.
- pub(crate) fn can_bulk_load_initial_tree(&self) -> bool {
- !self.host.initial_tree_batch_applied
- }
-
- /// Install a first batch of unique element arrivals without journalling one structural input
- /// per row. The document root is the transaction envelope, so planning will still choose the
- /// same exact whole-document result at first observation.
- pub(crate) fn bulk_load_initial_tree(
- &mut self,
- document_root: StyleNodeID,
- arrivals: &[(StyleNodeID, TreeRelations)],
- ) {
- debug_assert!(!self.host.initial_tree_batch_applied);
- debug_assert!(!arrivals.is_empty());
- debug_assert!(arrivals.iter().any(|&(node, _)| node == document_root));
+ /// The `StyleEnvironmentChange` bit of a change that can move how any element computes,
+ /// restyling every element: the quirks mode moving, which only the parser and `document.open()`
+ /// do, before the document holds an element.
+ const ENVIRONMENT_CHANGE_EVERYTHING: u8 = 1 << 7;
- for &(node, relations) in arrivals {
- self.link(node, relations);
+ /// Record a change to style inputs which are properties of the document environment rather
+ /// than of an element or stylesheet rule: the parts `changes` names as `StyleEnvironmentChange`
+ /// bits, which restyle the elements reading them, or every element where it names everything.
+ pub fn record_environment_change(&mut self, changes: u8) {
+ self.retained.counters.bump(Counter::RawMutationRecords);
+ self.retained.counters.bump(Counter::EnvironmentDeltas);
+ if changes & Self::ENVIRONMENT_CHANGE_EVERYTHING != 0 {
+ self.host.element_inputs.restyle_everything();
}
- self.update_journal_entry_limit();
-
- let root_relations = arrivals
- .iter()
- .find_map(|&(node, relations)| (node == document_root).then_some(relations))
- .unwrap();
- let recorded = self.record(
- InputKey::TreeRelations(document_root),
- InputValue::TreeRelations(None),
- InputValue::TreeRelations(Some(root_relations)),
- );
- debug_assert!(recorded);
-
- let folded_rows = arrivals.len() - 1;
- self.retained
- .counters
- .add(Counter::RawMutationRecords, folded_rows as u64);
- self.retained.counters.add(Counter::TreeDeltas, folded_rows as u64);
- self.retained.counters.bump(Counter::InitialBulkLoads);
- self.retained
- .counters
- .add(Counter::InitialBulkTreeRows, arrivals.len() as u64);
- self.host.initial_tree_batch_applied = true;
- self.host.initial_tree_bulk_load_is_pending = true;
+ self.host
+ .element_inputs
+ .note_environment_moved(super::input_types::StyleEnvironment::from_bits(changes));
}
#[must_use]
pub fn has_pending_transaction(&self) -> bool {
(self.host.deferred_element_style_inputs_are_pending && !self.host.deferred_element_style_inputs.is_empty())
- || !self.host.journal.is_empty()
- || (!self.host.flushing_deferred_geometry_journal && !self.host.deferred_geometry_journal.is_empty())
- || !self.host.tree_staging.is_empty()
+ || !self.host.element_inputs.is_empty()
+ || self.retained.projection.has_pending_changes()
+ || self.retained.projection.has_sealed_changes()
+ || self.retained.projection.has_written_links()
|| self.host.program_staging.is_dirty()
|| self.host.sheet_rule_replacement.is_some()
- || self.host.suspended_style_pass.is_some()
- }
-
- /// Whether the host is installing a style pass wave by wave, between two of its waves.
- #[must_use]
- pub fn has_suspended_style_pass(&self) -> bool {
- self.host.suspended_style_pass.is_some()
+ // The engine restyles what moved under it other than through an input, such as
+ // the children of an element whose animations' composition moved.
+ || self
+ .retained
+ .live_style
+ .as_ref()
+ .is_some_and(|live| live.has_pending())
}
#[must_use]
pub fn has_deferred_geometry_transaction(&self) -> bool {
- !self.host.flushing_deferred_geometry_journal && !self.host.deferred_geometry_journal.is_empty()
+ self.retained.projection.has_sealed_changes()
}
/// Whether any element style input is still deferred, waiting for the first transaction with a
- /// document root. A rootless flush drains the journal but preserves these — so an engine that
+ /// document root. A rootless flush drains the pending inputs but preserves these, so an engine that
/// reports no pending transaction can still owe an element its recomputation.
#[must_use]
pub fn has_deferred_element_style_inputs(&self) -> bool {
@@ -2303,10 +1712,9 @@ impl StyleEngine {
/// can, deciding the node's gated rules again and publishing its winners anew from its
/// retained answer where a verdict moved.
pub fn record_container_query_input(&mut self, node: StyleNodeID) {
- self.retained.row_inputs_moved.note_containers_moved(node);
self.record_derived_element_style_input(
node,
- transaction::STYLE_REACTION_PUBLISHED_STYLE | transaction::STYLE_REACTION_RECOMPUTE_STYLE,
+ input_types::STYLE_REACTION_PUBLISHED_STYLE | input_types::STYLE_REACTION_RECOMPUTE_STYLE,
0,
);
}
@@ -2322,9 +1730,10 @@ impl StyleEngine {
family_name_units: &[u16],
font_lists: &[u64],
) {
- use crate::css::computed_value_types::{FontValues, STYLE_GROUP_INDEX_FONT};
+ use crate::css::computed_value_types::FontValues;
use crate::css::custom_properties::Utf16SliceExt;
use crate::css::style_value::StyleValueData;
+ use crate::css::table_group_builder::group_index;
let families = || {
family_name_lengths.iter().scan(0, |offset, &length| {
@@ -2351,9 +1760,7 @@ impl StyleEngine {
let Some(payloads) = self.computed_group_sets.style_record_payloads(style_record) else {
return false;
};
- let font =
- crate::css::computed_value_views::ComputedValuesView::new(SharedPayload::as_pointer_slice(payloads))
- .font();
+ let font = crate::css::computed_value_views::ComputedValuesView::of(payloads).font();
*answers.entry(std::ptr::from_ref(font)).or_insert_with(|| {
font_lists.contains(&(font.font_cascade_list.as_raw() as u64)) || names_changed_family(font)
})
@@ -2361,7 +1768,7 @@ impl StyleEngine {
let users: Vec<StyleNodeID> = self
.held_style_records
.iter()
- .map(|(&node, &style_record)| (node, style_record))
+ .map(|(node, record)| (node, bridge::host_record_identity(record)))
.chain(
self.computed_group_sets
.pseudo_style_records()
@@ -2369,21 +1776,189 @@ impl StyleEngine {
)
.filter_map(|(node, style_record)| uses_changed_font(style_record).then_some(node))
.collect();
- // An element and its pseudo-elements may both be users: what it owes merges.
+ // An element and its pseudo-elements may both be users: what it owes merges. A font input
+ // asks for no rematch, which a reaction merged with it may still ask for.
for node in users {
self.record_derived_element_style_input(
node,
- transaction::STYLE_REACTION_PUBLISHED_STYLE
- | transaction::STYLE_REACTION_RECOMPUTE_STYLE
- | transaction::STYLE_REACTION_FONT_INPUTS_CHANGED,
- 1 << STYLE_GROUP_INDEX_FONT,
+ input_types::STYLE_REACTION_PUBLISHED_STYLE | input_types::STYLE_REACTION_FONT_INPUTS_CHANGED,
+ 1 << group_index::FONT,
);
}
}
+ /// Fill the faces that loaded into the frozen cascades that waited on them, which keep their
+ /// identities, as a font fallback list resolves a loaded face in place: a style naming a filled
+ /// cascade stays as it is, and what renders its text reads the loaded face through it. Only the
+ /// styles whose values derive from the metrics of a filled cascade's first available font,
+ /// their own or their parent's, are computed again; so is the document element's, where its
+ /// cascade is filled, as the root font the elements reading it resolve against moves with it.
+ /// The elements whose container conditions were evaluated against a container whose cascade
+ /// is filled decide their rules again, as the lengths of a query resolve against the
+ /// container's font.
+ pub(crate) fn fill_loaded_font_faces(&mut self, fills: super::boundary::LoadedFontFaceFills) {
+ use crate::css::table_group_builder::group_index;
+
+ for fill in fills.fills {
+ fill.apply();
+ }
+ let font_lists: HashSet<u64> = fills.font_lists.iter().copied().collect();
+ let sets = &self.computed_group_sets;
+ let uses_filled_font = |style_record: u64| {
+ sets.style_record_payloads(style_record).is_some_and(|payloads| {
+ let font = crate::css::computed_value_views::ComputedValuesView::of(payloads).font();
+ font_lists.contains(&(font.font_cascade_list.as_raw() as u64))
+ })
+ };
+ let element_uses_filled_font = |node: StyleNodeID| {
+ self.held_style_record(node).is_some_and(uses_filled_font)
+ || sets
+ .assigned_pseudo_kinds(node)
+ .filter_map(|kind| sets.pseudo_style_record(node, kind))
+ .any(|style_record| uses_filled_font(style_record.raw()))
+ };
+ let live = self.retained.live_style.as_deref();
+ let projection = &self.retained.projection;
+ let mut restyled = Vec::new();
+ let mut requeried = Vec::new();
+ for (node, _) in self.held_style_records.iter() {
+ let facts = self.projection.adjustment_facts(node);
+ let is_document_element = facts & super::bridge::element_adjustment_fact::IS_DOCUMENT_ELEMENT != 0;
+ // NB: The line-height of a single-line input settles against the metrics of its first available font.
+ let settles_line_height = facts & super::bridge::element_adjustment_fact::CHECK_INPUT_LINE_HEIGHT != 0;
+ let reads_font_metrics = live.is_none_or(|live| live.reads_font_metrics(node));
+ if (is_document_element || settles_line_height || reads_font_metrics)
+ && (element_uses_filled_font(node)
+ || (reads_font_metrics
+ && projection
+ .inheritance_parent(node)
+ .is_some_and(element_uses_filled_font)))
+ {
+ restyled.push(node);
+ }
+ if live.is_some_and(|live| {
+ live.font_metric_query_containers(node)
+ .iter()
+ .any(|&container| element_uses_filled_font(container))
+ }) {
+ requeried.push(node);
+ }
+ }
+ for node in restyled {
+ self.record_derived_element_style_input(
+ node,
+ input_types::STYLE_REACTION_PUBLISHED_STYLE | input_types::STYLE_REACTION_FONT_INPUTS_CHANGED,
+ 1 << group_index::FONT,
+ );
+ }
+ for node in requeried {
+ self.record_container_query_input(node);
+ }
+ }
+
/// Record a style reaction for one element, which the engine derived itself or C++ derived
/// from what it saw move, merged with what the element already owes. It joins the next
/// transaction, and the engine settles it where it can.
+ #[cfg(test)]
+ pub fn set_shadow_root(&mut self, host: StyleNodeID, shadow_root: StyleNodeID) {
+ let attached = self
+ .retained
+ .write_projection_for_test(|writes| writes.set_shadow_root(host, shadow_root));
+ self.note_shadow_root(host, attached);
+ }
+
+ /// Write the element facts the style computation's adjustments read, as the host does, and publish them.
+ #[cfg(test)]
+ pub fn set_element_adjustment_facts(&mut self, node: StyleNodeID, facts: u32) {
+ let moved = self
+ .retained
+ .write_projection_for_test(|writes| writes.set_element_adjustment_facts(node, facts));
+ if moved & super::bridge::element_adjustment_fact::RENDERED_IN_TOP_LAYER != 0 {
+ self.note_top_layer_move(node);
+ }
+ }
+
+ /// Write the element facts a layout row built for the element records, as the host does, and publish them.
+ #[cfg(test)]
+ pub fn set_element_construction_facts(&mut self, node: StyleNodeID, facts: u32) {
+ self.retained
+ .write_projection_for_test(|writes| writes.set_element_construction_facts(node, facts));
+ }
+
+ /// Write which principal box the element asks for, as the host does, and publish it.
+ #[cfg(test)]
+ pub fn set_element_box_kind(&mut self, node: StyleNodeID, box_kind: super::bridge::ElementBoxKind) {
+ if self
+ .retained
+ .write_projection_for_test(|writes| writes.set_element_box_kind(node, box_kind))
+ {
+ self.note_box_kind_change(node);
+ }
+ }
+
+ /// The element moved into or out of the top layer, as its published host facts say.
+ pub(crate) fn note_top_layer_move(&mut self, node: StyleNodeID) {
+ self.record_derived_element_style_input(
+ node,
+ super::input_types::STYLE_REACTION_PUBLISHED_STYLE | super::input_types::STYLE_REACTION_RECOMPUTE_STYLE,
+ 0,
+ );
+ self.set_hover(self.hover_target());
+ }
+
+ /// Take what the host published of its elements at a barrier: its projection rows, the elements it published
+ /// standing for a pseudo-element of their shadow host, and the declaration blocks it published them to hold. The
+ /// hover's chain follows the tree where the tree moved under it.
+ pub(in crate::css::style) fn adopt_host_publication(
+ &mut self,
+ projection: super::pipeline::projection::ProjectionPublication,
+ backing_elements: &[StyleNodeID],
+ declarations: &[super::bridge::FfiElementDeclarationDelta],
+ ) {
+ let moves_links = projection.moves_links();
+ for (counter, count) in self.retained.projection.adopt(projection) {
+ self.retained.counters.add(counter, count);
+ }
+ for &node in backing_elements {
+ self.retained.note_backing_element(node);
+ }
+ self.record_element_declaration_deltas(declarations);
+ if moves_links {
+ self.set_hover(self.hover_target());
+ }
+ }
+
+ /// Note that the host wrote `host`'s shadow root, which it did not have before where `attached`.
+ pub(crate) fn note_shadow_root(&mut self, host: StyleNodeID, attached: bool) {
+ self.retained.tree.note_element_links_moved();
+ // A host's shadow root decides which `:host` rules it matches and the elements that
+ // inherit from it, which the engine restyles the host and its flat tree descendants
+ // for.
+ if attached && self.retained.live_style.is_some() && self.retained.tree.is_live(host) {
+ self.record_derived_element_style_input(
+ host,
+ input_types::STYLE_REACTION_RECOMPUTE_STYLE | input_types::STYLE_REACTION_RECOMPUTE_DESCENDANT_STYLES,
+ 0,
+ );
+ }
+ }
+
+ /// Make `nodes` the elements the host shows the highlight pseudo-element of `kind` in. Those
+ /// that start or stop showing it style or drop theirs.
+ pub fn set_highlight_observing_elements(&mut self, kind: u8, nodes: &[StyleNodeID]) {
+ let mut moved = Vec::new();
+ self.retained
+ .highlight_observers
+ .replace(kind, nodes, |node| moved.push(node));
+ for node in moved {
+ self.record_derived_element_style_input(
+ node,
+ input_types::STYLE_REACTION_PSEUDO_INPUTS_MAY_HAVE_CHANGED,
+ 0,
+ );
+ }
+ }
+
pub fn record_derived_element_style_input(&mut self, node: StyleNodeID, reaction: u8, inherited_style_groups: u8) {
if reaction == 0 {
return;
@@ -2392,26 +1967,7 @@ impl StyleEngine {
self.host.deferred_element_style_inputs_are_pending = true;
}
- /// Fold the style input an element owes into the reaction C++ is about to apply to it, when
- /// that reaction covers it: a materialization covers anything, while a record delta covers
- /// what it already carries and a descendant recompute. The folded input is consumed; one not
- /// covered stays owed to the next transaction. Returns the merged reaction in the low byte and
- /// the merged inherited style groups in the next, or zero when nothing was folded.
- /// The reaction the element `node` owes as an element style input the engine defers, if it owes one.
- pub(crate) fn deferred_element_style_reaction(&self, node: StyleNodeID) -> Option<u8> {
- self.host
- .deferred_element_style_inputs
- .get(&node)
- .map(|pending| pending.reaction)
- }
-
- pub fn absorb_element_style_input(
- &mut self,
- node: StyleNodeID,
- reaction: u8,
- inherited_style_groups: u8,
- absorbs_any: bool,
- ) -> u32 {
+ pub fn absorb_element_style_input(&mut self, node: StyleNodeID, reaction: u8, inherited_style_groups: u8) -> u32 {
let Some(&DeferredElementStyleInput {
reaction: pending_reaction,
inherited_style_groups: pending_inherited_style_groups,
@@ -2421,9 +1977,8 @@ impl StyleEngine {
};
// A descendant recompute asks nothing of the element its own reaction does not answer, and
// the applied reaction carries what it asks of the descendants to the element's children.
- if !absorbs_any
- && (pending_reaction & !reaction & !transaction::STYLE_REACTION_RECOMPUTE_DESCENDANT_STYLES != 0
- || pending_inherited_style_groups & !inherited_style_groups != 0)
+ if pending_reaction & !reaction & !input_types::STYLE_REACTION_RECOMPUTE_DESCENDANT_STYLES != 0
+ || pending_inherited_style_groups & !inherited_style_groups != 0
{
return 0;
}
@@ -2456,21 +2011,6 @@ impl StyleEngine {
}
}
- /// Drop the style input an element owes but the descendant recompute it carries: a demand
- /// answers the element's own style, which reaches none of its descendants.
- pub(super) fn consume_element_style_input_but_descendants(&mut self, node: StyleNodeID) {
- let Some(pending) = self.host.deferred_element_style_inputs.get_mut(&node) else {
- return;
- };
- self.host.deferred_element_style_inputs_moved = true;
- if pending.reaction & transaction::STYLE_REACTION_RECOMPUTE_DESCENDANT_STYLES != 0 {
- pending.reaction = transaction::STYLE_REACTION_RECOMPUTE_DESCENDANT_STYLES;
- pending.inherited_style_groups = 0;
- } else {
- self.host.deferred_element_style_inputs.remove(&node);
- }
- }
-
/// Whether one element still owes a deferred style input, asked per node the way the recorded
/// batch is.
#[must_use]
@@ -2483,331 +2023,181 @@ impl StyleEngine {
/// usually avoid layout: anything not explicitly known to preserve geometry remains observable.
#[must_use]
pub fn pending_transaction_may_affect_layout_geometry(&self) -> bool {
- if self.host.journal.is_empty() {
- return !self.host.tree_staging.is_empty()
- || self.host.program_staging.is_dirty()
- || self.host.sheet_rule_replacement.is_some()
- || !self.host.deferred_element_style_inputs.is_empty()
- || self.host.initial_tree_bulk_load_is_pending;
- }
- if !self.host.journal.markers().is_empty()
- || !self.host.tree_staging.is_empty()
+ self.host.element_inputs.moves_environment()
+ || self.retained.projection.has_written_links()
|| self.host.program_staging.is_dirty()
|| self.host.sheet_rule_replacement.is_some()
|| !self.host.deferred_element_style_inputs.is_empty()
- || self.host.initial_tree_bulk_load_is_pending
- {
- return true;
- }
-
- let mut checked_keys = HashSet::default();
- self.host.journal.inputs().any(|input| {
- let keys = match input.key {
- InputKey::LocalFeature(_, LocalFeatureKey::PartExposure | LocalFeatureKey::ArrivingFacts) => {
- return true;
- }
- InputKey::LocalFeature(_, LocalFeatureKey::Attribute(name)) => {
- let mut keys = routing_keys_for_input(&input);
- for other in self.retained.facts.attribute_name_keys(name) {
- if other != name {
- keys.push(RoutingKey::AttributeName(other));
- }
- }
- keys
- }
- InputKey::LocalFeature(..) | InputKey::State(..) => routing_keys_for_input(&input),
- _ => return true,
- };
- keys.into_iter().any(|key| {
- // Geometry independence depends on the routing key's rules, not the node.
- // Reuse that proof when several journal inputs reach the same key.
- checked_keys.insert(key)
- && self.retained.routing.key_may_affect_layout_geometry(
- key,
- &self.retained.program,
- &self.retained.programs,
- )
- })
- })
+ || self.pending_inputs_may_affect_layout_geometry()
}
/// Preserve the pending paint-only selector facts as the style change event established by a
/// geometry read. Repeated reads advance the same boundary to the latest observed facts.
- /// Returning false means exact journalling coarsened while combining the facts, so the caller
- /// must settle style instead of reusing layout.
- pub fn defer_pending_transaction_for_geometry_read(&mut self) -> bool {
- debug_assert!(!self.host.flushing_deferred_geometry_journal);
- debug_assert!(self.host.tree_staging.is_empty());
+ pub fn defer_pending_transaction_for_geometry_read(&mut self) {
+ debug_assert!(!self.retained.projection.has_written_links());
debug_assert!(!self.host.program_staging.is_dirty());
debug_assert!(self.host.sheet_rule_replacement.is_none());
debug_assert!(self.host.deferred_element_style_inputs.is_empty());
- debug_assert!(!self.host.initial_tree_bulk_load_is_pending);
- debug_assert!(self.host.journal.markers().is_empty());
- debug_assert!(
- self.host
- .journal
- .inputs()
- .all(|input| matches!(input.key, InputKey::LocalFeature(..) | InputKey::State(..)))
- );
-
- if self.host.journal.is_empty() {
- return true;
- }
- if self.host.deferred_geometry_journal.is_empty() {
- std::mem::swap(&mut self.host.journal, &mut self.host.deferred_geometry_journal);
- } else {
- self.host
- .deferred_geometry_journal
- .absorb_newer(&mut self.host.journal, &self.retained.counters);
- }
- self.host.deferred_geometry_journal.markers().is_empty()
+ debug_assert!(self.host.element_inputs.is_empty());
+ self.retained.projection.seal_for_geometry_read();
}
- /// Make the style transaction sealed by a geometry read current while preserving local facts
+ /// Make the style update sealed by a geometry read current while preserving local facts
/// recorded after it for the following style change event.
pub fn begin_deferred_geometry_transaction_flush(&mut self) -> bool {
- debug_assert!(!self.host.flushing_deferred_geometry_journal);
- if self.host.deferred_geometry_journal.is_empty()
- || !self.host.journal.markers().is_empty()
- || !self.host.tree_staging.is_empty()
+ if !self.retained.projection.has_sealed_changes()
+ || !self.host.element_inputs.is_empty()
+ || self.retained.projection.has_written_links()
|| self.host.program_staging.is_dirty()
|| self.host.sheet_rule_replacement.is_some()
|| !self.host.deferred_element_style_inputs.is_empty()
- || self.host.initial_tree_bulk_load_is_pending
- || !self
- .host
- .journal
- .inputs()
- .all(|input| matches!(input.key, InputKey::LocalFeature(..) | InputKey::State(..)))
{
return false;
}
-
- let later_inputs: Vec<NormalizedInput> = self.host.journal.inputs().collect();
- for input in &later_inputs {
- self.apply_to_facts_without_settling(input.key, input.old);
- }
- std::mem::swap(&mut self.host.journal, &mut self.host.deferred_geometry_journal);
- self.host.flushing_deferred_geometry_journal = true;
+ self.retained.projection.begin_flushing_seal();
true
}
- /// Restore the local facts recorded after the geometry boundary once its transaction has been
- /// consumed.
+ /// Leave the local facts recorded after the geometry boundary to the next transaction once
+ /// the sealed one has been consumed.
pub fn end_deferred_geometry_transaction_flush(&mut self) {
- assert!(self.host.flushing_deferred_geometry_journal);
- assert!(self.host.journal.is_empty());
- assert!(self.host.tree_staging.is_empty());
+ assert!(self.host.element_inputs.is_empty());
+ assert!(!self.retained.projection.has_written_links());
assert!(!self.host.program_staging.is_dirty());
assert!(self.host.sheet_rule_replacement.is_none());
assert!(self.host.deferred_element_style_inputs.is_empty());
-
- std::mem::swap(&mut self.host.journal, &mut self.host.deferred_geometry_journal);
- let later_inputs: Vec<NormalizedInput> = self.host.journal.inputs().collect();
- for input in later_inputs {
- self.apply_to_facts_without_settling(input.key, input.new);
- }
- self.host.flushing_deferred_geometry_journal = false;
- }
-
- pub(super) fn merge_deferred_geometry_transaction(&mut self) {
- if self.host.flushing_deferred_geometry_journal || self.host.deferred_geometry_journal.is_empty() {
- return;
- }
- if self.host.journal.is_empty() {
- std::mem::swap(&mut self.host.journal, &mut self.host.deferred_geometry_journal);
- return;
- }
- self.host
- .deferred_geometry_journal
- .absorb_newer(&mut self.host.journal, &self.retained.counters);
- std::mem::swap(&mut self.host.journal, &mut self.host.deferred_geometry_journal);
- }
-
- pub(crate) fn settle_batched_inputs(&mut self) {
- self.install_pending_matching_context();
- if !self.host.journal.contains_only_element_style_inputs() {
- self.discard_prepared_batch_matching_traversal();
- }
- self.discard_published_match_answers();
+ self.retained.projection.end_flushing_seal();
}
#[must_use]
pub(crate) fn node_arrival_is_pending(&self, node: StyleNodeID) -> bool {
- self.host.journal.pending_old(InputKey::TreeRelations(node)) == Some(InputValue::TreeRelations(None))
- }
-
- /// Returns whether the change joined the current transaction.
- pub(super) fn record(&mut self, key: InputKey, old: InputValue, new: InputValue) -> bool {
- self.discard_prepared_batch_matching_traversal();
- if let Some(node) = self.node_whose_arrival_carries(key) {
- // Every fact of an arriving element folds onto one key, so the journal holds one entry
- // per element rather than one per fact. Routing reads the facts back off the element.
- self.retained.counters.bump(Counter::ArrivingNodeFactsFolded);
- self.host.journal.record(
- InputKey::LocalFeature(node, LocalFeatureKey::ArrivingFacts),
- InputValue::Feature(FeatureValue::Absent),
- InputValue::Feature(FeatureValue::Present),
- &self.retained.counters,
- );
- return true;
- }
- self.host.journal.record(key, old, new, &self.retained.counters);
- true
- }
-
- /// Whether a fact about an element is already carried by that element arriving.
- ///
- /// An element that connects in this transaction has its whole subtree put in the plan by its own
- /// tree delta, and the elements around it - the anchors of a relational query, the neighbours a
- /// sibling selector constrains, the parent whose emptiness moved - are reached from that delta
- /// too, not from anything the arriving element publishes about itself. So each of the facts it
- /// announces on the way in says nothing the arrival does not already say.
- ///
- /// What journalling them costs is the transaction's scratch budget: a page of a few thousand
- /// elements announces tens of thousands of them, and a journal that has to coarsen no longer
- /// knows which keys moved - which costs a restyle of the whole document, for elements whose
- /// arrival was already accounted for.
- ///
- /// The facts themselves are still applied: what is skipped is the journal entry, not the state.
- #[must_use]
- pub(super) fn node_whose_arrival_carries(&self, key: InputKey) -> Option<StyleNodeID> {
- let node = match key {
- InputKey::LocalFeature(node, feature) if feature != LocalFeatureKey::ArrivingFacts => node,
- InputKey::State(node, _) => node,
- _ => return None,
- };
- (self.host.journal.pending_old(InputKey::TreeRelations(node)) == Some(InputValue::TreeRelations(None)))
- .then_some(node)
+ self.retained.projection.arrival_is_pending(node)
}
- #[inline]
- pub(super) fn stage_tree_row(
- &mut self,
- node: StyleNodeID,
- old_if_unstaged: Option<TreeRelations>,
- new: Option<TreeRelations>,
- ) {
- let old = self.host.tree_staging.current_row(node, old_if_unstaged);
- if old == new {
- return;
+ /// Count one input, and note it for the next transaction where the projection holds no row
+ /// that says it: an element's facts and relations are written into the projection, whose
+ /// changes say them.
+ pub(super) fn record(&mut self, key: InputKey, old: InputValue, new: InputValue) {
+ let counters = &self.retained.counters;
+ counters.bump(Counter::RawMutationRecords);
+ if let Some(counter) = key.counter() {
+ counters.bump(counter);
}
- self.record(
- InputKey::TreeRelations(node),
- InputValue::TreeRelations(old),
- InputValue::TreeRelations(new),
- );
- if old.is_some() && new.is_none() {
- self.retained.counters.bump(Counter::TreeDepartureDeltas);
- }
- self.host.tree_staging.stage_row(node, old_if_unstaged, new);
- }
-
- pub(super) fn stage_connected_tree_row(&mut self, node: StyleNodeID, update: impl FnOnce(&mut TreeRelations)) {
- let old = self
- .host
- .tree_staging
- .current_row(node, Some(self.settled_tree_relations(node)));
- let mut new = old.expect("a pending neighbour must remain connected");
- // A subtree can preallocate sibling identities before publishing their insertions. Such
- // a neighbour has no parent yet; its own insertion will supply its links. Synthesizing a
- // connected before-row here would hide that arrival from transaction normalization.
- if new.parent.is_none() {
- return;
+ match (key, new) {
+ (InputKey::TreeRelations(_), _) => {}
+ (InputKey::LocalFeature(node, _) | InputKey::State(node, _), _) => {
+ // Every fact of an arriving element is said by its arrival.
+ if self.node_arrival_is_pending(node) {
+ counters.bump(Counter::ArrivingNodeFactsFolded);
+ }
+ }
+ (InputKey::ElementDeclaration(node, _), _) => {
+ if old != new {
+ self.host.element_inputs.note_declaration(node);
+ }
+ }
+ #[cfg(test)]
+ (
+ InputKey::ElementStyleInput(node),
+ InputValue::ElementStyleInput {
+ reaction,
+ inherited_style_groups,
+ },
+ ) => self.host.element_inputs.note_style_input(
+ node,
+ ElementStyleInput {
+ reaction,
+ inherited_style_groups,
+ },
+ ),
+ #[cfg(test)]
+ (InputKey::ElementStyleInput(_), _) => unreachable!("an element style input carries its reaction"),
+ // A registration made through `CSS.registerProperty()` moves how the elements declaring
+ // or reading its name compute, which the transaction taking the registry in finds.
+ (InputKey::CustomPropertyRegistration(_), _) => self.host.program_staging.note_registration_change(),
}
- update(&mut new);
- self.stage_tree_row(node, old, Some(new));
}
+ #[cfg(test)]
pub(super) fn stage_first_child(&mut self, parent: StyleNodeID, child: Option<StyleNodeID>) {
- self.host
- .tree_staging
- .stage_first_child(parent, self.retained.tree.first_element_child(parent), child);
+ self.retained
+ .write_projection_for_test(|writes| writes.stage_first_child(parent, child));
}
- pub(super) fn settle_tree_staging_memory(&mut self) {}
-
- /// Raises `deepest_element` to the depth of the deepest element the tree holds, and keeps `staged_rows` at how many
- /// relation rows are staged and not settled yet, both of which the document's host reads, rather than counts of
- /// the engine's own. Nothing is staged yet.
+ /// Raises `deepest_element` to the depth of the deepest element the tree holds, and keeps `link_rows_written` at
+ /// how many elements' links were written and not settled yet, both of which the document's host reads, rather than
+ /// counts of the engine's own. Nothing is written yet.
pub(crate) fn share_tree_depth(
&mut self,
deepest_element: std::sync::Arc<std::sync::atomic::AtomicU32>,
- staged_rows: std::sync::Arc<std::sync::atomic::AtomicU32>,
+ link_rows_written: std::sync::Arc<std::sync::atomic::AtomicU32>,
) {
- self.retained.tree.share_deepest_element(deepest_element);
- self.host.tree_staging.share_staged_rows(staged_rows);
+ deepest_element.fetch_max(
+ self.retained.deepest_element.load(std::sync::atomic::Ordering::Relaxed),
+ std::sync::atomic::Ordering::Relaxed,
+ );
+ self.retained.deepest_element = deepest_element;
+ self.retained.projection.share_link_rows_written(link_rows_written);
}
/// Gives a fork counts of the tree's depth of its own in place of those it shares with the host, holding what they
/// hold now.
pub(crate) fn detach_tree_depth_for_fork(&mut self) {
- self.retained.tree.detach_deepest_element_for_fork();
- self.host.tree_staging.detach_staged_rows_for_fork();
+ // NB: The depth lives beside the tree, so that a fork that never writes the tree shares it whole.
+ let deepest = self.retained.deepest_element.load(std::sync::atomic::Ordering::Relaxed);
+ self.retained.deepest_element = Arc::new(std::sync::atomic::AtomicU32::new(deepest));
+ self.retained.projection.detach_link_rows_written_for_fork();
}
- /// Install final staged relation rows at the transaction barrier.
- pub(super) fn apply_staged_tree_deltas(&mut self) {
- if self.host.tree_staging.is_empty() || self.host.tree_staging.is_applied() {
+ /// Settle the relation tree at the transaction barrier: recompute the depth of what the links written into the
+ /// projection since the last transaction was released moved, and retire the elements that left.
+ pub(super) fn settle_tree_at_barrier(&mut self) {
+ if !self.retained.projection.has_written_links() {
return;
}
- let staged_rows = self.host.tree_staging.dirty_rows();
- // Depth changes only for arrivals and for nodes whose parent differs from the resident one,
- // read before installation: the frozen before-side parent misses a move that a mid-transaction
- // application already installed, and a sibling-only row must not count as a moved parent.
- // A moved parent's subtree walk covers its moved descendants, so those are skipped below.
- let depth_recompute_nodes = self.depth_recompute_nodes(&staged_rows);
-
- for &(node, _, relations) in &staged_rows {
- let Some(relations) = relations else {
- self.retained.tree.set_parent_without_updating_depth(node, None);
- self.retained.tree.set_next_element_sibling(node, None);
- self.retained.tree.set_previous_element_sibling(node, None);
- self.retained.tree.set_assigned_slot(node, None);
- continue;
- };
- self.retained
- .tree
- .set_parent_without_updating_depth(node, relations.parent);
- self.retained
- .tree
- .set_next_element_sibling(node, relations.next_element_sibling);
- self.retained
- .tree
- .set_previous_element_sibling(node, relations.previous_element_sibling);
- if relations.tree_scope != TreeScopeID::DOCUMENT {
- self.retained.tree.enable_tree_scopes();
- }
- if self.retained.tree.has_tree_scopes() {
- self.retained.tree.set_tree_scope(node, relations.tree_scope);
- }
- self.retained.tree.set_assigned_slot(node, relations.assigned_slot);
- }
- for (parent, _, child) in self.host.tree_staging.dirty_first_children() {
- self.retained.tree.set_first_element_child(parent, child);
- }
- for &(node, _, _) in &staged_rows {
- if !depth_recompute_nodes.contains(&node) {
+ let mut nodes: Vec<StyleNodeID> = self.retained.projection.links_written().collect();
+ nodes.sort_unstable();
+ // Depth changes only for arrivals and for nodes whose parent differs from the one the last transaction
+ // committed: a sibling-only write must not count as a moved parent. A moved parent's subtree walk covers its
+ // moved descendants, so those are skipped below.
+ let depth_recompute_nodes = self.depth_recompute_nodes(&nodes);
+
+ self.retained.tree.note_element_links_moved();
+ for &node in &nodes {
+ if !depth_recompute_nodes.contains(&node) || !self.retained.tree.is_live(node) {
continue;
}
let parent_is_recomputed = self
- .tree
- .parent(node)
+ .retained
+ .projection
+ .written_relations(node)
+ .and_then(|relations| relations.parent)
.is_some_and(|parent| depth_recompute_nodes.contains(&parent));
if !parent_is_recomputed {
- self.retained.tree.recompute_subtree_depth(node);
+ let deepest = self.retained.tree.deepest_depth_under(&self.retained.projection, node);
+ self.retained
+ .deepest_element
+ .fetch_max(deepest, std::sync::atomic::Ordering::Relaxed);
}
}
let live_animation_overlays_before = self.retained.computed_group_sets.live_animation_overlay_records();
let mut retired_nodes: Vec<StyleNodeID> = Vec::new();
- for &(node, _, relations) in &staged_rows {
- if relations.is_some() || !self.retained.tree.is_live(node) {
+ let mut departed: Vec<StyleNodeID> = self
+ .retained
+ .projection
+ .relations_written()
+ .filter(|&node| self.retained.projection.written_relations(node).is_none())
+ .collect();
+ departed.sort_unstable();
+ for node in departed {
+ if !self.retained.tree.is_live(node) {
continue;
}
self.retained.retire_node_state(node);
retired_nodes.push(node);
}
if !retired_nodes.is_empty() {
+ // NB: The host retired the elements' rows as it published their departure.
self.retained.tree.retire_elements(&retired_nodes);
let live_animation_overlays_after = self.retained.computed_group_sets.live_animation_overlay_records();
self.retained.counters.add(
@@ -2822,34 +2212,6 @@ impl StyleEngine {
.counters
.add(Counter::StyleNodesRetired, retired_nodes.len() as u64);
}
- self.host.tree_staging.mark_applied();
- self.update_journal_entry_limit();
- }
-
- /// Name the node a style scope belongs to. A shadow root is a scope and a subtree at once, which
- /// is what lets a sheet attached there be bounded by the tree it decides in.
- /// Record that a tree scope decides with the document's author sheets as well as its own.
- pub fn set_tree_scope_uses_document_sheets(&mut self, tree_scope: TreeScopeID) {
- let previous = self
- .host
- .program_staging
- .scopes_using_document_sheets
- .current(tree_scope, || {
- self.retained.program.scope_uses_document_sheets(tree_scope)
- });
- if previous {
- return;
- }
- self.host.program_staging.scopes_using_document_sheets.stage(
- tree_scope,
- || self.retained.program.scope_uses_document_sheets(tree_scope),
- true,
- );
- self.host
- .program_staging
- .base_version
- .get_or_insert(self.retained.program.version());
- self.invalidate_scope_program(tree_scope);
}
}
@@ -2863,21 +2225,28 @@ impl StyleEngine {
&mut self,
sheet: SheetID,
before: Option<RuleID>,
- selectors: &[&CompiledSelector],
- namespaces: NamespaceScope,
- scope: &ScopeChain<'_>,
+ selectors: &SelectorListRef,
+ scope: Option<&super::bridge::BoundScopeChain>,
) -> RuleID {
- self.add_style_rule_with(sheet, before, |engine, previous_program| {
- engine.compile_selectors(selectors, namespaces, scope, previous_program)
+ let style_scope = self.scope_of_chain(scope);
+ self.add_style_rule_with(sheet, before, style_scope, |engine| {
+ engine.note_selectors(selectors, scope);
+ selectors.clone()
})
}
- /// Add a style rule whose selector program `attach` gives it, from the program of the rule it replaces, if any.
+ /// The scope a rule inside the `@scope` levels `chain`, if any, names.
+ fn scope_of_chain(&mut self, chain: Option<&super::bridge::BoundScopeChain>) -> StyleScopeID {
+ chain.map_or(StyleScopeID::NONE, |chain| self.retained.rules.scope_of_chain(chain))
+ }
+
+ /// Add a style rule inside the `@scope` levels `scope` names whose selectors `attach` gives it.
pub(super) fn add_style_rule_with(
&mut self,
sheet: SheetID,
before: Option<RuleID>,
- attach: impl FnOnce(&mut Self, Option<SelectorProgramID>) -> SelectorProgramID,
+ scope: StyleScopeID,
+ attach: impl FnOnce(&mut Self) -> SelectorListRef,
) -> RuleID {
let rule = match before {
Some(before) => self.insert_rule_before(before, RuleKind::Style),
@@ -2885,34 +2254,15 @@ impl StyleEngine {
.reuse_replaced_style_rule(sheet)
.unwrap_or_else(|| self.append_rule(sheet, None, RuleKind::Style)),
};
- let previous_program = self
- .replacement_rule(rule)
- .and_then(|replacement| replacement.version.selector_program);
- let program = attach(self, previous_program);
- if previous_program != Some(program) {
- self.add_routing_rule(rule, program);
- }
-
+ let selectors = attach(self);
let mut version = self.current_rule_version(rule);
- version.selector_program = Some(program);
+ version.selectors = self.retained.rules.start_of_selectors(sheet, &selectors);
+ version.scope = scope;
self.replace_rule_version(rule, version);
self.retained.counters.bump(Counter::StyleRulesCompiled);
rule
}
- /// Record that a sheet declared or gave up a cascade layer.
- ///
- /// The declaration contributes no declarations and matches nothing: what it does is fix the order
- /// of the layers every rule referencing them sits in. A layer name belongs to the tree scope the
- /// sheet is attached to, so what moves is that scope's layer order - one input per scope the sheet
- /// decides in.
- #[cfg(test)]
- pub fn record_layer_statement(&mut self, sheet: SheetID) {
- for scope in self.retained.program.sheet_scopes(sheet) {
- self.record_layer_topology_change(scope);
- }
- }
-
pub(super) fn add_named_rule(
&mut self,
sheet: SheetID,
@@ -2925,7 +2275,7 @@ impl StyleEngine {
None => self.append_rule(sheet, None, kind),
};
let mut version = self.current_rule_version(rule);
- version.declared_name = Some(name);
+ version.set_declared_name(name);
self.replace_rule_version(rule, version);
rule
}
@@ -2933,22 +2283,20 @@ impl StyleEngine {
/// Give an existing rule a new selector list, keeping its identity and its position.
///
/// Editing `selectorText` is one rule changing, not the sheet being rebuilt. The rule keeps its
- /// order token, so nothing around it is renumbered, and the journal sees exactly one selector
- /// field move.
+ /// order token, so nothing around it is renumbered, and the transaction sees exactly one rule
+ /// move.
pub fn replace_style_rule_selectors(
&mut self,
rule: RuleID,
- selectors: &[&CompiledSelector],
- namespaces: NamespaceScope,
- scope: &ScopeChain<'_>,
+ selectors: &SelectorListRef,
+ scope: Option<&super::bridge::BoundScopeChain>,
) {
- let program = self.compile_selectors(selectors, namespaces, scope, None);
- self.add_routing_rule(rule, program);
-
+ self.note_selectors(selectors, scope);
let mut version = self.current_rule_version(rule);
- version.selector_program = Some(program);
+ let sheet = self.retained.rules.rule_sheet(rule);
+ version.selectors = self.retained.rules.start_of_selectors(sheet, selectors);
+ version.scope = self.scope_of_chain(scope);
self.replace_rule_version(rule, version);
- self.settle_program();
self.retained.counters.bump(Counter::StyleRulesCompiled);
}
@@ -2956,165 +2304,57 @@ impl StyleEngine {
///
/// The block's contents changed even where the CSSOM object did not, so what makes this a
/// change is a version rather than the object's address. The rule keeps its identity, its
- /// position, and its selector program, so the journal sees one field move and routing reaches
+ /// position, and its selectors, so the transaction sees one rule move and restyles
/// exactly the elements that rule matches.
pub fn record_rule_declarations_changed(&mut self, rule: RuleID, block_version: u32) {
let mut version = self.current_rule_version(rule);
- version.declaration_block = Some(DeclarationBlockID(block_version));
+ version.declaration_block = Some(DeclarationBlockID::new(block_version));
self.replace_rule_version(rule, version);
- self.settle_program();
}
/// Make the identities the host minted live, ahead of anything the host records about their
/// nodes. Mints are batched because a call per node is exactly the boundary shape this design
/// rules out.
pub fn mint_style_nodes(&mut self, nodes: &[u32]) {
- let mut minted_an_element = false;
for node in nodes.iter().filter_map(|&raw| StyleNodeID::from_raw(raw)) {
if node.text_index().is_some() {
self.retained.tree.mint_text(node);
} else {
self.retained.tree.mint_element(node);
+ #[cfg(test)]
+ self.retained.write_projection_for_test(|writes| writes.mint([node]));
self.retained.counters.bump(Counter::StyleNodesAllocated);
- minted_an_element = true;
}
}
- if minted_an_element {
- self.update_journal_entry_limit();
- }
}
pub fn record_input(&mut self, key: InputKey, old: InputValue, new: InputValue) {
- if self.record(key, old, new) {
- self.apply_to_facts_without_settling(key, new);
- }
- }
-
- /// Record an exact style reaction for every flat-tree descendant of a node.
- ///
- /// The reaction is one C++ derived from a reaction it applied to `root`, not a fact only C++
- /// holds: a descendant is here because what it inherits moved, which the engine settles itself
- /// wherever its record computation admits it.
- pub fn record_flat_tree_descendant_style_inputs(
- &mut self,
- root: StyleNodeID,
- reaction: u8,
- inherited_style_groups: u8,
- ) {
- if reaction == 0 {
- return;
- }
- let mut descendants = Vec::new();
- self.for_each_flat_tree_descendant(root, |node| descendants.push(node));
- for node in descendants {
- self.record_derived_element_style_input(node, reaction, inherited_style_groups);
- }
- }
-
- /// Record one member of a flat FFI batch without repeatedly settling the fact-store capacity.
- ///
- /// The bridge has already applied every tree delta before it publishes facts. It can therefore
- /// identify facts carried by a node's arrival once per node instead of probing and replacing
- /// the same journal key once per fact.
- pub(crate) fn record_batched_input(
- &mut self,
- key: InputKey,
- old: InputValue,
- new: InputValue,
- arriving_node: bool,
- ) {
- if arriving_node {
- debug_assert!(matches!(key, InputKey::LocalFeature(..) | InputKey::State(..)));
- self.retained.counters.bump(Counter::ArrivingNodeFactsFolded);
- self.retained.counters.bump(Counter::RawMutationRecords);
- self.retained.counters.bump(Counter::LocalFeatureDeltas);
- self.apply_to_facts_without_settling(key, new);
- } else if self.record(key, old, new) {
- self.apply_to_facts_without_settling(key, new);
- }
- }
-
- /// Stage one structural delta and the neighbour rows it derives.
- pub(super) fn stage_tree_delta(
- &mut self,
- node: StyleNodeID,
- old: Option<TreeRelations>,
- new: Option<TreeRelations>,
- ) {
- if let Some(old) = old {
- if let Some(previous) = old.previous_element_sibling {
- self.stage_connected_tree_row(previous, |relations| {
- relations.next_element_sibling = old.next_element_sibling;
- });
- } else if let Some(parent) = old.parent {
- self.stage_first_child(parent, old.next_element_sibling);
- }
- if let Some(next) = old.next_element_sibling {
- self.stage_connected_tree_row(next, |relations| {
- relations.previous_element_sibling = old.previous_element_sibling;
- });
- }
- }
- if let Some(new) = new {
- if let Some(previous) = new.previous_element_sibling {
- self.stage_connected_tree_row(previous, |relations| {
- relations.next_element_sibling = Some(node);
- });
- } else if let Some(parent) = new.parent {
- self.stage_first_child(parent, Some(node));
- }
- if let Some(next) = new.next_element_sibling {
- self.stage_connected_tree_row(next, |relations| {
- relations.previous_element_sibling = Some(node);
- });
- }
- }
- self.stage_tree_row(node, old, new);
- self.settle_tree_staging_memory();
+ self.record(key, old, new);
+ self.apply_to_facts_without_settling(key, new);
}
/// Attach a compiled program at the end of a scope's sheet order.
pub(super) fn attach_sheet(&mut self, sheet: SheetID, tree_scope: TreeScopeID) {
- self.restore_routing_for_reattached_sheet(sheet);
let mut sheets = self.current_sheets_in_scope(tree_scope).to_vec();
- let previous_position = sheets.iter().position(|&candidate| candidate == sheet);
- let was_attached = previous_position.is_some();
sheets.retain(|&candidate| candidate != sheet);
sheets.push(sheet);
- let order_changed = previous_position.is_some_and(|previous| previous != sheets.len() - 1);
self.stage_sheets_in_scope(tree_scope, sheets);
- self.record_attachment(sheet, tree_scope, was_attached, true);
- if order_changed {
- self.record_sheet_order_change(tree_scope);
- }
}
/// Attach at a position established before the sheet finished loading. Network completion order
/// does not determine cascade order.
pub(super) fn attach_sheet_before(&mut self, sheet: SheetID, before: SheetID, tree_scope: TreeScopeID) {
- self.restore_routing_for_reattached_sheet(sheet);
let mut sheets = self.current_sheets_in_scope(tree_scope).to_vec();
- let previous_position = sheets.iter().position(|&candidate| candidate == sheet);
- let was_attached = previous_position.is_some();
sheets.retain(|&candidate| candidate != sheet);
let position = sheets
.iter()
.position(|&candidate| candidate == before)
.unwrap_or(sheets.len());
sheets.insert(position, sheet);
- let order_changed = previous_position.is_some_and(|previous| previous != position);
+ // NB: A sheet arriving in the middle is not the scope's order changing: every sheet already
+ // attached keeps the priority it had against every other, which is how the transaction
+ // tells an arrival from a move (see `staged_rule_changes`).
self.stage_sheets_in_scope(tree_scope, sheets);
- // A sheet arriving in the middle is not the scope's order changing. Order is kept as tokens
- // precisely so an insertion writes one label and renumbers nothing, so every sheet already
- // attached keeps the priority it had against every other. What is new is one more competitor
- // for the declarations it makes, and the elements that competition can reach are exactly the
- // ones its own rules match, which the attachment recorded above already names. A sheet that
- // was attached a moment ago and is arriving again can be a move, whose order delta is
- // recorded below.
- self.record_attachment(sheet, tree_scope, was_attached, true);
- if order_changed {
- self.record_sheet_order_change(tree_scope);
- }
}
/// Attach a sheet immediately before another sheet in the same scope, or at the end when that
@@ -3136,8 +2376,6 @@ impl StyleEngine {
let mut sheets = sheets.to_vec();
sheets.remove(position);
self.stage_sheets_in_scope(tree_scope, sheets);
- self.record_attachment(sheet, tree_scope, true, false);
- self.retained.routing_needs_detachment_sweep = true;
}
}
@@ -3166,12 +2404,12 @@ impl StyleEngine {
}
}
- /// Stage a structural change. The normalized transaction installs the final relation rows at
- /// the next observation boundary.
+ /// Write a structural change into the projection. The relation tree settles it at the next
+ /// transaction barrier.
+ #[cfg(test)]
pub fn record_tree_delta(&mut self, node: StyleNodeID, old: Option<TreeRelations>, new: Option<TreeRelations>) {
- if old != new {
- self.stage_tree_delta(node, old, new);
- }
+ self.retained
+ .write_projection_for_test(|writes| writes.record_tree_delta(node, old, new));
}
/// Record a registration made through `CSS.registerProperty()`. Stylesheet registrations are
@@ -3184,213 +2422,33 @@ impl StyleEngine {
);
}
- /// Record a state publication against the settled value StyleEngine already owns.
- ///
- /// State invalidators may conservatively republish a related group of pseudo-classes when one
- /// member changes. The settled fact is therefore the old side; assuming every publication is
- /// a Boolean toggle would invent transitions for the unchanged members of that group. Such a
- /// member is no input at all, and the answer says whether the state moved.
- pub(crate) fn record_batched_state(
- &mut self,
- node: StyleNodeID,
- fact: StateFact,
- new_value: bool,
- arriving_node: bool,
- ) -> bool {
- let old_value = self.retained.facts.states_of_node(node).contains(fact);
- if old_value == new_value && !arriving_node {
- return false;
- }
- self.record_batched_input(
- InputKey::State(node, fact),
- InputValue::State(old_value),
- InputValue::State(new_value),
- arriving_node,
- );
- true
- }
-
- /// Install the fixed facts carried by one element arrival. The tree row already routes the
- /// arriving element, so facts which can change later update their columns without adding one
- /// journal entry apiece.
- pub(crate) fn record_element_arrival(
- &mut self,
- node: StyleNodeID,
- arrival: &super::bridge::FfiElementArrival,
- custom_states: &[StyleAtomID],
- arriving_node: bool,
- ) {
- debug_assert!(arriving_node);
- self.retained
- .facts
- .set_namespace(node, StyleAtomID(arrival.namespace_atom));
- self.retained.facts.set_is_slot(node, arrival.is_slot);
- let mut publish_feature = |feature, value| {
- self.record_batched_input(
- InputKey::LocalFeature(node, feature),
- InputValue::Feature(FeatureValue::Absent),
- InputValue::Feature(value),
- arriving_node,
- );
- };
- if arrival.language_atom != 0 {
- publish_feature(
- LocalFeatureKey::Language,
- FeatureValue::Atom(StyleAtomID(arrival.language_atom)),
- );
- }
- if arrival.directionality_atom != 0 {
- publish_feature(
- LocalFeatureKey::Directionality,
- FeatureValue::Atom(StyleAtomID(arrival.directionality_atom)),
- );
- }
- if arrival.heading_level != 0 {
- publish_feature(
- LocalFeatureKey::HeadingLevel,
- FeatureValue::Number(u32::from(arrival.heading_level)),
- );
- }
- self.retained
- .computed_group_sets
- .set_adjustment_facts(node, arrival.adjustment_facts);
- self.retained
- .computed_group_sets
- .set_construction_facts(node, arrival.construction_facts);
- self.retained
- .computed_group_sets
- .set_box_kind(node, super::bridge::ElementBoxKind::from_raw(arrival.box_kind));
- self.retained
- .set_element_associated_pseudo_kind(node, arrival.associated_pseudo_kind_plus_one);
- for &state in custom_states {
- self.record_batched_input(
- InputKey::LocalFeature(node, LocalFeatureKey::CustomState(state)),
- InputValue::Feature(FeatureValue::Absent),
- InputValue::Feature(FeatureValue::Present),
- arriving_node,
- );
- }
- self.retained.facts.set_custom_states(node, custom_states);
- }
-
- /// Record the shadow parts an element exposes.
- ///
- /// A part is a fact about the element like a class is: posted so `::part()` rules can be
- /// enumerated from it, and journalled so a change to the `part` attribute routes. The plain
- /// name set is derived here from the name-to-host pairs exact matching needs, so the two views
- /// cannot disagree.
+ /// Record the shadow parts an element exposes, each with the shadow host it is exposed to.
+ #[cfg(test)]
pub fn set_element_parts(&mut self, node: StyleNodeID, pairs: &[(StyleAtomID, StyleNodeID)]) {
- let mut parts = Vec::new();
- for &(part, _) in pairs {
- if !parts.contains(&part) {
- parts.push(part);
- }
- }
- if self.retained.facts.parts_of(node) != parts {
- let previous: Vec<StyleAtomID> = self.retained.facts.parts_of(node).to_vec();
- for part in previous.iter().filter(|part| !parts.contains(part)) {
- self.record_input(
- InputKey::LocalFeature(node, LocalFeatureKey::Part(*part)),
- InputValue::Feature(FeatureValue::Present),
- InputValue::Feature(FeatureValue::Absent),
- );
- }
- for part in parts.iter().filter(|part| !previous.contains(part)) {
- self.record_input(
- InputKey::LocalFeature(node, LocalFeatureKey::Part(*part)),
- InputValue::Feature(FeatureValue::Absent),
- InputValue::Feature(FeatureValue::Present),
- );
- }
- self.retained.facts.set_parts(node, &parts);
- }
- self.retained.tree.set_part_hosts(node, pairs);
+ self.retained
+ .write_projection_for_test(|writes| writes.set_element_parts(node, pairs));
}
/// Report the outermost host a `::part()` rule can address this element from.
- ///
- /// What an `exportparts` change moves is which scopes can name an element, not which names it
- /// carries - the forwarded name is usually the one it already had. So the exposure is the fact,
- /// and an element whose reach did not move says nothing.
+ #[cfg(test)]
pub fn set_element_part_exposure(&mut self, node: StyleNodeID, exposure: StyleAtomID) {
- let previous = self.retained.facts.part_exposure_of(node);
- if previous == exposure {
- return;
- }
- self.record_input(
- InputKey::LocalFeature(node, LocalFeatureKey::PartExposure),
- InputValue::Feature(RetainedState::atom_or_absent(previous)),
- InputValue::Feature(RetainedState::atom_or_absent(exposure)),
- );
+ self.retained
+ .write_projection_for_test(|writes| writes.set_element_part_exposure(node, exposure));
}
+ #[cfg(test)]
pub fn set_element_heading_level(&mut self, node: StyleNodeID, level: u8) {
- let previous = self.retained.facts.heading_level_of(node);
- if previous == level {
- return;
- }
- self.record_input(
- InputKey::LocalFeature(node, LocalFeatureKey::HeadingLevel),
- InputValue::Feature(FeatureValue::Number(u32::from(previous))),
- InputValue::Feature(FeatureValue::Number(u32::from(level))),
- );
+ self.retained
+ .write_projection_for_test(|writes| writes.set_element_heading_level(node, level));
}
+ #[cfg(test)]
pub fn set_element_language(&mut self, node: StyleNodeID, language: StyleAtomID) {
- let previous = self.retained.facts.language_of(node);
- if previous == language {
- return;
- }
- self.record_input(
- InputKey::LocalFeature(node, LocalFeatureKey::Language),
- InputValue::Feature(RetainedState::atom_or_absent(previous)),
- InputValue::Feature(RetainedState::atom_or_absent(language)),
- );
- }
-
- /// Report the element's resolved directionality, which `:dir()` tests.
- pub fn set_element_directionality(&mut self, node: StyleNodeID, directionality: StyleAtomID) {
- let previous = self.retained.facts.directionality_of(node);
- if previous == directionality {
- return;
- }
- self.record_input(
- InputKey::LocalFeature(node, LocalFeatureKey::Directionality),
- InputValue::Feature(RetainedState::atom_or_absent(previous)),
- InputValue::Feature(RetainedState::atom_or_absent(directionality)),
- );
- }
-
- /// Replace the custom states an element is in.
- ///
- /// A custom state is a named fact about one element, exactly like a class, so it is published as
- /// one: the names that arrived and the names that left are each a local feature moving, and
- /// `:state()` reaches its subjects through the same postings every other name does.
- pub fn set_element_custom_states(&mut self, node: StyleNodeID, states: &[StyleAtomID]) {
- if self.retained.facts.custom_states_of(node) == states {
- return;
- }
- let previous: Vec<StyleAtomID> = self.retained.facts.custom_states_of(node).to_vec();
- for state in previous.iter().filter(|state| !states.contains(state)) {
- self.record_input(
- InputKey::LocalFeature(node, LocalFeatureKey::CustomState(*state)),
- InputValue::Feature(FeatureValue::Present),
- InputValue::Feature(FeatureValue::Absent),
- );
- }
- for state in states.iter().filter(|state| !previous.contains(state)) {
- self.record_input(
- InputKey::LocalFeature(node, LocalFeatureKey::CustomState(*state)),
- InputValue::Feature(FeatureValue::Absent),
- InputValue::Feature(FeatureValue::Present),
- );
- }
- self.retained.facts.set_custom_states(node, states);
+ self.retained
+ .write_projection_for_test(|writes| writes.set_element_language(node, language));
}
}
-impl StyleEngine {}
-
impl RetainedState {
/// Drop what the engine retains for an element whose identity retires. Identities are handed
/// out again once released, so a row left behind would describe whatever element is given the
@@ -3400,56 +2458,30 @@ impl RetainedState {
pub(super) fn retire_node_state(&mut self, node: StyleNodeID) {
let Self {
counters: _,
- deferred_pseudo_elements: _,
+ highlight_observers,
// Retires the whole batch at once, in `retire_elements`.
tree: _,
+ deepest_element: _,
hover,
- program: _,
- native_rules: _,
+ rules: _,
+ process_style: _,
declaration_block_version: _,
- last_transaction_only_derived_child_reactions: _,
- sheets_excluded_from_routing: _,
- sheets_kept_for_reattachment: _,
- routing_needs_detachment_sweep: _,
- match_workspace: _,
- // Scratch of one candidate evaluation.
- exact_covered_scratch: _,
- cascade_compaction_scratch: _,
- next_style_transaction_version: _,
+ next_style_update_version: _,
document_style_computation_inputs: _,
- driven_viewport: _,
document_resource_contexts: _,
document_media: _,
document_functions: _,
custom_property_registry: _,
font_resolution: _,
monospace_font_family: _,
- layer_topology_version: _,
- sheet_order_version: _,
- specified_values: _,
- winner_groups,
+ canonical_values: _,
computed_group_sets,
style_record_view_epoch_depth: _,
custom_property_environments: _,
- nodes_with_substituted_records,
- custom_declaration_reads,
- // Keyed by match answer, and cleared with the answers whose identities it names.
- custom_property_environments_by_answer: _,
- last_custom_property_environment_memoizable: _,
- custom_declaration_custom_property_reads,
- // Keyed by the values and names it holds.
- custom_property_reads_by_declarations: _,
- nodes_with_tree_counting_records,
- nodes_with_rolled_back_records,
- nodes_with_element_relative_substitutions,
element_custom_property_data,
pseudo_element_custom_property_data,
- environment_move_recompute_nodes,
+ keyframes_reading_parent_reset_values,
container_effects_for_host,
- published_container_verdicts,
- container_gates_unheld,
- row_inputs_moved,
- container_query_inputs,
layout_style_snapshots,
size_container_queries,
counter_style_environment_identities: _,
@@ -3458,7 +2490,6 @@ impl RetainedState {
// Empty but while a clock frame runs, which no retirement reaches.
tick_shown: _,
backing_elements,
- children_explicitly_inherit_marks,
css_defined_animations,
animation_keyframes: _,
position_try_rules: _,
@@ -3472,119 +2503,81 @@ impl RetainedState {
custom_property_registrations_changed: _,
// Settled or reverted when the transaction's outputs are discarded, before identities are
// released.
- engine_computed_records_pending: _,
demand_records,
- flush_stamp: _,
- engine_pseudo_record_cache: _,
- // Filled and cleared within one transaction's record loop.
- batch_answers_complete_but_for_custom_properties: _,
- batch_custom_property_matches: _,
- batch_custom_property_answers: _,
- batch_backing_pseudo_matches: _,
// Forgotten for departed elements in `forget_departed_elements`.
- shadow_host_backing_pseudo_matches: _,
- engine_cold_record_cache: _,
- engine_cold_record_donors: _,
- style_invalidation_cache: _,
- match_answers: _,
- selector_truth_sets: _,
// Forgotten for departed elements in `forget_departed_elements`.
- retained_match_answers: _,
- // Cleared by every transaction with a tree input, which a departure is.
- retained_selector_incidences: _,
- selector_incidence_is_current: _,
// Scratch of one traversal.
- batch_matching_traversal: _,
- route_pruning_states: _,
// Keyed by the tree's DOM order version.
sibling_positions: _,
// Dropped in `forget_departed_elements` when a relation holds a departed element.
- prefix_caches: _,
- #[cfg(test)]
- force_bounded_prefix_completion: _,
// Scratch of one transaction.
- prepared_batch_matching_traversal: _,
- published_match_answers: _,
- transaction_fact_view: _,
+ // Not keyed by style node.
+ cold_pass_report: _,
+ // Keyed by style node, and only ever started by a test.
+ live_style: _,
+ live_style_may_start: _,
+ cold_passes: _,
+ // The last pass's elements, which a reader leaves out where they departed.
+ live_counters: _,
+ style_pool: _,
+ substituted_font_values: _,
// Forgotten for departed elements in `forget_departed_elements`.
- facts: _,
- programs: _,
+ element_declarations: _,
+ // Retires the whole batch at once with the tree, in `settle_tree_at_barrier`, but for the hover overlay,
+ // which lets go of the element here.
+ projection,
attribute_value_text_names: _,
tested_attribute_names: _,
attribute_value_text_requirements_version: _,
+ selectors_test_local_link: _,
relational_arrival_keys: _,
unresolved_relational_arrival_keys: _,
relational_arrival_keys_version: _,
- selector_programs_need_sweep: _,
- routing: _,
- deferred_user_agent_routes: _,
- // Scratch of one transaction.
- selector_truth_changes: _,
- already_planned_selector_truth: _,
- selector_truth_changes_active: _,
// A witness is checked against the live tree before it is used.
- relational_witnesses: _,
// Scratch of one transaction.
- pending_witness_effects: _,
// Forgotten for departed scope roots in `forget_departed_elements`.
scope_roots: _,
scope_by_root: _,
- scope_programs: _,
- vacant_scope_programs: _,
- scope_dispatch_templates: _,
- scope_cascade_templates: _,
- ancestor_dispatch_templates: _,
- retired_scope_templates: _,
- scope_templates_need_sweep: _,
- scope_program_by_scope: _,
atoms: _,
html_element_namespace: _,
fold_id_and_class_name_case: _,
- #[cfg(test)]
- diagnostic_plan_capture: _,
} = self;
hover.retire(node);
- winner_groups.remove(node);
+ projection.retire_hovered(node);
+ highlight_observers.retire(node);
computed_group_sets.remove(node);
- nodes_with_substituted_records.remove(&node);
- custom_declaration_reads.remove(&node);
- custom_declaration_custom_property_reads.remove(&node);
- nodes_with_tree_counting_records.remove(&node);
- nodes_with_rolled_back_records.remove(&node);
- nodes_with_element_relative_substitutions.remove(&node);
element_custom_property_data.remove(&node);
pseudo_element_custom_property_data.remove(&node);
- environment_move_recompute_nodes.remove(&node);
+ if keyframes_reading_parent_reset_values.contains(&node) {
+ keyframes_reading_parent_reset_values.remove(&node);
+ }
+ // NB: A fork shares the tables below until either side writes them, so retiring an element that has no row
+ // in one writes nothing to it.
container_effects_for_host.set(node, None);
- published_container_verdicts.remove(&node);
- container_gates_unheld.remove(&node);
- row_inputs_moved.forget(node);
- container_query_inputs.clear(node);
layout_style_snapshots.remove(&node);
- demand_records.retain(|target, record| {
- let retired = target.node() == node;
- if retired {
- computed_group_sets.unpin_style_record(record.raw());
- }
- !retired
- });
- size_container_queries.retire(node);
- backing_elements.remove(&node);
- if let Some(style_record) = held_style_records.remove(&node) {
- computed_group_sets.unpin_style_record(style_record);
+ if demand_records.keys().any(|target| target.node() == node) {
+ demand_records.retain(|target, record| {
+ let retired = target.node() == node;
+ if retired {
+ computed_group_sets.unpin_style_record(record.raw());
+ }
+ !retired
+ });
}
- for (_, style_record) in held_pseudo_style_records.remove(&node).into_iter().flatten() {
- computed_group_sets.unpin_style_record(style_record);
+ size_container_queries.retire(node);
+ if backing_elements.contains_key(&node) {
+ backing_elements.remove(&node);
}
- children_explicitly_inherit_marks.remove(&node);
+ held_style_records.set(node, None);
+ held_pseudo_style_records.remove(&node);
css_defined_animations.retire(node);
animation_effect_descriptions.retire(node);
random_base_values.retire(node);
- replaced_content_inputs.remove(&node);
- // A retired identity can name another element before the epoch commits.
- for style_record in transition_baselines.remove(node) {
- computed_group_sets.unpin_style_record(style_record);
+ if replaced_content_inputs.contains_key(&node) {
+ replaced_content_inputs.remove(&node);
}
+ // A retired identity can name another element before the epoch commits.
+ transition_baselines.remove(node);
}
}
@@ -3602,9 +2595,3 @@ pub(crate) fn next_declaration_block_version(versions: &std::sync::atomic::Atomi
.checked_add(1)
.expect("declaration revision overflow")
}
-
-/// The attribute value text requirements version of an engine whose selectors' requirements are at `selector_version`:
-/// it moves with every name an `attr()` anywhere in the process can newly read, too.
-pub(crate) fn with_attr_names_read(selector_version: u64) -> u64 {
- selector_version.wrapping_add(crate::css::parser::arbitrary_substitution::attr_names_read_generation())
-}
diff --git a/Libraries/LibWeb/Rust/src/css/style/intern_table.rs b/Libraries/LibWeb/Rust/src/css/style/intern_table.rs
index 8fd2fbd0d22..af1d82886ff 100644
--- a/Libraries/LibWeb/Rust/src/css/style/intern_table.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/intern_table.rs
@@ -7,33 +7,35 @@
//! Shared hash index and dense payload storage for style-engine interners.
use hashbrown::HashTable;
-use std::hash::Hash;
-use std::hash::Hasher;
use std::ops::Index;
use std::ops::IndexMut;
-use super::fast_hash::fast_hasher;
-
-pub(super) fn content_hash(content: impl Hash) -> u64 {
- let mut hasher = fast_hasher();
- content.hash(&mut hasher);
- hasher.finish()
-}
-
pub(super) trait InternIdentity: Copy {
fn index(self) -> usize;
+ fn from_index(index: usize) -> Self;
}
+/// An entry's identity and 32 bits of its hash, which with a 32-bit identity fit in 8 bytes.
#[derive(Clone, Copy)]
struct HashedIdentity<Identity> {
- hash: u64,
+ hash: u32,
identity: Identity,
}
+/// The 32 bits of `hash` an entry keeps.
+fn short_hash(hash: u64) -> u32 {
+ (hash ^ (hash >> 32)) as u32
+}
+
+/// The hash the table places an entry by, spread from the 32 bits it keeps over all 64, as the
+/// table reads its top bits.
+fn table_hash(short_hash: u32) -> u64 {
+ u64::from(short_hash).wrapping_mul(0x9e37_79b9_7f4a_7c15)
+}
+
pub(super) struct InternTable<Identity, Payload> {
entries: Vec<Payload>,
identities: HashTable<HashedIdentity<Identity>>,
- free_identities: Vec<Identity>,
}
impl<Identity, Payload> Default for InternTable<Identity, Payload> {
@@ -41,15 +43,31 @@ impl<Identity, Payload> Default for InternTable<Identity, Payload> {
Self {
entries: Vec::new(),
identities: HashTable::new(),
- free_identities: Vec::new(),
}
}
}
impl<Identity: InternIdentity, Payload> InternTable<Identity, Payload> {
+ /// The bytes of the payload column and the hash index, with what `payload_heap` says each
+ /// payload holds.
+ pub(super) fn heap_size(
+ &self,
+ sizer: &mut crate::heap_size::HeapSizer,
+ mut payload_heap: impl FnMut(&Payload, &mut crate::heap_size::HeapSizer) -> usize,
+ ) -> usize {
+ crate::heap_size::vec_bytes(&self.entries)
+ + self.identities.allocation_size()
+ + self
+ .entries
+ .iter()
+ .map(|payload| payload_heap(payload, sizer))
+ .sum::<usize>()
+ }
+
pub(super) fn find(&self, hash: u64, mut matches: impl FnMut(Identity, &Payload) -> bool) -> Option<Identity> {
+ let hash = short_hash(hash);
self.identities
- .find(hash, |candidate| {
+ .find(table_hash(hash), |candidate| {
candidate.hash == hash && matches(candidate.identity, &self.entries[candidate.identity.index()])
})
.map(|candidate| candidate.identity)
@@ -61,8 +79,14 @@ impl<Identity: InternIdentity, Payload> InternTable<Identity, Payload> {
} else {
self.entries[identity.index()] = payload;
}
- self.identities
- .insert_unique(hash, HashedIdentity { hash, identity }, |candidate| candidate.hash);
+ self.identities.insert_unique(
+ table_hash(short_hash(hash)),
+ HashedIdentity {
+ hash: short_hash(hash),
+ identity,
+ },
+ |candidate| table_hash(candidate.hash),
+ );
}
pub(super) fn get(&self, identity: Identity) -> &Payload {
@@ -73,92 +97,48 @@ impl<Identity: InternIdentity, Payload> InternTable<Identity, Payload> {
&mut self.entries[identity.index()]
}
- pub(super) fn get_index(&self, index: usize) -> Option<&Payload> {
- self.entries.get(index)
- }
-
pub(super) fn len(&self) -> usize {
self.entries.len()
}
- pub(super) fn is_empty(&self) -> bool {
- self.entries.is_empty()
- }
-
- pub(super) fn iter(&self) -> impl Iterator<Item = &Payload> {
- self.entries.iter()
- }
-
- pub(super) fn iter_mut(&mut self) -> impl Iterator<Item = &mut Payload> {
- self.entries.iter_mut()
- }
-
- pub(super) fn live_identities(&self) -> impl ExactSizeIterator<Item = Identity> + '_ {
- self.identities.iter().map(|candidate| candidate.identity)
- }
-
- pub(super) fn take_free_identity(&mut self) -> Option<Identity> {
- self.free_identities.pop()
- }
-
- pub(super) fn shrink_excess_capacity(&mut self) {
- // Retain growth headroom so a batch of removals does not force the next
- // insertion to allocate and copy the table again.
- self.entries.shrink_to(self.entries.len().saturating_mul(2));
- self.identities
- .shrink_to(self.identities.len().saturating_mul(2), |candidate| candidate.hash);
- }
-
- #[cfg(test)]
- pub(super) fn live_len(&self) -> usize {
- self.identities.len()
- }
-
- #[cfg(test)]
- pub(super) fn live_is_empty(&self) -> bool {
- self.identities.is_empty()
- }
-}
-
-impl<Identity: InternIdentity> InternTable<Identity, ()> {
- pub(super) fn insert_identity(&mut self, hash: u64, identity: Identity) {
- if identity.index() >= self.entries.len() {
- self.entries.resize(identity.index() + 1, ());
+ /// Keep only the payloads `keep` says to, packing the ones kept in their order: each keeps
+ /// its hash, and the identity of its new index.
+ pub(super) fn retain(&mut self, mut keep: impl FnMut(&Payload) -> bool) {
+ let mut new_index = Vec::with_capacity(self.entries.len());
+ let mut kept = 0_usize;
+ let entries = std::mem::take(&mut self.entries);
+ for payload in entries {
+ if keep(&payload) {
+ new_index.push(Some(kept));
+ self.entries.push(payload);
+ kept += 1;
+ } else {
+ new_index.push(None);
+ }
}
+ self.entries.shrink_to_fit();
self.identities
- .insert_unique(hash, HashedIdentity { hash, identity }, |candidate| candidate.hash);
- }
-}
-
-impl<Identity: InternIdentity + PartialEq, Payload> InternTable<Identity, Payload> {
- pub(super) fn remove_identity(&mut self, hash: u64, identity: Identity) {
- let Ok(entry) = self.identities.find_entry(hash, |candidate| {
- candidate.hash == hash && candidate.identity == identity
- }) else {
- panic!("interned identity must have an index entry");
- };
- entry.remove();
- }
-
- pub(super) fn retire_identity(&mut self, hash: u64, identity: Identity) {
- self.remove_identity(hash, identity);
- self.free_identities.push(identity);
+ .retain(|candidate| match new_index[candidate.identity.index()] {
+ Some(index) => {
+ candidate.identity = Identity::from_index(index);
+ true
+ }
+ None => false,
+ });
+ self.identities.shrink_to_fit(|candidate| table_hash(candidate.hash));
}
}
impl<Identity: InternIdentity, Payload: Clone> Clone for InternTable<Identity, Payload> {
fn clone(&self) -> Self {
let entries = self.entries.clone();
- let free_identities = self.free_identities.clone();
let mut identities = HashTable::with_capacity(self.identities.len());
for candidate in &self.identities {
- identities.insert_unique(candidate.hash, *candidate, |candidate| candidate.hash);
- }
- Self {
- entries,
- identities,
- free_identities,
+ identities.insert_unique(table_hash(candidate.hash), *candidate, |candidate| {
+ table_hash(candidate.hash)
+ });
}
+ Self { entries, identities }
}
}
@@ -210,6 +190,10 @@ mod tests {
fn index(self) -> usize {
self.0 as usize
}
+
+ fn from_index(index: usize) -> Self {
+ Self(u32::try_from(index).unwrap())
+ }
}
#[test]
@@ -226,19 +210,17 @@ mod tests {
}
#[test]
- fn retired_identities_can_replace_their_dense_payload() {
+ fn retained_payloads_are_found_under_their_new_identities() {
let mut table = InternTable::default();
- let identity = TestIdentity(0);
- table.insert(7, identity, "first");
-
- table.retire_identity(7, identity);
- assert_eq!(table.find(7, |_identity, _payload| true), None);
- let recycled = table.take_free_identity().unwrap();
- assert_eq!(recycled, identity);
+ table.insert(1, TestIdentity(0), "dropped");
+ table.insert(2, TestIdentity(1), "kept");
+ table.retain(|payload| *payload == "kept");
- table.insert(9, recycled, "second");
assert_eq!(table.len(), 1);
- assert_eq!(table.find(9, |_identity, payload| *payload == "second"), Some(identity));
- assert_eq!(table.live_identities().collect::<Vec<_>>(), vec![identity]);
+ assert_eq!(
+ table.find(2, |_identity, payload| *payload == "kept"),
+ Some(TestIdentity(0))
+ );
+ assert_eq!(table.find(1, |_identity, _payload| true), None);
}
}
diff --git a/Libraries/LibWeb/Rust/src/css/style/kept_past_release.rs b/Libraries/LibWeb/Rust/src/css/style/kept_past_release.rs
new file mode 100644
index 00000000000..b001801b164
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/kept_past_release.rs
@@ -0,0 +1,196 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+use crate::fast_hash::FastMap;
+use std::sync::Arc;
+use std::time::{Duration, Instant};
+
+/// How many bytes of what nothing else holds the process keeps of each kind of shared style data.
+const BYTES_KEPT_PAST_RELEASE: usize = 15 * 1024 * 1024;
+
+/// How long after its last use the process keeps what nothing else holds.
+const KEPT_PAST_LAST_USE: Duration = Duration::from_secs(5 * 60);
+
+struct Kept<T> {
+ value: Arc<T>,
+ bytes: usize,
+ /// When the value was last asked for, in the order of such asks.
+ used: u64,
+ used_at: Instant,
+}
+
+/// Shared immutable values the process keeps alive once the documents using them let go: a navigation to a page of the
+/// same site finds what the page it left parsed and indexed, even after a collection. They go when they exceed a budget,
+/// the least recently used first, when they have gone unused for a while, and when the process is short of memory.
+/// What a document still holds costs nothing here, and counts against no budget.
+pub(in crate::css) struct KeptPastRelease<T> {
+ entries: FastMap<usize, Kept<T>>,
+ budget: usize,
+ next_use: u64,
+}
+
+impl<T> Default for KeptPastRelease<T> {
+ fn default() -> Self {
+ Self::with_budget(BYTES_KEPT_PAST_RELEASE)
+ }
+}
+
+fn is_released<T>(entry: &Kept<T>) -> bool {
+ Arc::strong_count(&entry.value) == 1
+}
+
+impl<T> KeptPastRelease<T> {
+ fn with_budget(budget: usize) -> Self {
+ Self {
+ entries: FastMap::default(),
+ budget,
+ next_use: 0,
+ }
+ }
+
+ /// Keep `value`, which holds about `bytes`, and answer the values that left to make room, for the caller to drop
+ /// past its locks.
+ #[must_use]
+ pub(in crate::css) fn keep(&mut self, value: &Arc<T>, bytes: usize) -> Vec<Arc<T>> {
+ self.keep_at(value, bytes, Instant::now())
+ }
+
+ fn keep_at(&mut self, value: &Arc<T>, bytes: usize, now: Instant) -> Vec<Arc<T>> {
+ self.next_use += 1;
+ self.entries.insert(
+ Arc::as_ptr(value).addr(),
+ Kept {
+ value: Arc::clone(value),
+ bytes,
+ used: self.next_use,
+ used_at: now,
+ },
+ );
+ let mut released: Vec<(u64, usize, usize)> = self
+ .entries
+ .iter()
+ .filter(|(_, entry)| is_released(entry))
+ .map(|(&key, entry)| (entry.used, key, entry.bytes))
+ .collect();
+ let mut over = released
+ .iter()
+ .map(|&(_, _, bytes)| bytes)
+ .sum::<usize>()
+ .saturating_sub(self.budget);
+ let mut left = Vec::new();
+ if over == 0 {
+ return left;
+ }
+ released.sort_unstable();
+ for (_, key, bytes) in released {
+ if over == 0 {
+ break;
+ }
+ over = over.saturating_sub(bytes);
+ left.extend(self.entries.remove(&key).map(|entry| entry.value));
+ }
+ left
+ }
+
+ /// Note that a document asked for `value`, if it is kept.
+ pub(in crate::css) fn note_use(&mut self, value: &Arc<T>) {
+ self.note_use_at(value, Instant::now());
+ }
+
+ fn note_use_at(&mut self, value: &Arc<T>, now: Instant) {
+ self.next_use += 1;
+ if let Some(entry) = self.entries.get_mut(&Arc::as_ptr(value).addr()) {
+ entry.used = self.next_use;
+ entry.used_at = now;
+ }
+ }
+
+ /// Let go of what nothing else holds and nothing asked for lately, and answer it, for the caller to drop past its
+ /// locks.
+ #[must_use]
+ pub(in crate::css) fn prune(&mut self) -> Vec<Arc<T>> {
+ let now = Instant::now();
+ self.take_released(|entry| now.saturating_duration_since(entry.used_at) >= KEPT_PAST_LAST_USE)
+ }
+
+ /// Let go of everything nothing else holds, as the process is short of memory, and answer it, for the caller to
+ /// drop past its locks.
+ #[must_use]
+ pub(in crate::css) fn release_all(&mut self) -> Vec<Arc<T>> {
+ self.take_released(|_| true)
+ }
+
+ fn take_released(&mut self, goes: impl Fn(&Kept<T>) -> bool) -> Vec<Arc<T>> {
+ let mut left = Vec::new();
+ self.entries.retain(|_, entry| {
+ if is_released(entry) && goes(entry) {
+ left.push(Arc::clone(&entry.value));
+ return false;
+ }
+ true
+ });
+ left
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn the_least_recently_used_released_values_go_first_and_only_past_the_budget() {
+ let mut kept = KeptPastRelease::with_budget(10);
+ let now = Instant::now();
+ let held = Arc::new(0);
+ assert!(kept.keep_at(&held, 100, now).is_empty());
+ let first = Arc::new(1);
+ assert!(kept.keep_at(&first, 5, now).is_empty());
+ let second = Arc::new(2);
+ assert!(kept.keep_at(&second, 5, now).is_empty());
+ let (first_pointer, second_pointer) = (Arc::as_ptr(&first), Arc::as_ptr(&second));
+ // A use makes the first the more recent, though it came first.
+ kept.note_use_at(&first, now);
+ drop(first);
+ drop(second);
+ let third = Arc::new(3);
+ assert!(kept.keep_at(&third, 5, now).is_empty());
+ drop(third);
+ let fourth = Arc::new(4);
+ let left = kept.keep_at(&fourth, 5, now);
+ assert_eq!(left.len(), 1);
+ assert_eq!(Arc::as_ptr(&left[0]), second_pointer);
+ assert!(kept.entries.contains_key(&first_pointer.addr()));
+ assert_eq!(Arc::strong_count(&held), 2);
+ }
+
+ #[test]
+ fn being_short_of_memory_lets_go_of_all_but_what_a_document_holds() {
+ let mut kept = KeptPastRelease::with_budget(100);
+ let held = Arc::new(0);
+ drop(kept.keep(&held, 1));
+ let released = Arc::new(1);
+ drop(kept.keep(&released, 1));
+ drop(released);
+ assert_eq!(kept.release_all().len(), 1);
+ assert_eq!(kept.entries.len(), 1);
+ }
+
+ #[test]
+ fn only_what_nothing_asked_for_lately_is_pruned() {
+ let mut kept = KeptPastRelease::with_budget(100);
+ let now = Instant::now();
+ let long_unused = Arc::new(0);
+ drop(kept.keep_at(&long_unused, 1, now.checked_sub(KEPT_PAST_LAST_USE).unwrap()));
+ let held = Arc::new(1);
+ drop(kept.keep_at(&held, 1, now.checked_sub(KEPT_PAST_LAST_USE).unwrap()));
+ let recent = Arc::new(2);
+ drop(kept.keep_at(&recent, 1, now));
+ drop(long_unused);
+ drop(recent);
+ assert_eq!(kept.prune().len(), 1);
+ assert_eq!(kept.entries.len(), 2);
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/partial_view.rs b/Libraries/LibWeb/Rust/src/css/style/partial_view.rs
deleted file mode 100644
index a1d9332019d..00000000000
--- a/Libraries/LibWeb/Rust/src/css/style/partial_view.rs
+++ /dev/null
@@ -1,27 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-/// The result of consulting an optional physical materialization.
-///
-/// A known absence is a semantic answer. A missing result names the coverage gap that prevents an
-/// answer, so a gap can never silently turn unknown state into an empty relation.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub(super) enum Lookup<T, Gap> {
- Known(T),
- KnownAbsent,
- Missing(Gap),
-}
-
-impl<T, Gap> Lookup<T, Gap> {
- /// Convert a sparse lookup, whose materialization never represents known absence.
- pub(super) fn sparse(self) -> Result<T, Gap> {
- match self {
- Self::Known(value) => Ok(value),
- Self::KnownAbsent => unreachable!("a sparse lookup cannot be known absent"),
- Self::Missing(gap) => Err(gap),
- }
- }
-}
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/pending_inputs.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/pending_inputs.rs
new file mode 100644
index 00000000000..90546541c0c
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/pending_inputs.rs
@@ -0,0 +1,429 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! What the inputs the host has yet to settle may change, which the host asks to skip settling
+//! them where nothing it reads can move: a geometry read reuses the committed layout where no
+//! pending input may move geometry, and a hover reuses the read-only frame where no element can
+//! match a compound testing `:hover`.
+
+use super::super::*;
+use super::invalidation::{InvalidationMap, Trigger};
+use super::live::Live;
+use super::projection::{ElementChange, ProjectionGeneration};
+use crate::fast_hash::FastSet;
+
+/// The last answer of whether a hover needs the style engine, with what it read to answer: the
+/// projection's generation, the tree's version, the invalidation map and the hover's root. An
+/// answer read over the same holds again, so a rendering update over a document nothing changed
+/// in asks nothing of its elements.
+#[derive(Clone, Default)]
+pub(in crate::css::style) struct HoverSealMemo {
+ last: Option<HoverSealAnswer>,
+ candidates: Option<HoverSealCandidates>,
+ cursor_facts: Option<HoverCursorFactsAnswer>,
+}
+
+/// The elements whose rows may make a hover need the style engine, with the generation of the rows they were read
+/// from and the invalidation map they were matched against: a seal over other rows reads again only the rows written
+/// since.
+#[derive(Clone)]
+struct HoverSealCandidates {
+ projection: ProjectionGeneration,
+ invalidation: Option<Arc<InvalidationMap>>,
+ /// The elements whose written facts say they are disabled.
+ disabled: FastSet<StyleNodeID>,
+ hover_keyed: HoverKeyedElements,
+}
+
+/// The elements that may match a compound testing `:hover`, by their keys.
+#[derive(Clone)]
+enum HoverKeyedElements {
+ /// Every element may: there is no map describing the rules, or a query tests `:hover`.
+ Every,
+ /// Those carrying the keys of a compound testing `:hover`.
+ Carrying(FastSet<StyleNodeID>),
+}
+
+/// The cursor facts published last, with the generations of what they read: the projection's, the tree's paint facts,
+/// and the records the elements are assigned.
+#[derive(Clone)]
+struct HoverCursorFactsAnswer {
+ projection: ProjectionGeneration,
+ dom_paint_facts_version: u64,
+ installed_column_version: u64,
+ facts: Arc<super::super::hover_lane::HoverCursorFacts>,
+ editable: Arc<FastSet<StyleNodeID>>,
+}
+
+#[derive(Clone)]
+struct HoverSealAnswer {
+ projection: ProjectionGeneration,
+ dom_order_version: u64,
+ invalidation: Option<Arc<InvalidationMap>>,
+ root: StyleNodeID,
+ needs_style_state: bool,
+}
+
+/// Whether `a` and `b` are the same invalidation map, or both none.
+fn same_map(a: Option<&Arc<InvalidationMap>>, b: Option<&Arc<InvalidationMap>>) -> bool {
+ match (a, b) {
+ (Some(a), Some(b)) => Arc::ptr_eq(a, b),
+ (None, None) => true,
+ _ => false,
+ }
+}
+
+impl StyleEngine {
+ fn hover_seal_invalidation(&self) -> Option<&Arc<InvalidationMap>> {
+ self.retained.live_style.as_deref()?.current_invalidation_shared()
+ }
+
+ /// The answer the hover seal gave last for `root`, where nothing it read moved since.
+ pub(in super::super) fn memoized_hover_seal(&self, root: StyleNodeID) -> Option<bool> {
+ let last = self.host.hover_seal.last.as_ref()?;
+ (last.root == root
+ && same_map(last.invalidation.as_ref(), self.hover_seal_invalidation())
+ && last.dom_order_version == self.tree().dom_order_version()
+ && self.retained.projection.is_at_generation(&last.projection))
+ .then_some(last.needs_style_state)
+ }
+
+ /// The cursor facts built last, where nothing they read moved since.
+ pub(in super::super) fn memoized_hover_cursor_facts(
+ &self,
+ ) -> Option<Arc<super::super::hover_lane::HoverCursorFacts>> {
+ let last = self.host.hover_seal.cursor_facts.as_ref()?;
+ (last.dom_paint_facts_version == self.tree().dom_paint_facts_version()
+ && last.installed_column_version == self.computed_group_sets.installed_column_version()
+ && self.retained.projection.is_at_generation(&last.projection))
+ .then(|| last.facts.clone())
+ }
+
+ /// The editable elements as they stand, shared with the cursor facts published last while the tree's paint facts
+ /// did not move.
+ pub(in super::super) fn hover_editable_nodes(&self) -> Arc<FastSet<StyleNodeID>> {
+ match &self.host.hover_seal.cursor_facts {
+ Some(last) if last.dom_paint_facts_version == self.tree().dom_paint_facts_version() => {
+ last.editable.clone()
+ }
+ _ => Arc::new(self.tree().editable_nodes().collect()),
+ }
+ }
+
+ /// Keep `facts`, the cursor facts as they stand, with what they read.
+ pub(in super::super) fn memoize_hover_cursor_facts(
+ &mut self,
+ facts: Arc<super::super::hover_lane::HoverCursorFacts>,
+ ) {
+ self.host.hover_seal.cursor_facts = Some(HoverCursorFactsAnswer {
+ projection: self.retained.projection.generation(),
+ dom_paint_facts_version: self.tree().dom_paint_facts_version(),
+ installed_column_version: self.computed_group_sets.installed_column_version(),
+ editable: facts.editable(),
+ facts,
+ });
+ }
+
+ /// Keep `needs_style_state`, the hover seal's answer for `root`, with what it read.
+ pub(in super::super) fn memoize_hover_seal(&mut self, root: StyleNodeID, needs_style_state: bool) {
+ self.host.hover_seal.last = Some(HoverSealAnswer {
+ projection: self.retained.projection.generation(),
+ dom_order_version: self.tree().dom_order_version(),
+ invalidation: self.hover_seal_invalidation().cloned(),
+ root,
+ needs_style_state,
+ });
+ }
+
+ /// The engine of the document and its invalidation map, where the map describes the
+ /// rules and elements as they stand.
+ fn current_invalidation(&self) -> Option<(&Live, &InvalidationMap)> {
+ let live = self.retained.live_style.as_deref()?;
+ let map = live.current_invalidation()?;
+ Some((live, map))
+ }
+
+ /// Whether settling the pending element inputs may move layout geometry: those the projection
+ /// holds no row for always may, and so may a change made to
+ /// the projection since the last barrier or geometry read seal that does by
+ /// [`Self::change_may_affect_layout_geometry`].
+ pub(in super::super) fn pending_inputs_may_affect_layout_geometry(&self) -> bool {
+ if !self.host.element_inputs.is_empty() {
+ return true;
+ }
+ let current = self.current_invalidation();
+ self.retained.projection.any_change_since_seal(|node, change| {
+ current.is_none_or(|(live, map)| self.change_may_affect_layout_geometry(live, map, node, change))
+ })
+ }
+
+ /// Whether settling `change`, a pending change to one element's facts or relations, may move
+ /// layout geometry: whether the elements it restyles may come to match, or stop matching, a
+ /// rule that may move geometry, or substitute the element's attributes.
+ fn change_may_affect_layout_geometry(
+ &self,
+ live: &Live,
+ map: &InvalidationMap,
+ node: StyleNodeID,
+ change: ElementChange,
+ ) -> bool {
+ let program = &self.retained.rules;
+ let rule_moves = |entry: u32| program.rule_may_affect_layout_geometry(live.index.rule_of(entry));
+ let moves = |trigger: Trigger| {
+ map.effects(&trigger).any(|effect| rule_moves(effect.entry))
+ || map.lone_entries(&trigger).any(rule_moves)
+ || map
+ .queries_testing(&trigger)
+ .any(|(query, _)| rule_moves(map.relative_entry(query)))
+ };
+ let feature = match change {
+ ElementChange::State(fact) => return moves(Trigger::State(fact)),
+ ElementChange::Id(old, new) => {
+ return [old, new].into_iter().any(|id| !id.is_none() && moves(Trigger::Id(id)));
+ }
+ ElementChange::Feature(feature) => feature,
+ ElementChange::Relations(..) | ElementChange::ArrivingFacts => return true,
+ };
+ match feature {
+ LocalFeatureKey::Class(class) => moves(Trigger::Class(class)),
+ LocalFeatureKey::Attribute(name) => {
+ self.retained
+ .projection
+ .attribute_name_keys(name)
+ .into_iter()
+ .any(|name| !name.is_none() && moves(Trigger::Attribute(name)))
+ // https://drafts.csswg.org/css-values-5/#attr-notation
+ || std::iter::once(node)
+ .chain(self.retained.backing_elements(node, u64::MAX))
+ .any(|reader| {
+ live.records.get(reader).is_some_and(|record| record.rare().reads.reads_attributes)
+ || live
+ .records
+ .pseudo_element_records(reader)
+ .iter()
+ .any(|(_, record)| record.rare().reads.reads_attributes)
+ })
+ }
+ LocalFeatureKey::CustomState(state) => moves(Trigger::CustomState(state)),
+ LocalFeatureKey::Emptiness => moves(Trigger::Emptiness),
+ LocalFeatureKey::Language => moves(Trigger::Language),
+ LocalFeatureKey::Directionality => moves(Trigger::Directionality),
+ LocalFeatureKey::HeadingLevel => moves(Trigger::Heading),
+ LocalFeatureKey::Part(part) => moves(Trigger::Part(part)),
+ LocalFeatureKey::Id
+ | LocalFeatureKey::PartExposure
+ | LocalFeatureKey::TagName
+ | LocalFeatureKey::FoldedTagName => true,
+ }
+ }
+
+ /// Whether a hover under `root` needs the style engine: whether an element in its shadow-including subtree is a
+ /// disabled control, or may come to match, or stop matching, a compound testing `:hover`. Reads again only the
+ /// rows written since the last answer, where the rules are the same.
+ pub(in super::super) fn hover_seal_needs_style_state(&mut self, root: StyleNodeID) -> bool {
+ self.update_hover_seal_candidates();
+ let candidates = self
+ .host
+ .hover_seal
+ .candidates
+ .as_ref()
+ .expect("the hover seal's candidates were just read");
+ let projection = &self.retained.projection;
+ let tree = self.tree();
+ let under_root =
+ |node: &StyleNodeID| tree.is_live(*node) && projection.is_in_shadow_including_subtree_of(*node, root);
+ candidates.disabled.iter().any(under_root)
+ || match &candidates.hover_keyed {
+ HoverKeyedElements::Every => true,
+ HoverKeyedElements::Carrying(elements) => elements.iter().any(under_root),
+ }
+ }
+
+ /// Bring the hover seal's candidates up to the rows as they stand: read the rows written since they were read
+ /// last, or every row where there are none yet, or the rules moved.
+ fn update_hover_seal_candidates(&mut self) {
+ if self.host.hover_seal.candidates.as_ref().is_some_and(|candidates| {
+ self.retained.projection.is_at_generation(&candidates.projection)
+ && same_map(candidates.invalidation.as_ref(), self.hover_seal_invalidation())
+ }) {
+ return;
+ }
+ let generation = self.retained.projection.generation();
+ let invalidation = self.hover_seal_invalidation().cloned();
+ let (mut candidates, first_read) = match self.host.hover_seal.candidates.take() {
+ Some(candidates) => (candidates, false),
+ None => (
+ HoverSealCandidates {
+ projection: generation.clone(),
+ invalidation: None,
+ disabled: FastSet::default(),
+ hover_keyed: HoverKeyedElements::Every,
+ },
+ true,
+ ),
+ };
+ let projection = &self.retained.projection;
+ let every_slot: Vec<_> = std::iter::once(0..projection.element_slot_count()).collect();
+ let element_at = |slot: usize| StyleNodeID::element(u32::try_from(slot).expect("element slot exceeds u32"));
+ let disabled_slots = match first_read {
+ true => every_slot.clone(),
+ false => generation.written_slots_changed_since(&candidates.projection),
+ };
+ for node in disabled_slots
+ .into_iter()
+ .flatten()
+ .filter(|&slot| slot != 0)
+ .map(element_at)
+ {
+ if projection
+ .written_facts(node)
+ .is_some_and(|facts| facts.states().contains(StateFact::Disabled))
+ {
+ candidates.disabled.insert(node);
+ } else {
+ candidates.disabled.remove(&node);
+ }
+ }
+ let hover = Trigger::State(StateFact::Hover);
+ candidates.hover_keyed = match self.current_invalidation() {
+ Some((live, map)) if map.queries_testing(&hover).next().is_none() => {
+ let rules_moved = first_read || !same_map(candidates.invalidation.as_ref(), invalidation.as_ref());
+ let (mut elements, keyed_slots) =
+ match std::mem::replace(&mut candidates.hover_keyed, HoverKeyedElements::Every) {
+ HoverKeyedElements::Carrying(elements) if !rules_moved => (
+ elements,
+ generation.committed_slots_changed_since(&candidates.projection),
+ ),
+ _ => (FastSet::default(), every_slot),
+ };
+ if map.has_effects(&hover) {
+ for node in keyed_slots
+ .into_iter()
+ .flatten()
+ .filter(|&slot| slot != 0)
+ .map(element_at)
+ {
+ let carries_keys = projection.row_of(node).is_some_and(|row| {
+ map.effects(&hover)
+ .any(|effect| map.may_match_by_keys(&live.index, effect, row))
+ });
+ if carries_keys {
+ elements.insert(node);
+ } else {
+ elements.remove(&node);
+ }
+ }
+ } else {
+ elements.clear();
+ }
+ HoverKeyedElements::Carrying(elements)
+ }
+ _ => HoverKeyedElements::Every,
+ };
+ candidates.projection = generation;
+ candidates.invalidation = invalidation;
+ self.host.hover_seal.candidates = Some(candidates);
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::super::test_support::{
+ add_class, add_rules, add_sheet, linear_document, remove_class, set_tag, start_live,
+ };
+ use super::*;
+
+ fn document_with_rules(source: &str) -> (StyleEngine, Vec<StyleNodeID>) {
+ let (mut engine, nodes) = linear_document();
+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);
+ add_rules(&mut engine, sheet, source);
+ start_live(&mut engine, nodes[0]);
+ (engine, nodes)
+ }
+
+ #[test]
+ fn only_inputs_reaching_rules_that_move_geometry_may_affect_layout_geometry() {
+ let (mut engine, nodes) = document_with_rules(
+ ".paint { background-color: green; } .wide > * { width: 10px; } .moved { transform: scale(2); }",
+ );
+ add_class(&mut engine, nodes[1], "paint");
+ add_class(&mut engine, nodes[2], "unstyled");
+ assert!(engine.has_pending_transaction());
+ assert!(!engine.pending_transaction_may_affect_layout_geometry());
+
+ add_class(&mut engine, nodes[0], "wide");
+ assert!(engine.pending_transaction_may_affect_layout_geometry());
+
+ let (mut engine, nodes) = document_with_rules(".moved { transform: scale(2); }");
+ add_class(&mut engine, nodes[3], "moved");
+ assert!(engine.pending_transaction_may_affect_layout_geometry());
+ }
+
+ #[test]
+ fn inputs_a_has_argument_reads_may_affect_layout_geometry_through_its_anchor() {
+ let (mut engine, nodes) = document_with_rules(".anchor:has(.inner) { width: 1px; }");
+ add_class(&mut engine, nodes[2], "inner");
+ assert!(engine.pending_transaction_may_affect_layout_geometry());
+
+ let (mut engine, nodes) = document_with_rules(".anchor:has(.inner) { background-color: green; }");
+ add_class(&mut engine, nodes[2], "inner");
+ assert!(!engine.pending_transaction_may_affect_layout_geometry());
+ }
+
+ #[test]
+ fn hover_restyles_only_where_an_element_may_match_a_hover_compound() {
+ let (mut engine, nodes) = document_with_rules(".menu:hover .item { color: red; }");
+ assert!(!engine.hover_needs_style_state(nodes[0]));
+
+ add_class(&mut engine, nodes[1], "menu");
+ start_live(&mut engine, nodes[0]);
+ assert!(engine.hover_needs_style_state(nodes[0]));
+
+ let (mut engine, nodes) = document_with_rules(":is(button, .action):hover { color: red; }");
+ assert!(!engine.hover_needs_style_state(nodes[0]));
+ set_tag(&mut engine, nodes[2], "button");
+ start_live(&mut engine, nodes[0]);
+ assert!(engine.hover_needs_style_state(nodes[0]));
+ }
+
+ #[test]
+ fn hover_restyles_through_a_type_selector_in_any_case() {
+ let (mut engine, nodes) = document_with_rules("A:hover { color: red; }");
+ assert!(!engine.hover_needs_style_state(nodes[0]));
+ set_tag(&mut engine, nodes[2], "a");
+ start_live(&mut engine, nodes[0]);
+ assert!(engine.hover_needs_style_state(nodes[0]));
+ }
+
+ #[test]
+ fn hover_restyles_through_what_no_compound_of_its_own_tests() {
+ let (mut engine, nodes) = document_with_rules(":nth-child(1 of :hover) { color: red; }");
+ assert!(engine.hover_needs_style_state(nodes[0]));
+ }
+
+ #[test]
+ fn hover_restyles_a_backed_pseudo_element_only_through_the_element_backing_it() {
+ let (mut engine, nodes) = document_with_rules("input::file-selector-button:hover { color: red; }");
+ assert!(!engine.hover_needs_style_state(nodes[0]));
+ }
+
+ #[test]
+ fn a_hover_seal_follows_the_rows_written_since_it_answered() {
+ let (mut engine, nodes) = document_with_rules(".menu:hover { color: red; }");
+ assert!(!engine.hover_needs_style_state(nodes[0]));
+ add_class(&mut engine, nodes[2], "menu");
+ start_live(&mut engine, nodes[0]);
+ assert!(engine.hover_needs_style_state(nodes[0]));
+ assert!(!engine.hover_needs_style_state(nodes[3]));
+ remove_class(&mut engine, nodes[2], "menu");
+ start_live(&mut engine, nodes[0]);
+ assert!(!engine.hover_needs_style_state(nodes[0]));
+ add_class(&mut engine, nodes[3], "menu");
+ start_live(&mut engine, nodes[0]);
+ assert!(engine.hover_needs_style_state(nodes[3]));
+ assert!(engine.hover_needs_style_state(nodes[0]));
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/projection.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/projection.rs
new file mode 100644
index 00000000000..1824c7c44b7
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/projection.rs
@@ -0,0 +1,2936 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The document as the engine reads it: each element's local facts and the links between elements,
+//! projected from the writes the host makes, in the order it makes them.
+//!
+//! One row holds everything style reads of one element, addressed by its element slot, so reading
+//! an element's facts and following a link out of it are one lookup each. Rows live in a
+//! [`CowColumn`]: a fork shares every chunk of rows and copies one only when it writes there, and
+//! the variable-length facts of a row are `Arc` slices, which a copied chunk shares in turn. The
+//! catalogs keyed by atom (attribute name forms and the texts of values and languages) belong to
+//! the document rather than to an element and are shared the same way.
+//!
+//! A row's facts and its links have lifetimes of their own. An element's links are reset when its
+//! identity is minted and when it retires, as the tree changes; its facts exist from the first one
+//! published until the element is forgotten at the end of the transaction it departed in, so that
+//! invalidation can still read the facts of an element that left.
+//!
+//! Facts are written as their inputs arrive, ahead of the transaction they join, but style reads
+//! them as the last transaction committed them: the projection publishes its rows at each
+//! transaction barrier, and the facts readers see are those of that committed generation. An
+//! element's links are read the same way; the shadow relations are read as written, as the host's
+//! shadow tree changes between barriers are. While a transaction is
+//! taken, the generation committed before it stays at hand too: the side of the transaction from
+//! before it, which invalidation compares the elements' facts and relations against.
+
+mod fact_lists;
+pub(in crate::css::style) use fact_lists::{FactListsIdentity, FactListsTable};
+mod tree_reads;
+mod writer;
+
+use super::super::element_host_facts::HostFactSet;
+use super::super::element_host_facts::HostFactSetID;
+use super::super::element_host_facts::HostFactSets;
+use super::super::fast_hash::FastMap as HashMap;
+use super::super::fast_hash::FastSet as HashSet;
+use super::super::index::AttributeFact;
+use super::super::index::AttributeNameForms;
+use super::super::index::DispatchKey;
+use super::super::index::LocalFeatureKey;
+use super::super::index::StateSet;
+use super::super::index::StyleAtomID;
+use super::super::index::dispatch_bloom_bit;
+use super::super::input_types::StateFact;
+use super::super::input_types::TreeRelations;
+use super::super::selector::Incomplete;
+use super::super::selector::MatchScratch;
+use super::super::selector::NthPosition;
+use super::super::selector::PositionalIndexPolicy;
+use super::super::selector::RelativeAnswerKey;
+use super::super::selector::SiblingAnswerKey;
+use super::super::selector::SiblingAnswerTable;
+use super::super::selector::SiblingSequenceSource;
+use super::super::selector_evaluation::ElementFeatures;
+use super::super::selector_evaluation::SelectorBindings;
+use super::super::selector_evaluation::SelectorEvaluator;
+use super::super::selector_evaluation::SelectorSubject;
+use super::super::selector_evaluation::SelectorTree;
+use super::super::selector_evaluation::StructuralRead;
+use super::super::transaction_view::TransactionFactSide;
+use super::super::tree::StyleNodeID;
+use super::super::tree::TreeScopeID;
+use crate::cow_column::ColumnSnapshot;
+use crate::cow_column::CowColumn;
+use crate::css::css_tokenizer::TokenizerInput;
+use crate::css::retained_fly_string::RetainedUtf16FlyString;
+use fact_lists::FactLists;
+use fact_lists::FactListsEdit;
+use smallvec::SmallVec;
+use std::sync::Arc;
+use std::sync::atomic::AtomicU8;
+use std::sync::atomic::AtomicU32;
+use std::sync::atomic::Ordering;
+pub(in crate::css::style) use writer::ProjectionPublication;
+pub(in crate::css::style) use writer::ProjectionWriter;
+
+/// How many rows a chunk of the projection holds, and so how many rows the first write after a fork
+/// copies.
+const ROWS_PER_CHUNK: usize = 64;
+
+/// A set of elements whose rows were written, each listed once, with a bit per element slot saying
+/// which.
+#[derive(Clone, Default)]
+struct WrittenRows {
+ nodes: Vec<StyleNodeID>,
+ bits: Vec<u64>,
+}
+
+impl WrittenRows {
+ /// Add an element, saying whether it was not in the set yet.
+ fn insert(&mut self, node: StyleNodeID, slot: usize) -> bool {
+ let (word, bit) = (slot / 64, 1_u64 << (slot % 64));
+ if word >= self.bits.len() {
+ self.bits.resize(word + 1, 0);
+ }
+ if self.bits[word] & bit != 0 {
+ return false;
+ }
+ self.bits[word] |= bit;
+ self.nodes.push(node);
+ true
+ }
+
+ fn contains(&self, slot: usize) -> bool {
+ self.bits
+ .get(slot / 64)
+ .is_some_and(|word| word & (1_u64 << (slot % 64)) != 0)
+ }
+
+ /// Take the elements out, leaving the set empty.
+ fn take(&mut self) -> Vec<StyleNodeID> {
+ let nodes = std::mem::take(&mut self.nodes);
+ for node in &nodes {
+ let slot = node.element_slot();
+ self.bits[slot / 64] &= !(1_u64 << (slot % 64));
+ }
+ nodes
+ }
+
+ /// Empty the set, keeping `nodes`, taken from it, as its allocation.
+ fn reuse(&mut self, mut nodes: Vec<StyleNodeID>) {
+ debug_assert!(self.nodes.is_empty());
+ nodes.clear();
+ self.nodes = nodes;
+ }
+}
+
+/// The elements written since the last barrier, in the order of their writes, once per write, of which the first
+/// `checked` were found to leave their rows as the committed generation has them, until written again.
+#[derive(Default)]
+struct PendingChangeScan {
+ writes: Vec<StyleNodeID>,
+ checked: std::sync::atomic::AtomicUsize,
+}
+
+impl Clone for PendingChangeScan {
+ fn clone(&self) -> Self {
+ Self {
+ writes: self.writes.clone(),
+ checked: self.checked.load(std::sync::atomic::Ordering::Relaxed).into(),
+ }
+ }
+}
+
+impl PendingChangeScan {
+ fn clear(&mut self) {
+ self.writes.clear();
+ *self.checked.get_mut() = 0;
+ }
+
+ fn heap_size(&self) -> usize {
+ crate::heap_size::vec_bytes(&self.writes)
+ }
+}
+
+/// A list of atoms or pairs a row holds, shared by every copy of the row. An empty one holds no
+/// allocation.
+#[derive(Clone, PartialEq)]
+struct SharedList<T>(Option<Arc<[T]>>);
+
+impl<T> Default for SharedList<T> {
+ fn default() -> Self {
+ Self(None)
+ }
+}
+
+impl<T: Clone> SharedList<T> {
+ fn new(values: &[T]) -> Self {
+ Self((!values.is_empty()).then(|| values.into()))
+ }
+
+ fn as_slice(&self) -> &[T] {
+ self.0.as_deref().unwrap_or_default()
+ }
+}
+
+/// What one element publishes of itself, which its selectors test.
+#[derive(Clone, Default, PartialEq)]
+pub(in crate::css::style) struct ElementFacts {
+ tag: StyleAtomID,
+ /// The `ElementFacts::RESIDENT` and the other flags.
+ flags: u8,
+ /// The element's heading level, 1 to 9, or zero where it is not a heading.
+ heading_level: u8,
+ /// The identity of the set of facts the host publishes of the element beside the ones its selectors test, among
+ /// the document's sets: what its box and its style adjustments read of it, and the element-backed pseudo-element
+ /// of its shadow host it stands for.
+ host_facts: HostFactSetID,
+ states: StateSet,
+ /// The element's id, namespace, language, directionality, tree scope and assigned slot, and its
+ /// classes, attributes, parts and custom states, with its folded tag and part exposure, interned
+ /// by content.
+ lists: FactLists,
+ /// A Bloom summary of the dispatch keys the element carries, document-root status aside: those
+ /// its lists summarize, and its own. Kept beside the facts, as an ancestor walk reads it for
+ /// every ancestor and the lists may be a cache miss away.
+ dispatch_bloom: u64,
+}
+
+const _: () = assert!(size_of::<ElementFacts>() == 32);
+
+impl ElementFacts {
+ /// Whether anything was published about the element, or it is a shadow root standing in the
+ /// tree. An element without facts is one the projection cannot answer for, which is not the same
+ /// as an element that has none.
+ const RESIDENT: u8 = 1 << 0;
+ /// Whether a text or comment child keeps the element from being `:empty`.
+ const HAS_TEXT_CONTENT: u8 = 1 << 1;
+ /// Whether the element is a `<slot>`. A slot inside a shadow tree is not itself a flattened
+ /// slottable, so `::slotted()` never names one even when its assignment carries a chain onward.
+ const IS_SLOT: u8 = 1 << 2;
+ /// Whether the row's identity is live, which belongs to its links rather than its facts and is
+ /// kept here where the row has room for it.
+ const LIVE: u8 = 1 << 3;
+ /// Whether the element stands in a tree: it was inserted and has not left. An identity is
+ /// minted as its node arrives, before its relations are published. Like `LIVE`, of its links.
+ const CONNECTED: u8 = 1 << 4;
+
+ fn flag(&self, flag: u8) -> bool {
+ self.flags & flag != 0
+ }
+
+ fn set_flag(&mut self, flag: u8, value: bool) {
+ match value {
+ true => self.flags |= flag,
+ false => self.flags &= !flag,
+ }
+ }
+
+ fn resident(&self) -> bool {
+ self.flag(Self::RESIDENT)
+ }
+
+ /// Whether the two say the same of their elements, leaving aside what they keep of their links: whether the
+ /// identity is live and stands in a tree, its tree scope and its assigned slot.
+ fn says_the_same_as(&self, other: &Self) -> bool {
+ const LINK_FLAGS: u8 = ElementFacts::LIVE | ElementFacts::CONNECTED;
+ self.tag == other.tag
+ && self.flags & !LINK_FLAGS == other.flags & !LINK_FLAGS
+ && self.heading_level == other.heading_level
+ && self.host_facts == other.host_facts
+ && self.states == other.states
+ && self.lists.says_the_same_as(&other.lists)
+ }
+
+ /// Summarizes the dispatch keys the element carries again: those of its lists, which the lists summarize where they
+ /// are made, and its own few.
+ fn refresh_dispatch_bloom(&mut self) {
+ let mut bloom = self.lists.bloom()
+ | dispatch_bloom_bit(DispatchKey::Universal)
+ | dispatch_bloom_bit(DispatchKey::TagName(self.tag));
+ if self.heading_level() != 0 {
+ bloom |= dispatch_bloom_bit(DispatchKey::Heading);
+ }
+ for fact in self.states.facts() {
+ bloom |= dispatch_bloom_bit(DispatchKey::State(fact));
+ }
+ self.dispatch_bloom = bloom;
+ }
+
+ /// The facts the element is left with once they are forgotten: none, but what they keep of its links, and the host
+ /// facts, which the element keeps until its identity is minted again, for what reads the departed element.
+ fn forgotten(&self) -> Self {
+ Self {
+ flags: self.flags & (Self::LIVE | Self::CONNECTED),
+ host_facts: self.host_facts,
+ ..Self::default()
+ }
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn tag(&self) -> StyleAtomID {
+ self.tag
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn namespace(&self) -> StyleAtomID {
+ self.lists.namespace()
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn id(&self) -> StyleAtomID {
+ self.lists.id()
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn states(&self) -> StateSet {
+ self.states
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn language(&self) -> StyleAtomID {
+ self.lists.language()
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn directionality(&self) -> StyleAtomID {
+ self.lists.directionality()
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn part_exposure(&self) -> StyleAtomID {
+ self.lists.part_exposure()
+ }
+
+ /// The ASCII-lowercase folding of the element's tag, where it differs from it.
+ #[must_use]
+ pub(in crate::css::style) fn folded_tag(&self) -> StyleAtomID {
+ self.lists.folded_tag()
+ }
+
+ /// What is equal between two elements only if their lists are the same ones, and so everything
+ /// they hold is: for as long as both stand in rows.
+ #[must_use]
+ pub(in crate::css::style) fn lists_identity(&self) -> FactListsIdentity {
+ self.lists.identity()
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn heading_level(&self) -> u8 {
+ self.heading_level
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn is_slot(&self) -> bool {
+ self.flag(Self::IS_SLOT)
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn has_text_content(&self) -> bool {
+ self.flag(Self::HAS_TEXT_CONTENT)
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn classes(&self) -> &[StyleAtomID] {
+ self.lists.classes()
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn attributes(&self) -> &[AttributeFact] {
+ self.lists.attributes()
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn parts(&self) -> &[StyleAtomID] {
+ self.lists.parts()
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn custom_states(&self) -> &[StyleAtomID] {
+ self.lists.custom_states()
+ }
+
+ /// The Bloom summary of the dispatch keys the element carries.
+ #[must_use]
+ pub(in crate::css::style) fn dispatch_bloom(&self, is_document_root: bool) -> u64 {
+ self.dispatch_bloom
+ | match is_document_root {
+ true => dispatch_bloom_bit(DispatchKey::Root),
+ false => 0,
+ }
+ }
+}
+
+/// How one element stands in the tree. Its tree scope and assigned slot are held in its fact lists,
+/// and whether it is live and connected in its facts' flags, so that a row is 48 bytes.
+#[derive(Clone, Default, PartialEq)]
+struct Links {
+ parent: Option<StyleNodeID>,
+ first_element_child: Option<StyleNodeID>,
+ previous_element_sibling: Option<StyleNodeID>,
+ next_element_sibling: Option<StyleNodeID>,
+}
+
+const _: () = assert!(size_of::<Links>() == 16);
+
+/// The shadow relations of an element, which few elements have.
+#[derive(Clone, Default, PartialEq)]
+struct ShadowLinks {
+ /// A shadow host's shadow root.
+ shadow_root: Option<StyleNodeID>,
+ /// A shadow root's host.
+ host: Option<StyleNodeID>,
+ /// A slot's assigned nodes, text nodes included, in the order the DOM assigned them.
+ assigned_nodes: SharedList<StyleNodeID>,
+ /// Every part name the element is addressable by, each with the host of the level that name
+ /// reaches.
+ part_hosts: SharedList<(StyleAtomID, StyleNodeID)>,
+}
+
+#[derive(Clone, Default, PartialEq)]
+struct Row {
+ facts: ElementFacts,
+ links: Links,
+}
+
+const _: () = assert!(size_of::<Row>() == 48);
+
+/// The shadow relations of the elements by slot, in a column of their own that is made only as far as the last element
+/// holding any: most documents have none, and most elements of those that do hold none either.
+type ShadowColumn = CowColumn<Option<Arc<ShadowLinks>>, ROWS_PER_CHUNK>;
+type ShadowSnapshot = ColumnSnapshot<Option<Arc<ShadowLinks>>, ROWS_PER_CHUNK>;
+
+fn shadow_links_heap_size(shadow: Option<&Arc<ShadowLinks>>, sizer: &mut crate::heap_size::HeapSizer) -> usize {
+ shadow.map_or(0, |shadow| {
+ if !sizer.first_sight(Arc::as_ptr(shadow)) {
+ return 0;
+ }
+ crate::heap_size::ARC_HEADER_BYTES
+ + size_of::<ShadowLinks>()
+ + shadow.assigned_nodes.heap_size(sizer)
+ + shadow.part_hosts.heap_size(sizer)
+ })
+}
+
+impl Row {
+ /// Whether the row's element identity is live: minted and not retired.
+ fn live(&self) -> bool {
+ self.facts.flag(ElementFacts::LIVE)
+ }
+
+ /// Whether the row's element stands in a tree.
+ fn connected(&self) -> bool {
+ self.facts.flag(ElementFacts::CONNECTED)
+ }
+}
+
+/// What a document's atoms spell, for the tests and substitutions that compare text.
+#[derive(Clone, Default)]
+struct Catalogs {
+ name_forms: Catalog<AttributeNameForms>,
+ /// The local name an `attr()` reads an attribute in no namespace by.
+ substitution_names: Catalog<Box<[u16]>>,
+ /// What attribute-value atoms spell: the host's own string, which the document's attribute
+ /// holds as well, shared by reference.
+ value_texts: Catalog<RetainedUtf16FlyString>,
+ language_texts: Catalog<Box<[u16]>>,
+}
+
+/// A catalog the writer adds to between publications, which every publication shares: a large base and the small part
+/// added since the base was last folded, so that an addition after a publication copies only the small part. The part
+/// is folded into the base once it grows past an eighth of it.
+#[derive(Clone)]
+struct Catalog<T> {
+ base: Arc<HashMap<StyleAtomID, T>>,
+ recent: Arc<HashMap<StyleAtomID, T>>,
+ /// How many entries additions copied, for a test.
+ #[cfg(test)]
+ copied: usize,
+}
+
+impl<T> Default for Catalog<T> {
+ fn default() -> Self {
+ Self {
+ base: Arc::default(),
+ recent: Arc::default(),
+ #[cfg(test)]
+ copied: 0,
+ }
+ }
+}
+
+impl<T: Clone> Catalog<T> {
+ fn get(&self, atom: &StyleAtomID) -> Option<&T> {
+ self.recent.get(atom).or_else(|| self.base.get(atom))
+ }
+
+ fn contains_key(&self, atom: &StyleAtomID) -> bool {
+ self.get(atom).is_some()
+ }
+
+ /// Every entry, once, the recent spelling of an atom standing for the one in the base.
+ fn iter(&self) -> impl Iterator<Item = (&StyleAtomID, &T)> {
+ self.recent
+ .iter()
+ .chain(self.base.iter().filter(|(atom, _)| !self.recent.contains_key(atom)))
+ }
+
+ /// Notes, for a test, how many entries writing `map` now copies.
+ #[cfg(test)]
+ fn note_copy(copied: &mut usize, map: &Arc<HashMap<StyleAtomID, T>>) {
+ if Arc::strong_count(map) > 1 {
+ *copied += map.len();
+ }
+ }
+
+ fn insert(&mut self, atom: StyleAtomID, value: T) {
+ #[cfg(test)]
+ Self::note_copy(&mut self.copied, &self.recent);
+ Arc::make_mut(&mut self.recent).insert(atom, value);
+ if self.recent.len() > self.base.len() / 8 + 64 {
+ #[cfg(test)]
+ Self::note_copy(&mut self.copied, &self.base);
+ let recent = std::mem::take(&mut self.recent);
+ let base = Arc::make_mut(&mut self.base);
+ match Arc::try_unwrap(recent) {
+ Ok(recent) => base.extend(recent),
+ Err(recent) => base.extend(recent.iter().map(|(atom, value)| (*atom, value.clone()))),
+ }
+ }
+ }
+
+ /// Drops whatever the catalog holds of `atoms`.
+ fn forget(&mut self, atoms: &[StyleAtomID]) {
+ for map in [&mut self.base, &mut self.recent] {
+ if atoms.iter().any(|atom| map.contains_key(atom)) {
+ let map = Arc::make_mut(map);
+ for atom in atoms {
+ map.remove(atom);
+ }
+ }
+ }
+ }
+
+ /// The bytes of the catalog's maps that `sizer` reaches for the first time.
+ fn heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {
+ [&self.base, &self.recent]
+ .into_iter()
+ .map(|map| sizer.arc_shallow(map) + crate::heap_size::map_bytes(map))
+ .sum()
+ }
+
+ fn values(&self) -> impl Iterator<Item = &T> {
+ self.iter().map(|(_, value)| value)
+ }
+}
+
+/// The elements that match `:hover`, which the render owner places as the pointer moves rather than the host writes:
+/// a small overlay over the rows, holding the hover chain as placed, and for each generation style reads the hovered
+/// elements' facts with the hover fact set. A fork carries it whole, as it is the size of one chain.
+#[derive(Clone, Default)]
+struct HoverOverlay {
+ /// The chain as last placed, which the next transaction takes.
+ placed: SmallVec<[StyleNodeID; 16]>,
+ committed: HoveredFacts,
+ before: HoveredFacts,
+ /// The chain as the latest geometry read sealed it, beside the sealed rows.
+ sealed: Option<SmallVec<[StyleNodeID; 16]>>,
+}
+
+/// The facts of the hovered elements of one generation, the hover fact set, which stand in for their rows' facts.
+#[derive(Clone, Default)]
+struct HoveredFacts {
+ facts: Vec<(StyleNodeID, ElementFacts)>,
+ /// A bit per element slot modulo 64, which rules out most elements without a search.
+ slots: u64,
+}
+
+impl HoveredFacts {
+ /// The hovered elements of `chain` that `generation` holds facts of, with the hover fact set.
+ fn of(chain: &[StyleNodeID], generation: &ColumnSnapshot<Row, ROWS_PER_CHUNK>) -> Self {
+ let mut hovered = Self::default();
+ for &node in chain {
+ let Some(row) = generation.get(node.element_slot()).filter(|row| row.facts.resident()) else {
+ continue;
+ };
+ let mut facts = row.facts.clone();
+ facts.states.insert(StateFact::Hover);
+ facts.refresh_dispatch_bloom();
+ hovered.slots |= 1 << (node.element_slot() % 64);
+ hovered.facts.push((node, facts));
+ }
+ hovered
+ }
+
+ #[inline]
+ fn get(&self, node: StyleNodeID) -> Option<&ElementFacts> {
+ if self.slots & (1 << (node.element_slot() % 64)) == 0 {
+ return None;
+ }
+ self.facts
+ .iter()
+ .find_map(|(hovered, facts)| (*hovered == node).then_some(facts))
+ }
+
+ fn contains(&self, node: StyleNodeID) -> bool {
+ self.get(node).is_some()
+ }
+}
+
+/// The generations a [`Projection`] reads its facts, links and shadow relations from, held so that
+/// no later generation takes their place in memory while a memo compares against them.
+#[derive(Clone)]
+pub(in crate::css::style) struct ProjectionGeneration {
+ rows: ColumnSnapshot<Row, ROWS_PER_CHUNK>,
+ committed: ColumnSnapshot<Row, ROWS_PER_CHUNK>,
+ shadows: ShadowSnapshot,
+}
+
+impl ProjectionGeneration {
+ /// The element `node` inherits from in this generation, as [`Projection::inheritance_parent`] answers for an
+ /// element.
+ pub(in crate::css::style) fn element_inheritance_parent(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ let row = self.committed.get(node.element_slot())?;
+ if let Some(slot) = row.facts.lists.assigned_slot() {
+ return Some(slot);
+ }
+ let parent = row.links.parent?;
+ let host = self
+ .shadows
+ .get(parent.element_slot())?
+ .as_deref()
+ .and_then(|shadow| shadow.host);
+ Some(host.unwrap_or(parent))
+ }
+
+ /// The element slots whose written rows may differ between `older` and this generation.
+ pub(in crate::css::style) fn written_slots_changed_since(&self, older: &Self) -> Vec<std::ops::Range<usize>> {
+ self.rows.changed_rows_since(&older.rows)
+ }
+
+ /// The element slots whose committed rows may differ between `older` and this generation.
+ pub(in crate::css::style) fn committed_slots_changed_since(&self, older: &Self) -> Vec<std::ops::Range<usize>> {
+ self.committed.changed_rows_since(&older.committed)
+ }
+}
+
+/// What the selectors matched against an element read of its children's places among their siblings, and of itself
+/// whether it is empty: the changes to its children that can move what they matched.
+#[derive(Clone, Copy, PartialEq, Eq, Default, Debug)]
+pub(in crate::css::style) struct StructuralFlags(u8);
+
+impl StructuralFlags {
+ /// A selector read a child's earlier siblings, across a `+` or a `~`, or rejected a child on what they carry.
+ pub(in crate::css::style) const CHILDREN_READ_SIBLINGS: Self = Self(1 << 0);
+ /// A selector read a child's previous sibling, across a `+`.
+ pub(in crate::css::style) const CHILDREN_READ_PREVIOUS_SIBLING: Self = Self(1 << 1);
+ /// A selector read where a child stands among its siblings.
+ pub(in crate::css::style) const CHILDREN_READ_POSITIONS: Self = Self(1 << 2);
+ /// A selector read whether the element is `:empty`.
+ pub(in crate::css::style) const READ_EMPTINESS: Self = Self(1 << 3);
+ /// The record of a child, or of a pseudo-element of it, computes from its place among its siblings.
+ pub(in crate::css::style) const CHILD_READS_SIBLING_POSITION: Self = Self(1 << 4);
+ /// A selector read where a child stands counted from the end.
+ pub(in crate::css::style) const CHILDREN_READ_POSITIONS_FROM_END: Self = Self(1 << 5);
+ /// A selector read where a child stands among those of its type.
+ pub(in crate::css::style) const CHILDREN_READ_POSITIONS_OF_TYPE: Self = Self(1 << 6);
+ /// A selector read more of where a child stands than whether it stands first, in the way it counts.
+ pub(in crate::css::style) const CHILDREN_READ_POSITIONS_BEYOND_EDGES: Self = Self(1 << 7);
+ const ALL: Self = Self(0xff);
+
+ #[must_use]
+ const fn union(self, other: Self) -> Self {
+ Self(self.0 | other.0)
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn contains(self, other: Self) -> bool {
+ self.0 & other.0 == other.0
+ }
+}
+
+/// The structural flags of the elements by slot, which selectors matched on any thread set, and which are never
+/// cleared while the element's records may hold what its children matched: a flag set for nothing only costs a
+/// change to the element's children the work it does without the flag.
+#[derive(Default)]
+struct StructuralFlagsColumn(Box<[AtomicU8]>);
+
+impl StructuralFlagsColumn {
+ /// The column for `slot_count` slots, holding what this one holds.
+ fn grown_to(&self, slot_count: usize) -> Self {
+ let length = slot_count.max(self.0.len().saturating_mul(2)).max(64);
+ Self(
+ (0..length)
+ .map(|slot| AtomicU8::new(self.0.get(slot).map_or(0, |flags| flags.load(Ordering::Relaxed))))
+ .collect(),
+ )
+ }
+}
+
+/// The projection of a document's elements that the style engine reads: the rows as the host last published them, which
+/// only the host's [`ProjectionWriter`] writes, with the generations transactions take of them.
+#[derive(Clone, Default)]
+pub(in crate::css::style) struct Projection {
+ /// The rows as the host last published them.
+ rows: ColumnSnapshot<Row, ROWS_PER_CHUNK>,
+ /// The elements' shadow relations as the host last published them, which are read as published.
+ shadows: ShadowSnapshot,
+ /// The rows as the last transaction published them, whose facts style reads. It shares every
+ /// chunk `rows` has not written since.
+ committed: ColumnSnapshot<Row, ROWS_PER_CHUNK>,
+ /// The rows as the transaction being taken found them, until it is released.
+ before: ColumnSnapshot<Row, ROWS_PER_CHUNK>,
+ /// One past the greatest element slot written.
+ slot_count: usize,
+ catalogs: Catalogs,
+ /// The distinct sets of host facts the rows name, as the host last published them.
+ host_fact_sets: Arc<HostFactSets>,
+ /// A slotted text node's slot. Text nodes have no rows, and a slotted one is rare.
+ text_assigned_slots: Arc<HashMap<StyleNodeID, StyleNodeID>>,
+ /// The elements whose rows the host's publications wrote since the last barrier.
+ written: WrittenRows,
+ /// Each write since the last barrier, which whether a written row changes the committed
+ /// generation is asked of at most once, as long as it is not written again.
+ pending_change_scan: PendingChangeScan,
+ /// The elements whose rows were written since the last barrier or geometry read seal, whichever
+ /// came last: those whose changes the pending transaction has not yet been asked about.
+ written_since_seal: WrittenRows,
+ /// The rows as the latest geometry read sealed them, where it sealed a change the next
+ /// transaction has yet to take: the style change event a geometry read established without
+ /// settling style. The transaction that flushes the seal takes these rows alone, and what was
+ /// written after the seal waits for the transaction after it.
+ sealed: Option<ColumnSnapshot<Row, ROWS_PER_CHUNK>>,
+ /// Whether the transaction being taken is the one that flushes the seal.
+ flushing_seal: bool,
+ /// What the transaction being taken changed, element by element, until it is released.
+ changes: Vec<(StyleNodeID, ElementChange)>,
+ /// The elements the render owner's hover places in the hover state, beside the rows.
+ hover: HoverOverlay,
+ /// The elements whose links were written since the last transaction was released: those the
+ /// tree has to settle at the next barrier, and those it settled at the barrier of the
+ /// transaction being taken.
+ links_written: WrittenRows,
+ /// Of those, the elements whose own relations were written, rather than only their first element
+ /// child: an element whose children arrive before it does stands in no tree yet, and has not left
+ /// one either.
+ relations_written: WrittenRows,
+ /// How many elements' links were written since the last transaction was released, which the
+ /// document's host reads: each may deepen the tree by a level once the tree settles it.
+ link_rows_written: Arc<AtomicU32>,
+ /// What the selectors matched against each element read of its structure, which matching on any thread sets.
+ /// A fork shares it, where what one side sets only costs the other the work a flag lets it skip.
+ structural_flags: Arc<StructuralFlagsColumn>,
+ /// The host's writer of a test, whose writes are published to the projection as they are made.
+ #[cfg(test)]
+ test_writer: Box<ProjectionWriter>,
+}
+
+/// Everything an element arrives with that its selectors test, which its row takes in one write.
+pub(in crate::css::style) struct ArrivalFacts<'a> {
+ pub tag: StyleAtomID,
+ /// The ASCII-lowercase folding of the tag, or the tag itself where folding leaves it as it is.
+ pub folded_tag: StyleAtomID,
+ pub namespace: StyleAtomID,
+ pub id: StyleAtomID,
+ pub language: StyleAtomID,
+ pub directionality: StyleAtomID,
+ pub heading_level: u8,
+ pub is_slot: bool,
+ pub has_text_content: bool,
+ pub states: StateSet,
+ pub classes: &'a [StyleAtomID],
+ pub attributes: &'a [AttributeFact],
+ pub custom_states: &'a [StyleAtomID],
+}
+
+/// What a transaction changed of one element: how the projection's side from before the
+/// transaction and the generation it committed differ there.
+#[derive(Clone, Copy, Debug, PartialEq, Eq)]
+pub(in crate::css::style) enum ElementChange {
+ /// The element's relations, before and now, none on a side where it stood in no tree.
+ Relations(Option<TreeRelations>, Option<TreeRelations>),
+ /// The element arrived with facts, which its arrival says all of.
+ ArrivingFacts,
+ /// One local fact of an element that stood where it was.
+ Feature(LocalFeatureKey),
+ /// The element's id, before and now.
+ Id(StyleAtomID, StyleAtomID),
+ State(StateFact),
+}
+
+impl<T> SharedList<T> {
+ fn heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {
+ self.0.as_ref().map_or(0, |list| sizer.arc_shallow(list))
+ }
+}
+
+impl Row {
+ fn heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {
+ self.facts.lists.heap_size(sizer)
+ }
+}
+
+impl WrittenRows {
+ fn heap_size(&self) -> usize {
+ crate::heap_size::vec_bytes(&self.nodes) + crate::heap_size::vec_bytes(&self.bits)
+ }
+}
+
+impl Projection {
+ /// Counts the rows of every generation the projection holds, each chunk once, and its
+ /// catalogs and change sets, with the live elements it holds.
+ pub(in crate::css::style) fn report_memory(&self, report: &mut crate::css::style::memory_report::MemoryReport) {
+ use crate::heap_size::map_bytes;
+ let owner = crate::css::style::memory_report::MemoryOwner::Projection;
+ let sizer = &mut report.sizer;
+ let mut bytes = self.rows.heap_size(sizer, Row::heap_size)
+ + self
+ .shadows
+ .heap_size(sizer, |shadow, sizer| shadow_links_heap_size(shadow.as_ref(), sizer));
+ // NB: The generations a transaction or a geometry read holds share the chunks the rows
+ // were not written in since, and hold the others only until they are released.
+ let generations = self.committed.heap_size(sizer, Row::heap_size)
+ + self.before.heap_size(sizer, Row::heap_size)
+ + self
+ .sealed
+ .as_ref()
+ .map_or(0, |sealed| sealed.heap_size(sizer, Row::heap_size));
+ report.add(
+ crate::css::style::memory_report::MemoryOwner::ProjectionGenerations,
+ generations,
+ );
+ let sizer = &mut report.sizer;
+ if sizer.arc_shallow(&self.host_fact_sets) != 0 {
+ bytes += crate::heap_size::ARC_HEADER_BYTES + size_of::<HostFactSets>() + self.host_fact_sets.heap_size();
+ }
+ let catalogs = &self.catalogs;
+ bytes += catalogs.name_forms.heap_size(sizer);
+ // NB: The value texts are the host's strings, which its attributes hold too.
+ bytes += catalogs.value_texts.heap_size(sizer);
+ for texts in [&catalogs.substitution_names, &catalogs.language_texts] {
+ bytes += texts.heap_size(sizer);
+ bytes += texts.values().map(|text| size_of_val::<[u16]>(text)).sum::<usize>();
+ }
+ bytes += sizer.arc_shallow(&self.text_assigned_slots) + map_bytes(&self.text_assigned_slots);
+ if sizer.arc_shallow(&self.structural_flags) != 0 {
+ bytes += crate::heap_size::ARC_HEADER_BYTES
+ + size_of::<StructuralFlagsColumn>()
+ + size_of_val::<[AtomicU8]>(&self.structural_flags.0);
+ }
+ bytes += [
+ &self.written,
+ &self.written_since_seal,
+ &self.links_written,
+ &self.relations_written,
+ ]
+ .iter()
+ .map(|rows| rows.heap_size())
+ .sum::<usize>();
+ bytes += self.pending_change_scan.heap_size();
+ bytes += crate::heap_size::vec_bytes(&self.changes);
+ report.add(owner, bytes);
+ report.elements += (0..self.slot_count)
+ .filter(|&slot| self.rows.get(slot).is_some_and(Row::live))
+ .count();
+ }
+}
+
+impl Projection {
+ fn row(&self, node: StyleNodeID) -> Option<&Row> {
+ self.rows.get(node.element_slot())
+ }
+
+ /// Note that the row of `node`, at `slot`, is written in the transaction to come.
+ fn note_written(&mut self, node: StyleNodeID, slot: usize) {
+ self.written.insert(node, slot);
+ self.written_since_seal.insert(node, slot);
+ }
+
+ /// The links of `node` as the last transaction committed them.
+ /// Whether the rows stand as they did in `generation`, without taking a generation to compare.
+ #[must_use]
+ pub(in crate::css::style) fn is_at_generation(&self, generation: &ProjectionGeneration) -> bool {
+ generation.rows.is_same_generation_as(&self.rows)
+ && generation.committed.is_same_generation_as(&self.committed)
+ && generation.shadows.is_same_generation_as(&self.shadows)
+ }
+
+ /// The generations of the rows, as the host last published them and as the last transaction
+ /// committed them, and of the shadow relations: what a read of the facts, links and shadow
+ /// relations reads, which reads the same where the generations are the same.
+ pub(in crate::css::style) fn generation(&self) -> ProjectionGeneration {
+ ProjectionGeneration {
+ rows: self.rows.clone(),
+ committed: self.committed.clone(),
+ shadows: self.shadows.clone(),
+ }
+ }
+
+ fn links(&self, node: StyleNodeID) -> Option<&Links> {
+ Some(&self.committed.get(node.element_slot())?.links)
+ }
+
+ fn shadow(&self, node: StyleNodeID) -> Option<&ShadowLinks> {
+ self.shadows.get(node.element_slot())?.as_deref()
+ }
+
+ // -- Identity lifecycle --------------------------------------------------------------------
+
+ /// Take a transaction at its barrier: what was committed before it becomes its side from before
+ /// it, and the facts written so far are the ones style reads. A published generation shares
+ /// every chunk of rows with the written one until the written one writes there.
+ ///
+ /// The transaction that flushes a geometry read's seal publishes the sealed rows instead, and
+ /// the elements written after the seal stay written for the transaction after it.
+ pub(in crate::css::style) fn commit(&mut self) {
+ let committed = match self.flushing_seal {
+ true => self.sealed.clone().expect("a flushed seal holds its rows"),
+ false => self.rows.clone(),
+ };
+ self.before = std::mem::replace(&mut self.committed, committed);
+ let chain = match self.flushing_seal {
+ true => self
+ .hover
+ .sealed
+ .as_deref()
+ .expect("a flushed seal holds its hover chain"),
+ false => &self.hover.placed,
+ };
+ let hovered = HoveredFacts::of(chain, &self.committed);
+ self.hover.before = std::mem::replace(&mut self.hover.committed, hovered);
+ let mut written = self.written.take();
+ written.sort_unstable();
+ self.pending_change_scan.clear();
+ self.changes.clear();
+ for pass in ChangePass::ALL {
+ for &node in &written {
+ let slot = node.element_slot();
+ let before = self.before.get(slot);
+ let after = self.committed.get(slot);
+ let hovered = (self.hover.before.contains(node), self.hover.committed.contains(node));
+ note_changes(pass, node, (before, after), hovered, &mut self.changes);
+ }
+ }
+ self.written.reuse(written);
+ if self.flushing_seal {
+ for index in 0..self.written_since_seal.nodes.len() {
+ let node = self.written_since_seal.nodes[index];
+ self.written.insert(node, node.element_slot());
+ self.pending_change_scan.writes.push(node);
+ }
+ } else {
+ self.forget_written_since_seal();
+ }
+ }
+
+ fn forget_written_since_seal(&mut self) {
+ let written = self.written_since_seal.take();
+ self.written_since_seal.reuse(written);
+ }
+
+ /// Seal what was written so far for a geometry read that found none of it could move geometry:
+ /// [`Self::any_change_since_seal`] asks only about rows written after this.
+ /// The transaction a later style change event flushes the seal with takes the rows as they
+ /// are now, where they hold a change at all.
+ pub(in crate::css::style) fn seal_for_geometry_read(&mut self) {
+ debug_assert!(!self.flushing_seal);
+ self.forget_written_since_seal();
+ self.sealed = self.has_pending_changes().then(|| self.rows.clone());
+ self.hover.sealed = self.sealed.is_some().then(|| self.hover.placed.clone());
+ }
+
+ /// Whether a geometry read sealed a change that no transaction has taken yet.
+ #[must_use]
+ pub(in crate::css::style) fn has_sealed_changes(&self) -> bool {
+ !self.flushing_seal && self.sealed.is_some()
+ }
+
+ /// Have the next transaction take the sealed rows alone.
+ pub(in crate::css::style) fn begin_flushing_seal(&mut self) {
+ assert!(self.has_sealed_changes(), "flushing a seal that holds no change");
+ self.flushing_seal = true;
+ }
+
+ /// Finish the transaction that flushed the seal: what was written after it is what the next
+ /// transaction takes.
+ pub(in crate::css::style) fn end_flushing_seal(&mut self) {
+ assert!(self.flushing_seal, "ending a seal flush that did not begin");
+ self.flushing_seal = false;
+ self.sealed = None;
+ self.hover.sealed = None;
+ }
+
+ /// Drop the seal, for a transaction that takes everything written, sealed or not.
+ pub(in crate::css::style) fn drop_seal(&mut self) {
+ if !self.flushing_seal {
+ self.sealed = None;
+ self.hover.sealed = None;
+ }
+ }
+
+ /// Whether the rows written since the last barrier change the committed generation, as
+ /// [`Self::changes`] would say a transaction taken now does.
+ #[must_use]
+ pub(in crate::css::style) fn has_pending_changes(&self) -> bool {
+ // NB: A row found to leave the committed generation as it was does so until it is written again, which lists
+ // it again, so each write is asked about at most once, and a row found to change it is asked first next.
+ use std::sync::atomic::Ordering;
+ let scan = &self.pending_change_scan;
+ let mut changes = Vec::new();
+ let start = scan.checked.load(Ordering::Relaxed);
+ let pending = scan.writes[start..]
+ .iter()
+ .position(|&node| self.has_pending_change_noted_in(node, &mut changes));
+ scan.checked
+ .store(start + pending.unwrap_or(scan.writes.len() - start), Ordering::Relaxed);
+ debug_assert_eq!(
+ pending.is_some(),
+ self.written.nodes.iter().any(|&node| self.has_pending_change(node)),
+ "a written row that changes the committed generation is among the writes not yet found to change nothing"
+ );
+ pending.is_some()
+ }
+
+ /// Whether the row of `node` as written changes the committed generation.
+ #[must_use]
+ pub(in crate::css::style) fn has_pending_change(&self, node: StyleNodeID) -> bool {
+ self.has_pending_change_noted_in(node, &mut Vec::new())
+ }
+
+ /// [`Self::has_pending_change`], noting the changes it finds in `changes`, an empty list.
+ fn has_pending_change_noted_in(&self, node: StyleNodeID, changes: &mut Vec<(StyleNodeID, ElementChange)>) -> bool {
+ let slot = node.element_slot();
+ if node.element_index().is_none() || !self.written.contains(slot) {
+ return false;
+ }
+ let (committed, now) = (self.committed.get(slot), self.rows.get(slot));
+ let hovered = (self.hover.committed.contains(node), self.hover.placed.contains(&node));
+ ChangePass::ALL.into_iter().any(|pass| {
+ note_changes(pass, node, (committed, now), hovered, changes);
+ !changes.is_empty()
+ })
+ }
+
+ /// The elements whose rows as written change the committed generation.
+ pub(in crate::css::style) fn pending_change_nodes(&self) -> impl Iterator<Item = StyleNodeID> + '_ {
+ self.written
+ .nodes
+ .iter()
+ .copied()
+ .filter(|&node| self.has_pending_change(node))
+ }
+
+ /// Whether `node` arrives in the transaction to come: it stood in no tree when the last one
+ /// was committed, and stands in one as written.
+ #[must_use]
+ pub(in crate::css::style) fn arrival_is_pending(&self, node: StyleNodeID) -> bool {
+ node.element_index().is_some()
+ && self.committed_relations(node).is_none()
+ && self.written_relations(node).is_some()
+ }
+
+ /// Whether `test` holds for a change the rows written since the last barrier or seal make to
+ /// the committed generation, each said as [`Self::changes`] says a taken transaction's.
+ pub(in crate::css::style) fn any_change_since_seal(
+ &self,
+ mut test: impl FnMut(StyleNodeID, ElementChange) -> bool,
+ ) -> bool {
+ let mut changes = Vec::new();
+ self.written_since_seal.nodes.iter().any(|&node| {
+ let slot = node.element_slot();
+ let (committed, now) = (self.committed.get(slot), self.rows.get(slot));
+ let hovered = (self.hover.committed.contains(node), self.hover.placed.contains(&node));
+ changes.clear();
+ for pass in ChangePass::ALL {
+ note_changes(pass, node, (committed, now), hovered, &mut changes);
+ }
+ changes.iter().any(|&(node, change)| test(node, change))
+ })
+ }
+
+ /// Release the transaction taken last: its side from before it is dropped, and the links written for it are
+ /// settled.
+ pub(in crate::css::style) fn release(&mut self) {
+ self.before = ColumnSnapshot::default();
+ self.hover.before = HoveredFacts::default();
+ self.changes.clear();
+ let links_written = self.links_written.take();
+ self.links_written.reuse(links_written);
+ let relations_written = self.relations_written.take();
+ self.relations_written.reuse(relations_written);
+ self.link_rows_written.store(0, Ordering::Relaxed);
+ }
+
+ /// Keep `link_rows_written`, which the document's host reads, at how many elements' links
+ /// were written and not released yet, rather than a count of the projection's own. Nothing is
+ /// written yet.
+ pub(in crate::css::style) fn share_link_rows_written(&mut self, link_rows_written: Arc<AtomicU32>) {
+ debug_assert!(!self.has_written_links());
+ self.link_rows_written = link_rows_written;
+ }
+
+ /// Give a fork a count of written link rows of its own in place of the one it shares with the
+ /// host, holding what it holds now.
+ pub(in crate::css::style) fn detach_link_rows_written_for_fork(&mut self) {
+ let written = self.link_rows_written.load(Ordering::Relaxed);
+ self.link_rows_written = Arc::new(AtomicU32::new(written));
+ }
+
+ /// Whether any element's links were written since the last transaction was released.
+ #[must_use]
+ pub(in crate::css::style) fn has_written_links(&self) -> bool {
+ !self.links_written.nodes.is_empty()
+ }
+
+ /// The elements whose links were written since the last transaction was released, each once,
+ /// in the order they were first written.
+ pub(in crate::css::style) fn links_written(&self) -> impl Iterator<Item = StyleNodeID> + '_ {
+ self.links_written.nodes.iter().copied()
+ }
+
+ /// The elements whose relations were written since the last transaction was released, each
+ /// once, in the order they were first written.
+ pub(in crate::css::style) fn relations_written(&self) -> impl Iterator<Item = StyleNodeID> + '_ {
+ self.relations_written.nodes.iter().copied()
+ }
+
+ /// Whether the relations of `node` were written since the last transaction was released.
+ #[must_use]
+ pub(in crate::css::style) fn relations_were_written(&self, node: StyleNodeID) -> bool {
+ node.element_index().is_some() && self.relations_written.contains(node.element_slot())
+ }
+
+ /// What the transaction being taken changed of the elements' facts and relations: their
+ /// relations first, then their facts, then their states, each in element order.
+ #[must_use]
+ pub(in crate::css::style) fn changes(&self) -> &[(StyleNodeID, ElementChange)] {
+ &self.changes
+ }
+
+ // -- Hover ---------------------------------------------------------------------------------
+
+ /// Place the hover on `chain`, the hovered element first: each element entering or leaving it is written, as its
+ /// hover state moves.
+ pub(in crate::css::style) fn place_hover(&mut self, chain: &[StyleNodeID]) {
+ let placed = std::mem::replace(&mut self.hover.placed, SmallVec::from_slice(chain));
+ for &node in placed.iter().filter(|node| !chain.contains(node)) {
+ self.note_hover_written(node);
+ }
+ for &node in chain.iter().filter(|node| !placed.contains(node)) {
+ self.note_hover_written(node);
+ }
+ }
+
+ fn note_hover_written(&mut self, node: StyleNodeID) {
+ self.note_written(node, node.element_slot());
+ self.pending_change_scan.writes.push(node);
+ }
+
+ /// Whether the hover as last placed puts `node` in the hover state.
+ #[cfg(test)]
+ #[must_use]
+ pub(in crate::css::style) fn hover_is_placed_on(&self, node: StyleNodeID) -> bool {
+ self.hover.placed.contains(&node)
+ }
+
+ /// Let go of `node`, whose identity retires: an element that leaves the tree takes its hover state along.
+ pub(in crate::css::style) fn retire_hovered(&mut self, node: StyleNodeID) {
+ self.hover.placed.retain(|hovered| *hovered != node);
+ }
+
+ // -- Adoption ------------------------------------------------------------------------------
+
+ /// Take what the host published at a barrier as the rows written, for the next transaction to take, answering
+ /// what the host's writes counted.
+ pub(in crate::css::style) fn adopt(
+ &mut self,
+ publication: ProjectionPublication,
+ ) -> SmallVec<[(super::super::instrumentation::Counter, u64); 4]> {
+ let ProjectionPublication {
+ rows,
+ shadows,
+ slot_count,
+ catalogs,
+ host_fact_sets,
+ text_assigned_slots,
+ written,
+ links_written,
+ relations_written,
+ counts,
+ } = publication;
+ self.rows = rows;
+ self.shadows = shadows;
+ self.slot_count = slot_count;
+ if self.structural_flags.0.len() < slot_count {
+ self.structural_flags = Arc::new(self.structural_flags.grown_to(slot_count));
+ }
+ self.catalogs = catalogs;
+ self.host_fact_sets = host_fact_sets;
+ self.text_assigned_slots = text_assigned_slots;
+ for node in written {
+ self.note_written(node, node.element_slot());
+ self.pending_change_scan.writes.push(node);
+ }
+ for node in links_written {
+ self.note_links_written(node);
+ }
+ for node in relations_written {
+ self.relations_written.insert(node, node.element_slot());
+ }
+ counts
+ }
+
+ /// Write through the test's own writer, publishing what it wrote to the projection at once, as a host would at
+ /// its next barrier.
+ #[cfg(test)]
+ pub(in crate::css::style) fn write_for_test<R>(
+ &mut self,
+ write: impl FnOnce(&mut ProjectionWriter) -> R,
+ ) -> (R, SmallVec<[(super::super::instrumentation::Counter, u64); 4]>) {
+ let answer = write(&mut self.test_writer);
+ let publication = self.test_writer.publish();
+ (answer, self.adopt(publication))
+ }
+
+ /// Note that the links of `node` are written in the transaction to come.
+ fn note_links_written(&mut self, node: StyleNodeID) {
+ if self.links_written.insert(node, node.element_slot()) {
+ self.link_rows_written.store(
+ u32::try_from(self.links_written.nodes.len()).unwrap_or(u32::MAX),
+ Ordering::Relaxed,
+ );
+ }
+ }
+
+ // -- Reads ---------------------------------------------------------------------------------
+
+ /// One past the greatest element slot the projection holds a row for.
+ #[must_use]
+ pub(in crate::css::style) fn element_slot_count(&self) -> usize {
+ self.slot_count
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn is_live(&self, node: StyleNodeID) -> bool {
+ self.row(node).is_some_and(Row::live)
+ }
+
+ /// The element's facts as the last transaction committed them, or none where nothing was
+ /// published of it by then.
+ #[must_use]
+ pub(in crate::css::style) fn facts(&self, node: StyleNodeID) -> Option<&ElementFacts> {
+ self.facts_on(TransactionFactSide::After, node)
+ }
+
+ /// The facts the host published of `node` beside those its selectors test, as published: an element keeps them from
+ /// its arrival until its identity is minted again, and a text node holds none.
+ #[must_use]
+ pub(in crate::css::style) fn host_facts(&self, node: StyleNodeID) -> HostFactSet {
+ let id = match node.element_index() {
+ Some(_) => self
+ .row(node)
+ .map_or_else(HostFactSetID::default, |row| row.facts.host_facts),
+ None => HostFactSetID::default(),
+ };
+ self.host_fact_sets.get(id)
+ }
+
+ /// The element facts the style computation's adjustments read, as `bridge::element_adjustment_fact` names them.
+ #[must_use]
+ pub(in crate::css::style) fn adjustment_facts(&self, node: StyleNodeID) -> u32 {
+ self.host_facts(node).adjustment_facts
+ }
+
+ /// The element facts a layout row built for the element records, as `bridge::element_construction_fact` names
+ /// them.
+ #[must_use]
+ pub(in crate::css::style) fn construction_facts(&self, node: StyleNodeID) -> u32 {
+ self.host_facts(node).construction_facts
+ }
+
+ /// Which principal box the element asks for.
+ #[must_use]
+ pub(in crate::css::style) fn box_kind(&self, node: StyleNodeID) -> super::super::bridge::ElementBoxKind {
+ self.host_facts(node).box_kind()
+ }
+
+ /// The element-backed pseudo-element kind of its shadow host the element stands for, as published.
+ #[must_use]
+ pub(in crate::css::style) fn associated_pseudo_kind(&self, node: StyleNodeID) -> Option<u8> {
+ self.host_facts(node).associated_pseudo_kind()
+ }
+
+ /// The element-backed pseudo-element kind of its shadow host the element `facts` are of stands for, on whichever
+ /// generation they are read: the published sets hold every set an earlier generation names.
+ #[must_use]
+ pub(in crate::css::style) fn backing_pseudo_kind(&self, facts: &ElementFacts) -> Option<u8> {
+ self.host_fact_sets.get(facts.host_facts).associated_pseudo_kind()
+ }
+
+ /// The element's facts as written, the ones the next transaction is to take included, or none
+ /// where nothing was published of it.
+ #[must_use]
+ pub(in crate::css::style) fn written_facts(&self, node: StyleNodeID) -> Option<&ElementFacts> {
+ self.row(node).map(|row| &row.facts).filter(|facts| facts.resident())
+ }
+
+ /// The element's facts as the transaction being taken left them, or as it found them.
+ #[must_use]
+ pub(in crate::css::style) fn facts_on(
+ &self,
+ side: TransactionFactSide,
+ node: StyleNodeID,
+ ) -> Option<&ElementFacts> {
+ let (generation, hovered) = match side {
+ TransactionFactSide::Before => (&self.before, &self.hover.before),
+ TransactionFactSide::After => (&self.committed, &self.hover.committed),
+ };
+ if let Some(facts) = hovered.get(node) {
+ return Some(facts);
+ }
+ generation
+ .get(node.element_slot())
+ .map(|row| &row.facts)
+ .filter(|facts| facts.resident())
+ }
+
+ /// The element's committed facts, read with the catalogs that spell them.
+ #[must_use]
+ pub(in crate::css::style) fn row_of(&self, node: StyleNodeID) -> Option<ProjectionRow<'_>> {
+ self.row_on(TransactionFactSide::After, node)
+ }
+
+ /// The element's facts on one side of the transaction being taken, read with the catalogs that
+ /// spell them.
+ #[must_use]
+ pub(in crate::css::style) fn row_on(
+ &self,
+ side: TransactionFactSide,
+ node: StyleNodeID,
+ ) -> Option<ProjectionRow<'_>> {
+ Some(ProjectionRow {
+ facts: self.facts_on(side, node)?,
+ projection: self,
+ })
+ }
+
+ /// How the element stands in the tree as written, the writes the next transaction is to take
+ /// included, or none where it stands in no tree.
+ #[must_use]
+ pub(in crate::css::style) fn written_relations(&self, node: StyleNodeID) -> Option<TreeRelations> {
+ self.row(node).and_then(relations_of)
+ }
+
+ /// The element's first element child as written.
+ #[must_use]
+ pub(in crate::css::style) fn written_first_element_child(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ self.row(node)?.links.first_element_child
+ }
+
+ /// How the element stands in the tree as the last transaction committed it, or none where it
+ /// stood in no tree then.
+ #[must_use]
+ pub(in crate::css::style) fn committed_relations(&self, node: StyleNodeID) -> Option<TreeRelations> {
+ self.committed.get(node.element_slot()).and_then(relations_of)
+ }
+
+ /// The links of `node` as the transaction being taken left them, or as it found them.
+ fn links_on(&self, side: TransactionFactSide, node: StyleNodeID) -> Option<&Links> {
+ match side {
+ TransactionFactSide::Before => Some(&self.before.get(node.element_slot())?.links),
+ TransactionFactSide::After => self.links(node),
+ }
+ }
+
+ /// Whether the element stands in a tree as the transaction being taken left it, or did when it
+ /// found it.
+ #[must_use]
+ pub(in crate::css::style) fn is_connected_on(&self, side: TransactionFactSide, node: StyleNodeID) -> bool {
+ let row = match side {
+ TransactionFactSide::Before => self.before.get(node.element_slot()),
+ TransactionFactSide::After => self.committed.get(node.element_slot()),
+ };
+ row.and_then(relations_of).is_some()
+ }
+
+ /// Whether the children of `parent` stood in a tree before the update: where it did, or for a shadow root, which
+ /// holds no relations of its own, where its host did.
+ #[must_use]
+ pub(in crate::css::style) fn children_were_connected(&self, parent: StyleNodeID) -> bool {
+ self.is_connected_on(TransactionFactSide::Before, parent)
+ || self
+ .host_of(parent)
+ .is_some_and(|host| self.is_connected_on(TransactionFactSide::Before, host))
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn parent_on(&self, side: TransactionFactSide, node: StyleNodeID) -> Option<StyleNodeID> {
+ self.links_on(side, node)?.parent
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn first_element_child_on(
+ &self,
+ side: TransactionFactSide,
+ node: StyleNodeID,
+ ) -> Option<StyleNodeID> {
+ self.links_on(side, node)?.first_element_child
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn previous_element_sibling_on(
+ &self,
+ side: TransactionFactSide,
+ node: StyleNodeID,
+ ) -> Option<StyleNodeID> {
+ self.links_on(side, node)?.previous_element_sibling
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn next_element_sibling_on(
+ &self,
+ side: TransactionFactSide,
+ node: StyleNodeID,
+ ) -> Option<StyleNodeID> {
+ self.links_on(side, node)?.next_element_sibling
+ }
+
+ pub(in crate::css::style) fn children_on(
+ &self,
+ side: TransactionFactSide,
+ node: StyleNodeID,
+ ) -> impl Iterator<Item = StyleNodeID> + '_ {
+ std::iter::successors(self.first_element_child_on(side, node), move |&child| {
+ self.next_element_sibling_on(side, child)
+ })
+ }
+
+ /// Visit every dispatch probe the element carries: each dispatch key, an attribute's under every
+ /// name a selector can reach it by, with the value of the attribute that supplied it.
+ pub(in crate::css::style) fn for_each_dispatch_probe(
+ &self,
+ facts: &ElementFacts,
+ is_document_root: bool,
+ visit: impl FnMut(DispatchKey, Option<StyleAtomID>),
+ ) {
+ for_each_dispatch_probe(facts, &self.catalogs.name_forms, is_document_root, visit);
+ }
+
+ /// Add the atoms the rows hold to `atoms`, with the other forms of each attribute name one
+ /// carries, and return how many rows were visited.
+ pub(in crate::css::style) fn collect_atoms(&self, atoms: &mut HashSet<StyleAtomID>) -> u64 {
+ let mut visited = 0_u64;
+ let mut insert = |atom: StyleAtomID| {
+ if !atom.is_none() {
+ atoms.insert(atom);
+ }
+ };
+ for slot in 0..self.slot_count {
+ let Some(row) = self.rows.get(slot) else {
+ continue;
+ };
+ visited += 1;
+ let facts = &row.facts;
+ for atom in [
+ facts.tag,
+ facts.folded_tag(),
+ facts.id(),
+ facts.language(),
+ facts.namespace(),
+ facts.part_exposure(),
+ facts.directionality(),
+ ] {
+ insert(atom);
+ }
+ for &atom in facts.custom_states().iter().chain(facts.parts()).chain(facts.classes()) {
+ insert(atom);
+ }
+ if let Some(shadow) = self.shadows.get(slot).and_then(Option::as_deref) {
+ for &(atom, _) in shadow.part_hosts.as_slice() {
+ insert(atom);
+ }
+ }
+ for attribute in facts.attributes() {
+ insert(attribute.name);
+ insert(attribute.value);
+ let forms = self.attribute_name_forms(attribute.name);
+ for form in [forms.local, forms.folded_name, forms.folded_local] {
+ insert(form);
+ }
+ }
+ }
+ visited
+ }
+
+ /// Add to `atoms` the other forms of every attribute name in it, which stay live with it.
+ pub(in crate::css::style) fn extend_live_attribute_name_forms(&self, atoms: &mut HashSet<StyleAtomID>) {
+ for (name, forms) in self.catalogs.name_forms.iter() {
+ if atoms.contains(name) {
+ atoms.extend(
+ [forms.local, forms.folded_name, forms.folded_local]
+ .into_iter()
+ .filter(|atom| !atom.is_none()),
+ );
+ }
+ }
+ }
+
+ /// The names an attribute called `name` answers to, each one standing for itself where it has
+ /// no other form.
+ #[must_use]
+ pub(in crate::css::style) fn attribute_name_keys(&self, name: StyleAtomID) -> [StyleAtomID; 4] {
+ attribute_name_keys(&self.catalogs.name_forms, name)
+ }
+
+ /// Whether the rules of trees other than the element's own can reach it: it hosts a shadow
+ /// tree, is slotted, or is a part exposed outside its tree.
+ #[must_use]
+ pub(in crate::css::style) fn is_reached_from_other_trees(&self, node: StyleNodeID) -> bool {
+ self.shadow_root_of(node).is_some()
+ || self.assigned_slot_of(node).is_some()
+ || !self.part_hosts_of(node).is_empty()
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn attribute_name_forms(&self, name: StyleAtomID) -> AttributeNameForms {
+ self.catalogs.name_forms.get(&name).copied().unwrap_or_default()
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn attribute_substitution_name(&self, name: StyleAtomID) -> Option<&[u16]> {
+ self.catalogs.substitution_names.get(&name).map(AsRef::as_ref)
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn attribute_value_text(&self, value: StyleAtomID) -> Option<&RetainedUtf16FlyString> {
+ self.catalogs.value_texts.get(&value)
+ }
+
+ /// The element's resolved language tag, empty when it has none.
+ #[must_use]
+ pub(in crate::css::style) fn language_tag_of(&self, node: StyleNodeID) -> &[u16] {
+ self.facts(node)
+ .and_then(|facts| self.catalogs.language_texts.get(&facts.language()))
+ .map_or(&[], AsRef::as_ref)
+ }
+
+ /// What the selectors matched against `node` read of its structure. An element the column has no slot for yet
+ /// is taken to have had all of it read.
+ #[must_use]
+ pub(in crate::css::style) fn structural_flags(&self, node: StyleNodeID) -> StructuralFlags {
+ self.structural_flags
+ .0
+ .get(node.element_slot())
+ .map_or(StructuralFlags::ALL, |flags| {
+ StructuralFlags(flags.load(Ordering::Relaxed))
+ })
+ }
+
+ /// Note that a selector read `read` of `node`, on `side` of the transaction being taken: of its place among its
+ /// siblings on its parent, of whether it is empty on itself.
+ pub(in crate::css::style) fn note_structural_read(
+ &self,
+ side: TransactionFactSide,
+ node: StyleNodeID,
+ read: StructuralRead,
+ ) {
+ let (flagged, flags) = match read {
+ StructuralRead::PreviousSibling => (
+ self.parent_on(side, node),
+ StructuralFlags::CHILDREN_READ_SIBLINGS.union(StructuralFlags::CHILDREN_READ_PREVIOUS_SIBLING),
+ ),
+ StructuralRead::EarlierSiblings => (self.parent_on(side, node), StructuralFlags::CHILDREN_READ_SIBLINGS),
+ StructuralRead::Position {
+ from_end,
+ of_type,
+ beyond_edge,
+ } => {
+ let when = |read: bool, flag: StructuralFlags| match read {
+ true => flag,
+ false => StructuralFlags::default(),
+ };
+ (
+ self.parent_on(side, node),
+ StructuralFlags::CHILDREN_READ_POSITIONS
+ .union(when(from_end, StructuralFlags::CHILDREN_READ_POSITIONS_FROM_END))
+ .union(when(of_type, StructuralFlags::CHILDREN_READ_POSITIONS_OF_TYPE))
+ .union(when(beyond_edge, StructuralFlags::CHILDREN_READ_POSITIONS_BEYOND_EDGES)),
+ )
+ }
+ StructuralRead::Emptiness => (Some(node), StructuralFlags::READ_EMPTINESS),
+ StructuralRead::SiblingPositionValue => (
+ self.parent_on(side, node),
+ StructuralFlags::CHILD_READS_SIBLING_POSITION,
+ ),
+ };
+ // NB: A row lies below the slot count, which the column always covers.
+ let Some(cell) = flagged.and_then(|flagged| self.structural_flags.0.get(flagged.element_slot())) else {
+ return;
+ };
+ if cell.load(Ordering::Relaxed) & flags.0 != flags.0 {
+ cell.fetch_or(flags.0, Ordering::Relaxed);
+ }
+ }
+
+ /// Forget what the selectors read of the structure of `node`, which arrived where all its children are matched
+ /// again.
+ pub(in crate::css::style) fn forget_structural_flags(&self, node: StyleNodeID) {
+ if let Some(cell) = self.structural_flags.0.get(node.element_slot()) {
+ cell.store(0, Ordering::Relaxed);
+ }
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn parent(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ self.links(node)?.parent
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn first_element_child(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ self.links(node)?.first_element_child
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn previous_element_sibling(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ self.links(node)?.previous_element_sibling
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn next_element_sibling(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ self.links(node)?.next_element_sibling
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn tree_scope(&self, node: StyleNodeID) -> TreeScopeID {
+ self.committed
+ .get(node.element_slot())
+ .map_or(TreeScopeID::DOCUMENT, |row| row.facts.lists.tree_scope())
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn shadow_root_of(&self, host: StyleNodeID) -> Option<StyleNodeID> {
+ self.shadow(host)?.shadow_root
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn host_of(&self, shadow_root: StyleNodeID) -> Option<StyleNodeID> {
+ self.shadow(shadow_root)?.host
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn assigned_slot_of(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ match node.text_index() {
+ Some(_) => self.text_assigned_slots.get(&node).copied(),
+ None => self.committed.get(node.element_slot())?.facts.lists.assigned_slot(),
+ }
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn assigned_nodes_of(&self, slot: StyleNodeID) -> &[StyleNodeID] {
+ self.shadow(slot).map_or(&[], |shadow| shadow.assigned_nodes.as_slice())
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn part_hosts_of(&self, node: StyleNodeID) -> &[(StyleAtomID, StyleNodeID)] {
+ self.shadow(node).map_or(&[], |shadow| shadow.part_hosts.as_slice())
+ }
+
+ /// The shadow host of the tree `node` is in, if it is in one: the host of the root of its
+ /// parent chain.
+ #[must_use]
+ pub(in crate::css::style) fn shadow_host_of(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ let mut root = node;
+ while let Some(parent) = self.parent(root) {
+ root = parent;
+ }
+ self.host_of(root)
+ }
+
+ /// The shadow host of the tree `node` stands in as written, the writes the next transaction is
+ /// to take included.
+ #[must_use]
+ pub(in crate::css::style) fn written_shadow_host_of(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ let mut root = node;
+ while let Some(parent) = self.row(root).and_then(|row| row.links.parent) {
+ root = parent;
+ }
+ self.host_of(root)
+ }
+
+ /// The element whose computed values this element inherits: its slot, the host of the shadow
+ /// root it is a child of, or its parent.
+ #[must_use]
+ pub(in crate::css::style) fn inheritance_parent(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ if let Some(slot) = self.assigned_slot_of(node) {
+ return Some(slot);
+ }
+ let parent = self.parent(node)?;
+ Some(self.host_of(parent).unwrap_or(parent))
+ }
+
+ /// The parent an element has in the flat tree: its slot, the host of the shadow root it is a
+ /// child of, or its parent, unless that parent hosts a shadow tree or is a slot with assigned
+ /// nodes, which leave the element out of the flat tree.
+ #[must_use]
+ pub(in crate::css::style) fn flat_tree_parent(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ if let Some(slot) = self.assigned_slot_of(node) {
+ return Some(slot);
+ }
+ let parent = self.parent(node)?;
+ if let Some(host) = self.host_of(parent) {
+ return Some(host);
+ }
+ if self.shadow_root_of(parent).is_some() || !self.assigned_nodes_of(parent).is_empty() {
+ return None;
+ }
+ Some(parent)
+ }
+
+ /// The children an element has in the flat tree: those of its shadow root where it hosts one,
+ /// a slot's assigned nodes, text nodes included, where it has any, and its own otherwise.
+ pub(in crate::css::style) fn flat_tree_children(
+ &self,
+ node: StyleNodeID,
+ ) -> impl Iterator<Item = StyleNodeID> + '_ {
+ let assigned = match self.shadow_root_of(node) {
+ Some(_) => &[][..],
+ None => self.assigned_nodes_of(node),
+ };
+ let dom_parent = match assigned.is_empty() {
+ true => Some(self.shadow_root_of(node).unwrap_or(node)),
+ false => None,
+ };
+ dom_parent
+ .into_iter()
+ .flat_map(|parent| self.children(parent))
+ .chain(assigned.iter().copied())
+ }
+
+ pub(in crate::css::style) fn children(&self, node: StyleNodeID) -> impl Iterator<Item = StyleNodeID> + '_ {
+ std::iter::successors(self.first_element_child(node), |&child| {
+ self.next_element_sibling(child)
+ })
+ }
+
+ pub(in crate::css::style) fn ancestors(&self, node: StyleNodeID) -> impl Iterator<Item = StyleNodeID> + '_ {
+ std::iter::successors(self.parent(node), |&ancestor| self.parent(ancestor))
+ }
+
+ /// `root` and its descendants, in tree order.
+ pub(in crate::css::style) fn preorder(&self, root: StyleNodeID) -> impl Iterator<Item = StyleNodeID> + '_ {
+ let tree = ProjectionTree {
+ projection: self,
+ side: TransactionFactSide::After,
+ };
+ std::iter::successors(Some(root), move |&node| tree.next_in_subtree(node, root))
+ }
+
+ /// The elements whose [`Self::inheritance_parent`] is `node`: a shadow host's shadow root
+ /// children, a slot's assigned elements, and the children assigned to no slot.
+ pub(in crate::css::style) fn style_children(&self, node: StyleNodeID) -> impl Iterator<Item = StyleNodeID> + '_ {
+ let shadow_root_children = self
+ .shadow_root_of(node)
+ .into_iter()
+ .flat_map(|shadow_root| self.children(shadow_root));
+ let assigned_elements = self.assigned_nodes_of(node).iter().copied().filter(move |&assigned| {
+ assigned.element_index().is_some() && self.assigned_slot_of(assigned) == Some(node)
+ });
+ let own_children = self
+ .children(node)
+ .filter(move |&child| self.inheritance_parent(child) == Some(node));
+ shadow_root_children.chain(assigned_elements).chain(own_children)
+ }
+
+ /// `root` and the elements a style traversal reaches from it through [`Self::style_children`],
+ /// each after its inheritance parent.
+ pub(in crate::css::style) fn style_preorder(&self, root: StyleNodeID) -> impl Iterator<Item = StyleNodeID> + '_ {
+ let mut stack = vec![root];
+ std::iter::from_fn(move || {
+ let node = stack.pop()?;
+ let first = stack.len();
+ stack.extend(self.style_children(node));
+ stack[first..].reverse();
+ Some(node)
+ })
+ }
+
+ /// The projection as a selector is matched against it on one side of the
+ /// transaction being taken.
+ #[must_use]
+ pub(in crate::css::style) fn subject_on(&self, side: TransactionFactSide) -> ProjectionSubject<'_> {
+ ProjectionSubject {
+ projection: self,
+ side,
+ part_exposure_scope: None,
+ match_workspace: None,
+ owned_match_workspace: None,
+ positional_index_policy: PositionalIndexPolicy::All,
+ last_structural_read: std::cell::Cell::new(None),
+ }
+ }
+
+ /// An evaluator of selectors against the projection.
+ #[must_use]
+ pub(in crate::css::style) fn evaluator(&self) -> ProjectionEvaluator<'_> {
+ self.evaluator_on(TransactionFactSide::After)
+ }
+
+ /// An evaluator of selectors against the projection on one side of the transaction
+ /// being taken.
+ #[must_use]
+ pub(in crate::css::style) fn evaluator_on(&self, side: TransactionFactSide) -> ProjectionEvaluator<'_> {
+ SelectorEvaluator {
+ subject: self.subject_on(side),
+ bindings: SelectorBindings::default(),
+ }
+ }
+}
+
+/// The relations of the element a row holds, or none where it stands in no tree.
+/// The writes a test makes of a projection directly, each published to it at once through the test's own writer, as
+/// a host's are at its next barrier.
+#[cfg(test)]
+macro_rules! writes_for_test {
+ ($($name:ident($($argument:ident: $type:ty),*);)+) => {
+ impl Projection {
+ $(
+ pub(in crate::css::style) fn $name(&mut self, $($argument: $type),*) {
+ self.write_for_test(|writer| writer.$name($($argument),*));
+ }
+ )+
+ }
+ };
+}
+
+#[cfg(test)]
+writes_for_test! {
+ mint(node: StyleNodeID);
+ retire(node: StyleNodeID);
+ forget(node: StyleNodeID);
+ set_tag(node: StyleNodeID, tag: StyleAtomID);
+ set_folded_tag(node: StyleNodeID, folded: StyleAtomID);
+ set_language(node: StyleNodeID, language: StyleAtomID);
+ set_directionality(node: StyleNodeID, directionality: StyleAtomID);
+ set_part_exposure(node: StyleNodeID, exposure: StyleAtomID);
+ set_custom_states(node: StyleNodeID, states: &[StyleAtomID]);
+ set_language_text(language: StyleAtomID, text: &[u16]);
+ ensure_facts(node: StyleNodeID);
+ write_relations(node: StyleNodeID, relations: Option<TreeRelations>);
+ set_namespace(node: StyleNodeID, namespace: StyleAtomID);
+ set_id(node: StyleNodeID, id: StyleAtomID);
+ set_class(node: StyleNodeID, class: StyleAtomID, present: bool);
+ set_attribute(node: StyleNodeID, name: StyleAtomID, value: StyleAtomID, present: bool);
+ set_parts(node: StyleNodeID, parts: &[StyleAtomID]);
+ set_attribute_value_text(value: StyleAtomID, text: RetainedUtf16FlyString);
+ note_attribute_name_forms(name: StyleAtomID, forms: AttributeNameForms);
+ forget_atoms(atoms: &[StyleAtomID]);
+ set_parent(node: StyleNodeID, parent: Option<StyleNodeID>);
+ set_first_element_child(node: StyleNodeID, child: Option<StyleNodeID>);
+ set_previous_element_sibling(node: StyleNodeID, sibling: Option<StyleNodeID>);
+ set_next_element_sibling(node: StyleNodeID, sibling: Option<StyleNodeID>);
+ set_connected(node: StyleNodeID, connected: bool);
+ set_assigned_slot(node: StyleNodeID, slot: Option<StyleNodeID>);
+ set_shadow_root(host: StyleNodeID, shadow_root: StyleNodeID);
+ set_assigned_nodes(slot: StyleNodeID, nodes: &[StyleNodeID]);
+ retire_texts(nodes: [StyleNodeID; 1]);
+}
+
+fn relations_of(row: &Row) -> Option<TreeRelations> {
+ (row.live() && row.connected()).then_some(TreeRelations {
+ parent: row.links.parent,
+ previous_element_sibling: row.links.previous_element_sibling,
+ next_element_sibling: row.links.next_element_sibling,
+ tree_scope: row.facts.lists.tree_scope(),
+ assigned_slot: row.facts.lists.assigned_slot(),
+ })
+}
+
+#[derive(Clone, Copy, PartialEq, Eq)]
+enum ChangePass {
+ Relations,
+ Facts,
+ States,
+}
+
+impl ChangePass {
+ const ALL: [Self; 3] = [Self::Relations, Self::Facts, Self::States];
+}
+
+/// Visit what is in one of `a` and `b`, sorted lists, and not in the other.
+fn for_each_difference<T: Ord + Copy>(a: &[T], b: &[T], mut visit: impl FnMut(T)) {
+ let (mut a, mut b) = (a.iter().peekable(), b.iter().peekable());
+ loop {
+ match (a.peek(), b.peek()) {
+ (None, None) => return,
+ (Some(&&x), None) => {
+ visit(x);
+ a.next();
+ }
+ (None, Some(&&y)) => {
+ visit(y);
+ b.next();
+ }
+ (Some(&&x), Some(&&y)) => match x.cmp(&y) {
+ std::cmp::Ordering::Less => {
+ visit(x);
+ a.next();
+ }
+ std::cmp::Ordering::Greater => {
+ visit(y);
+ b.next();
+ }
+ std::cmp::Ordering::Equal => {
+ a.next();
+ b.next();
+ }
+ },
+ }
+ }
+}
+
+/// Note what one pass over the elements of a transaction finds changed of `node` between its row
+/// before the transaction and its row now.
+fn note_changes(
+ pass: ChangePass,
+ node: StyleNodeID,
+ (before, after): (Option<&Row>, Option<&Row>),
+ (was_hovered, is_hovered): (bool, bool),
+ changes: &mut Vec<(StyleNodeID, ElementChange)>,
+) {
+ let (old, new) = (before.and_then(relations_of), after.and_then(relations_of));
+ let empty = ElementFacts::default();
+ let (was, is) = (
+ before.map_or(&empty, |row| &row.facts),
+ after.map_or(&empty, |row| &row.facts),
+ );
+ let mut note = |change| changes.push((node, change));
+ match pass {
+ ChangePass::Relations => {
+ if old != new {
+ note(ElementChange::Relations(old, new));
+ }
+ }
+ // NB: An element that leaves says every fact it had by leaving, and the host forgets them as it publishes that.
+ ChangePass::Facts | ChangePass::States if old.is_some() && new.is_none() => {}
+ // NB: Every fact of an element arriving is said by its arrival.
+ ChangePass::Facts if old.is_none() && new.is_some() => {
+ if !was.says_the_same_as(is) {
+ note(ElementChange::ArrivingFacts);
+ }
+ }
+ ChangePass::Facts => {
+ if was.tag != is.tag {
+ note(ElementChange::Feature(LocalFeatureKey::TagName));
+ }
+ if was.folded_tag() != is.folded_tag() {
+ note(ElementChange::Feature(LocalFeatureKey::FoldedTagName));
+ }
+ if was.id() != is.id() {
+ note(ElementChange::Id(was.id(), is.id()));
+ }
+ for_each_difference(was.classes(), is.classes(), |class| {
+ note(ElementChange::Feature(LocalFeatureKey::Class(class)));
+ });
+ let mut parts: SmallVec<[StyleAtomID; 4]> = SmallVec::from_slice(was.parts());
+ parts.sort_unstable();
+ let mut now: SmallVec<[StyleAtomID; 4]> = SmallVec::from_slice(is.parts());
+ now.sort_unstable();
+ for_each_difference(&parts, &now, |part| {
+ note(ElementChange::Feature(LocalFeatureKey::Part(part)));
+ });
+ parts.clear();
+ parts.extend_from_slice(was.custom_states());
+ parts.sort_unstable();
+ now.clear();
+ now.extend_from_slice(is.custom_states());
+ now.sort_unstable();
+ for_each_difference(&parts, &now, |state| {
+ note(ElementChange::Feature(LocalFeatureKey::CustomState(state)));
+ });
+ if was.has_text_content() != is.has_text_content() {
+ note(ElementChange::Feature(LocalFeatureKey::Emptiness));
+ }
+ // An attribute whose value moved is one change, as one that came or went is.
+ let names = |attributes: &[AttributeFact]| -> SmallVec<[StyleAtomID; 8]> {
+ attributes.iter().map(|attribute| attribute.name).collect()
+ };
+ let (old_names, new_names) = (names(was.attributes()), names(is.attributes()));
+ for_each_difference(&old_names, &new_names, |name| {
+ note(ElementChange::Feature(LocalFeatureKey::Attribute(name)));
+ });
+ for attribute in was.attributes() {
+ if let Ok(index) = new_names.binary_search(&attribute.name)
+ && is.attributes()[index].value != attribute.value
+ {
+ note(ElementChange::Feature(LocalFeatureKey::Attribute(attribute.name)));
+ }
+ }
+ if was.language() != is.language() {
+ note(ElementChange::Feature(LocalFeatureKey::Language));
+ }
+ if was.directionality() != is.directionality() {
+ note(ElementChange::Feature(LocalFeatureKey::Directionality));
+ }
+ if was.heading_level() != is.heading_level() {
+ note(ElementChange::Feature(LocalFeatureKey::HeadingLevel));
+ }
+ if was.part_exposure() != is.part_exposure() {
+ note(ElementChange::Feature(LocalFeatureKey::PartExposure));
+ }
+ }
+ ChangePass::States => {
+ if old.is_none() && new.is_some() {
+ return;
+ }
+ let hovered = |hovered: bool| match hovered {
+ true => 1_u64 << StateFact::Hover as u32,
+ false => 0,
+ };
+ // NB: An element that leaves the tree leaves the hover chain with it, which is no change of its state.
+ let hover_moved = new.is_some() && was_hovered != is_hovered;
+ let (was_states, is_states) = (
+ was.states.0 | hovered(was_hovered && hover_moved),
+ is.states.0 | hovered(is_hovered && hover_moved),
+ );
+ for fact in StateSet(was_states ^ is_states).facts() {
+ note(ElementChange::State(fact));
+ }
+ }
+ }
+}
+
+/// The names an attribute called `name` answers to: itself, its local name, and the folding of
+/// each, the foldings standing for the names they fold where they are the same.
+fn attribute_name_keys(name_forms: &Catalog<AttributeNameForms>, name: StyleAtomID) -> [StyleAtomID; 4] {
+ let forms = name_forms.get(&name).copied().unwrap_or_default();
+ let folded_name = match forms.folded_name.is_none() {
+ true => name,
+ false => forms.folded_name,
+ };
+ let folded_local = match forms.folded_local.is_none() {
+ true => forms.local,
+ false => forms.folded_local,
+ };
+ [name, forms.local, folded_name, folded_local]
+}
+
+/// The Bloom summary of the dispatch keys `facts` carry, document-root status aside.
+/// The Bloom summary of the dispatch keys the lists `lists` would carry.
+fn list_bloom_of(lists: &FactListsEdit, name_forms: &Catalog<AttributeNameForms>) -> u64 {
+ let mut bloom = 0;
+ if !lists.folded_tag.is_none() {
+ bloom |= dispatch_bloom_bit(DispatchKey::TagName(lists.folded_tag));
+ }
+ if !lists.id.is_none() {
+ bloom |= dispatch_bloom_bit(DispatchKey::Id(lists.id));
+ }
+ for &class in lists.classes.iter() {
+ bloom |= dispatch_bloom_bit(DispatchKey::Class(class));
+ }
+ if !lists.directionality.is_none() {
+ bloom |= dispatch_bloom_bit(DispatchKey::Directionality(lists.directionality));
+ }
+ for &state in lists.custom_states.iter() {
+ bloom |= dispatch_bloom_bit(DispatchKey::CustomState(state));
+ }
+ for &part in lists.parts.iter() {
+ bloom |= dispatch_bloom_bit(DispatchKey::Part(part));
+ }
+ for attribute in lists.attributes.iter() {
+ for name in attribute_name_keys(name_forms, attribute.name) {
+ if !name.is_none() {
+ bloom |= dispatch_bloom_bit(DispatchKey::AttributeName(name));
+ }
+ }
+ }
+ bloom
+}
+
+/// See [`Projection::for_each_dispatch_probe`].
+fn for_each_dispatch_probe(
+ facts: &ElementFacts,
+ name_forms: &Catalog<AttributeNameForms>,
+ is_document_root: bool,
+ mut visit: impl FnMut(DispatchKey, Option<StyleAtomID>),
+) {
+ visit(DispatchKey::Universal, None);
+ for fact in facts.states.facts() {
+ visit(DispatchKey::State(fact), None);
+ }
+ if is_document_root {
+ visit(DispatchKey::Root, None);
+ }
+ if facts.heading_level() != 0 {
+ visit(DispatchKey::Heading, None);
+ }
+ visit(DispatchKey::TagName(facts.tag), None);
+ let folded_tag = facts.folded_tag();
+ if !folded_tag.is_none() {
+ visit(DispatchKey::TagName(folded_tag), None);
+ }
+ if !facts.id().is_none() {
+ visit(DispatchKey::Id(facts.id()), None);
+ }
+ for &class in facts.classes() {
+ visit(DispatchKey::Class(class), None);
+ }
+ if !facts.directionality().is_none() {
+ visit(DispatchKey::Directionality(facts.directionality()), None);
+ }
+ for &state in facts.custom_states() {
+ visit(DispatchKey::CustomState(state), None);
+ }
+ for &part in facts.parts() {
+ visit(DispatchKey::Part(part), None);
+ }
+ for attribute in facts.attributes() {
+ // Every name a selector can reach this attribute by, since a compound dispatches under one
+ // of them and which one depends on how the selector wrote it.
+ let keys = attribute_name_keys(name_forms, attribute.name);
+ for (index, &name) in keys.iter().enumerate() {
+ if !name.is_none() && !keys[..index].contains(&name) {
+ visit(DispatchKey::AttributeName(name), Some(attribute.value));
+ }
+ }
+ }
+}
+
+impl<'a> ProjectionRow<'a> {
+ #[must_use]
+ pub(in crate::css::style) fn tag(self) -> StyleAtomID {
+ self.facts.tag
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn folded_tag(self) -> StyleAtomID {
+ self.facts.folded_tag()
+ }
+
+ /// The element-backed pseudo-element kind of its shadow host the element stands for.
+ #[must_use]
+ pub(in crate::css::style) fn backing_pseudo_kind(self) -> Option<u8> {
+ self.projection.backing_pseudo_kind(self.facts)
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn id(self) -> StyleAtomID {
+ self.facts.id()
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn states(self) -> StateSet {
+ self.facts.states
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn classes(self) -> &'a [StyleAtomID] {
+ self.facts.classes()
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn attributes(self) -> &'a [AttributeFact] {
+ self.facts.attributes()
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn custom_states(self) -> &'a [StyleAtomID] {
+ self.facts.custom_states()
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn parts(self) -> &'a [StyleAtomID] {
+ self.facts.parts()
+ }
+
+ /// See [`Projection::attribute_name_keys`].
+ #[must_use]
+ pub(in crate::css::style) fn attribute_name_keys(self, name: StyleAtomID) -> [StyleAtomID; 4] {
+ self.projection.attribute_name_keys(name)
+ }
+}
+
+/// Matches selectors against the projection.
+pub(in crate::css::style) type ProjectionEvaluator<'a> = SelectorEvaluator<ProjectionSubject<'a>>;
+
+impl<'a> ProjectionEvaluator<'a> {
+ /// Evaluate for a part exposed in `scope`, for an evaluator reused across the rules of several trees, or for no part
+ /// for none.
+ pub(in crate::css::style) fn set_part_exposure_scope(&mut self, scope: Option<TreeScopeID>) {
+ self.subject.part_exposure_scope = scope;
+ }
+
+ /// Keep sibling positions, and the answers of positional tests, in `workspace`.
+ #[must_use]
+ pub(in crate::css::style) fn with_match_workspace(mut self, workspace: &'a mut MatchScratch) -> Self {
+ self.subject.match_workspace = Some(workspace);
+ self
+ }
+
+ /// Keep sibling positions, and the answers of positional tests, in a workspace of the
+ /// evaluator's own for `side`, for as long as it lives. The projection must not change
+ /// meanwhile, as the positions are not taken again.
+ #[must_use]
+ pub(in crate::css::style) fn with_owned_match_workspace(mut self) -> Self {
+ self.subject.owned_match_workspace = Some(MatchScratch::default());
+ self
+ }
+
+ /// How many walks of a `:has()` argument the workspace the evaluator owns remembers the answers of.
+ pub(in crate::css::style) fn relative_walks(&self) -> u64 {
+ self.subject
+ .owned_match_workspace
+ .as_ref()
+ .map_or(0, MatchScratch::relative_walks)
+ }
+
+ /// Answer only stepped positional tests from the workspace's sibling index, and memoize no
+ /// positional answer. See [`PositionalIndexPolicy::SteppedOnly`].
+ #[must_use]
+ pub(in crate::css::style) fn indexing_stepped_positions_only(mut self) -> Self {
+ self.subject.positional_index_policy = PositionalIndexPolicy::SteppedOnly;
+ self
+ }
+}
+
+/// The projection's links, as a selector walks them.
+///
+/// On the side of a transaction from before it, an element's parent and siblings are the ones it
+/// had, but its shadow relations, its slot and the parent that scoping and `:scope` walk are the
+/// ones it has: an element whose tree or slot moved restyles whole, so what they reach is the same
+/// before as now.
+#[derive(Clone, Copy)]
+pub(in crate::css::style) struct ProjectionTree<'a> {
+ projection: &'a Projection,
+ side: TransactionFactSide,
+}
+
+impl SelectorTree for ProjectionTree<'_> {
+ type Node = StyleNodeID;
+
+ #[inline]
+ fn backs_pseudo_element(self, node: StyleNodeID, kind: u16) -> bool {
+ self.projection
+ .facts_on(self.side, node)
+ .is_some_and(|facts| self.projection.backing_pseudo_kind(facts).map(u16::from) == Some(kind))
+ }
+
+ #[inline]
+ fn parent(self, node: StyleNodeID) -> Option<StyleNodeID> {
+ self.projection.parent_on(self.side, node)
+ }
+
+ #[inline]
+ fn previous_sibling(self, node: StyleNodeID) -> Option<StyleNodeID> {
+ self.projection.previous_element_sibling_on(self.side, node)
+ }
+
+ #[inline]
+ fn next_sibling(self, node: StyleNodeID) -> Option<StyleNodeID> {
+ self.projection.next_element_sibling_on(self.side, node)
+ }
+
+ #[inline]
+ fn first_child(self, parent: StyleNodeID) -> Option<StyleNodeID> {
+ self.projection.first_element_child_on(self.side, parent)
+ }
+
+ #[inline]
+ fn live_parent(self, node: StyleNodeID) -> Option<StyleNodeID> {
+ self.projection.parent(node)
+ }
+
+ #[inline]
+ fn shadow_root_of(self, host: StyleNodeID) -> Option<StyleNodeID> {
+ self.projection.shadow_root_of(host)
+ }
+
+ #[inline]
+ fn host_of(self, shadow_root: StyleNodeID) -> Option<StyleNodeID> {
+ self.projection.host_of(shadow_root)
+ }
+
+ #[inline]
+ fn assigned_slot_of(self, node: StyleNodeID) -> Option<StyleNodeID> {
+ self.projection.assigned_slot_of(node)
+ }
+
+ #[inline]
+ fn shadow_host_of(self, node: StyleNodeID) -> Option<StyleNodeID> {
+ self.projection.shadow_host_of(node)
+ }
+}
+
+/// One element's facts, as the tests of a selector read them.
+#[derive(Clone, Copy)]
+pub(in crate::css::style) struct ProjectionRow<'a> {
+ pub(in crate::css::style) facts: &'a ElementFacts,
+ projection: &'a Projection,
+}
+
+impl ElementFeatures for ProjectionRow<'_> {
+ type Attribute = AttributeFact;
+
+ #[inline]
+ fn local_name_is(&self, name: StyleAtomID) -> bool {
+ self.facts.tag == name
+ }
+
+ #[inline]
+ fn namespace_is(&self, namespace: StyleAtomID) -> bool {
+ self.facts.namespace() == namespace
+ }
+
+ #[inline]
+ fn has_id(&self, id: StyleAtomID) -> bool {
+ self.facts.id() == id
+ }
+
+ #[inline]
+ fn has_class(&self, class: StyleAtomID) -> bool {
+ self.facts.classes().binary_search(&class).is_ok()
+ }
+
+ /// `[*|x]` names the attribute called `x` in each namespace the element carries it in, and they
+ /// all publish the same any-namespace atom as their local name.
+ #[inline]
+ fn attributes_named(&self, name: StyleAtomID, any_namespace: bool) -> impl Iterator<Item = AttributeFact> + '_ {
+ self.facts
+ .attributes()
+ .iter()
+ .filter(move |attribute| match any_namespace {
+ false => attribute.name == name,
+ true => self.projection.attribute_name_forms(attribute.name).local == name,
+ })
+ .copied()
+ }
+}
+
+/// The projection's elements, as a selector is matched against them: their committed
+/// facts, their links, and the workspace the evaluation keeps sibling positions in, if any.
+pub(in crate::css::style) struct ProjectionSubject<'a> {
+ projection: &'a Projection,
+ /// Which side of the transaction being taken the elements' facts and relations are read on.
+ side: TransactionFactSide,
+ /// The outer tree scope asking about a part exposed from a shadow tree.
+ part_exposure_scope: Option<TreeScopeID>,
+ match_workspace: Option<&'a mut MatchScratch>,
+ /// The workspace the evaluation keeps sibling positions in where none is lent to it.
+ owned_match_workspace: Option<MatchScratch>,
+ positional_index_policy: PositionalIndexPolicy,
+ /// The structural read the evaluation noted last, which the candidates of one element note again
+ /// one after another.
+ last_structural_read: std::cell::Cell<Option<(StyleNodeID, StructuralRead)>>,
+}
+
+impl ProjectionSubject<'_> {
+ fn workspace_mut(&mut self) -> Option<&mut MatchScratch> {
+ match &mut self.match_workspace {
+ Some(workspace) => Some(&mut **workspace),
+ None => self.owned_match_workspace.as_mut(),
+ }
+ }
+
+ /// The distinct hosts the element's part names reach, or the host of the tree it stands in,
+ /// which is the only level it has where it exports no part.
+ fn part_exposure_hosts_of(&self, node: StyleNodeID) -> SmallVec<[StyleNodeID; 1]> {
+ let pairs = self.projection.part_hosts_of(node);
+ if pairs.is_empty() {
+ return self.projection.shadow_host_of(node).into_iter().collect();
+ }
+ let mut hosts = SmallVec::new();
+ for &(_, host) in pairs {
+ if !hosts.contains(&host) {
+ hosts.push(host);
+ }
+ }
+ hosts
+ }
+}
+
+impl<'a> SelectorSubject for ProjectionSubject<'a> {
+ type Node = StyleNodeID;
+ type Tree = ProjectionTree<'a>;
+ type Row = ProjectionRow<'a>;
+ type Attribute = AttributeFact;
+ type Features<'s>
+ = ProjectionRow<'a>
+ where
+ Self: 's;
+ type Incomplete = Incomplete;
+
+ #[inline]
+ fn tree(&self) -> ProjectionTree<'a> {
+ ProjectionTree {
+ projection: self.projection,
+ side: self.side,
+ }
+ }
+
+ #[inline]
+ fn row(&mut self, node: StyleNodeID) -> Result<ProjectionRow<'a>, Incomplete> {
+ let facts = self
+ .projection
+ .facts_on(self.side, node)
+ .ok_or(Incomplete::MissingFacts(node))?;
+ Ok(ProjectionRow {
+ facts,
+ projection: self.projection,
+ })
+ }
+
+ #[inline]
+ fn features(&self, row: ProjectionRow<'a>) -> ProjectionRow<'a> {
+ row
+ }
+
+ #[inline]
+ fn same_type(&self, row: ProjectionRow<'a>, other: ProjectionRow<'a>) -> bool {
+ row.facts.tag == other.facts.tag && row.facts.namespace() == other.facts.namespace()
+ }
+
+ #[inline]
+ fn attribute_value_atom(&self, attribute: AttributeFact) -> StyleAtomID {
+ attribute.value
+ }
+
+ #[inline]
+ fn attribute_value_text(&self, attribute: AttributeFact) -> Option<TokenizerInput<'_>> {
+ self.projection
+ .attribute_value_text(attribute.value)
+ .map(TokenizerInput::from)
+ }
+
+ #[inline]
+ fn has_state(&self, row: ProjectionRow<'a>, fact: StateFact) -> bool {
+ row.facts.states.contains(fact)
+ }
+
+ #[inline]
+ fn language_tag(&self, row: ProjectionRow<'a>) -> TokenizerInput<'_> {
+ let tag = self
+ .projection
+ .catalogs
+ .language_texts
+ .get(&row.facts.language())
+ .map_or(&[][..], AsRef::as_ref);
+ TokenizerInput::Utf16(tag)
+ }
+
+ #[inline]
+ fn directionality_is(&self, row: ProjectionRow<'a>, direction: StyleAtomID) -> bool {
+ row.facts.directionality() == direction
+ }
+
+ #[inline]
+ fn has_custom_state(&self, row: ProjectionRow<'a>, state: StyleAtomID) -> bool {
+ row.facts.custom_states().contains(&state)
+ }
+
+ #[inline]
+ fn heading_level(&self, row: ProjectionRow<'a>) -> u8 {
+ row.facts.heading_level()
+ }
+
+ /// Element children are rows and the links answer for them. A text or comment child is not,
+ /// so the element publishes whether it holds one.
+ #[inline]
+ fn is_empty(&mut self, node: StyleNodeID) -> Result<bool, Incomplete> {
+ let row = self.row(node)?;
+ Ok(self.projection.first_element_child_on(self.side, node).is_none() && !row.facts.has_text_content())
+ }
+
+ #[inline]
+ fn is_root(&self, node: StyleNodeID) -> bool {
+ self.projection.parent_on(self.side, node).is_none()
+ }
+
+ #[inline]
+ fn is_node(&self, node: StyleNodeID, named: StyleNodeID) -> bool {
+ node == named
+ }
+
+ #[inline]
+ fn has_part(&self, row: ProjectionRow<'a>, part: StyleAtomID) -> bool {
+ row.facts.parts().contains(&part)
+ }
+
+ fn part_exposure_hosts(&self, node: StyleNodeID) -> SmallVec<[StyleNodeID; 1]> {
+ self.part_exposure_hosts_of(node)
+ }
+
+ fn part_hosts_in_exposure_scope(&self, node: StyleNodeID) -> Option<SmallVec<[StyleNodeID; 1]>> {
+ let scope = self.part_exposure_scope?;
+ let mut hosts = self.part_exposure_hosts_of(node);
+ hosts.retain(|host| self.projection.tree_scope(*host) == scope);
+ Some(hosts)
+ }
+
+ fn exposes_part_to(&mut self, node: StyleNodeID, part: StyleAtomID, host: StyleNodeID) -> Result<bool, Incomplete> {
+ let row = self.row(node)?;
+ let pairs = self.projection.part_hosts_of(node);
+ Ok(match pairs.is_empty() {
+ // With no pairing recorded the element is addressable only under the names it carries,
+ // and all of them reach the host of the tree it stands in.
+ true => row.facts.parts().contains(&part),
+ false => pairs
+ .iter()
+ .any(|&(exposed, exposed_to)| exposed == part && exposed_to == host),
+ })
+ }
+
+ #[inline]
+ fn note_structural_read(&self, node: StyleNodeID, read: StructuralRead) {
+ if self.last_structural_read.get() == Some((node, read)) {
+ return;
+ }
+ self.last_structural_read.set(Some((node, read)));
+ self.projection.note_structural_read(self.side, node, read);
+ }
+
+ const FILTERS_BY_REQUIRED_DISPATCH_BLOOM: bool = true;
+
+ /// A row facts cannot answer for yet is never prejudged.
+ #[inline]
+ fn may_match_required(&self, required: u64, node: StyleNodeID) -> bool {
+ self.projection
+ .facts_on(self.side, node)
+ .is_none_or(|facts| facts.dispatch_bloom(false) & required == required)
+ }
+
+ /// NB: Only the workspace the evaluator owns keeps relative answers: an evaluator owning one
+ /// lives while the projection holds still, which is what an answer reads, as the sibling
+ /// positions it keeps do. A lent workspace may outlive a change of facts.
+ fn relative_answer_of(
+ &mut self,
+ list: super::super::selector_evaluation::SelectorListKey,
+ anchor: StyleNodeID,
+ bindings: &SelectorBindings<StyleNodeID>,
+ ) -> Option<bool> {
+ let workspace = self.owned_match_workspace.as_ref()?;
+ workspace.relative_answer(&RelativeAnswerKey::of_list(list, anchor, bindings))
+ }
+
+ fn record_relative_answer_of(
+ &mut self,
+ list: super::super::selector_evaluation::SelectorListKey,
+ anchor: StyleNodeID,
+ bindings: &SelectorBindings<StyleNodeID>,
+ answer: bool,
+ ) {
+ if let Some(workspace) = self.owned_match_workspace.as_mut() {
+ workspace.insert_relative_answer(RelativeAnswerKey::of_list(list, anchor, bindings), answer);
+ }
+ }
+
+ const REMEMBERS_SIBLING_ANSWERS: bool = true;
+
+ type WalkAnswers = SiblingAnswerTable;
+
+ /// NB: Only the workspace the evaluator owns keeps sibling answers, as it keeps relative ones.
+ fn walk_answers(
+ &mut self,
+ selector: super::super::selector_evaluation::SelectorKey,
+ bindings: &SelectorBindings<StyleNodeID>,
+ ) -> Option<SiblingAnswerTable> {
+ let key = SiblingAnswerKey {
+ selector,
+ scope_shadow_root: bindings.scope_shadow_root,
+ scope_root_instance: bindings.scope_root_instance,
+ part_exposure_scope: self.part_exposure_scope,
+ };
+ let workspace = self.owned_match_workspace.as_mut()?;
+ Some(workspace.sibling_table(key))
+ }
+
+ fn walk_answer(&self, table: SiblingAnswerTable, node: StyleNodeID) -> Option<bool> {
+ let workspace = self.owned_match_workspace.as_ref()?;
+ workspace.sibling_answer(table, node)
+ }
+
+ fn record_walk_answers(&mut self, table: SiblingAnswerTable, nodes: &[StyleNodeID], answer: bool) {
+ if let Some(workspace) = self.owned_match_workspace.as_mut() {
+ for &node in nodes {
+ workspace.insert_sibling_answer(table, node, answer);
+ }
+ }
+ }
+
+ #[inline]
+ fn sibling_index(&mut self, position: NthPosition, node: StyleNodeID) -> Result<Option<i64>, Incomplete> {
+ if position.step == 0 && self.positional_index_policy != PositionalIndexPolicy::All {
+ return Ok(None);
+ }
+ let (projection, fact_side) = (self.projection, self.side);
+ let Some(workspace) = self.workspace_mut() else {
+ return Ok(None);
+ };
+ workspace.indexed_sibling_position(
+ position,
+ node,
+ SiblingSequenceSource {
+ parent: projection.parent_on(fact_side, node),
+ children: |parent| projection.children_on(fact_side, parent).collect(),
+ type_of: |sibling| {
+ let facts = projection
+ .facts_on(fact_side, sibling)
+ .ok_or(Incomplete::MissingFacts(sibling))?;
+ Ok((facts.tag, facts.namespace()))
+ },
+ },
+ )
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ const DIV: StyleAtomID = StyleAtomID(1);
+ const THEME: StyleAtomID = StyleAtomID(10);
+ const ITEM: StyleAtomID = StyleAtomID(11);
+ const HREF: StyleAtomID = StyleAtomID(20);
+ const HREF_VALUE: StyleAtomID = StyleAtomID(21);
+
+ fn element(index: u32) -> StyleNodeID {
+ StyleNodeID::element(index)
+ }
+
+ /// `root > [first.item, second.item[href], third]`, root carrying `.theme`.
+ fn document() -> Projection {
+ let mut projection = Projection::default();
+ for index in 1..=4 {
+ projection.mint(element(index));
+ projection.set_connected(element(index), true);
+ projection.set_tag(element(index), DIV);
+ }
+ projection.set_class(element(1), THEME, true);
+ projection.set_first_element_child(element(1), Some(element(2)));
+ for index in 2..=4 {
+ projection.set_parent(element(index), Some(element(1)));
+ projection.set_previous_element_sibling(element(index), (index > 2).then(|| element(index - 1)));
+ projection.set_next_element_sibling(element(index), (index < 4).then(|| element(index + 1)));
+ }
+ projection.set_class(element(2), ITEM, true);
+ projection.set_class(element(3), ITEM, true);
+ projection.set_attribute(element(3), HREF, HREF_VALUE, true);
+ projection.commit();
+ projection
+ }
+
+ #[test]
+ fn a_catalog_copies_only_what_was_added_since_its_base_was_folded() {
+ let mut catalog: Catalog<u32> = Catalog::default();
+ let mut published = Vec::new();
+ for index in 1..=10_000_u32 {
+ catalog.insert(StyleAtomID(index), index);
+ published.push(catalog.clone());
+ if published.len() > 2 {
+ published.remove(0);
+ }
+ }
+ assert_eq!(catalog.get(&StyleAtomID(1)), Some(&1));
+ assert_eq!(catalog.get(&StyleAtomID(10_000)), Some(&10_000));
+ assert_eq!(catalog.iter().count(), 10_000);
+ // NB: Copying the whole catalog for each addition would copy about 50 million entries.
+ assert!(
+ catalog.copied < 10_000 * 10_000 / 8,
+ "additions copied {} entries",
+ catalog.copied
+ );
+ catalog.forget(&[StyleAtomID(1), StyleAtomID(10_000)]);
+ assert!(!catalog.contains_key(&StyleAtomID(1)) && !catalog.contains_key(&StyleAtomID(10_000)));
+ }
+
+ #[test]
+ fn live_atoms_are_those_the_rows_hold_with_their_attribute_name_forms() {
+ let mut projection = Projection::default();
+ let node = element(1);
+ projection.mint(node);
+ projection.set_tag(node, StyleAtomID(1));
+ projection.set_folded_tag(node, StyleAtomID(2));
+ projection.set_id(node, StyleAtomID(3));
+ projection.set_language(node, StyleAtomID(4));
+ projection.set_namespace(node, StyleAtomID(5));
+ projection.set_part_exposure(node, StyleAtomID(6));
+ projection.set_directionality(node, StyleAtomID(7));
+ projection.set_custom_states(node, &[StyleAtomID(8)]);
+ projection.set_parts(node, &[StyleAtomID(9)]);
+ projection.set_class(node, StyleAtomID(10), true);
+ let forms = AttributeNameForms {
+ local: StyleAtomID(13),
+ folded_name: StyleAtomID(14),
+ folded_local: StyleAtomID(15),
+ };
+ projection.note_attribute_name_forms(StyleAtomID(11), forms);
+ projection.note_attribute_name_forms(StyleAtomID(16), forms);
+ projection.set_attribute(node, StyleAtomID(11), StyleAtomID(12), true);
+ projection.commit();
+ projection.release();
+
+ let mut atoms = HashSet::default();
+ assert_eq!(projection.collect_atoms(&mut atoms), 2);
+ assert_eq!(atoms, (1..=15).map(StyleAtomID).collect());
+
+ // A name another root keeps live keeps its forms live with it.
+ let mut live: HashSet<StyleAtomID> = [StyleAtomID(16)].into_iter().collect();
+ projection.extend_live_attribute_name_forms(&mut live);
+ assert_eq!(live, [16, 13, 14, 15].into_iter().map(StyleAtomID).collect());
+
+ projection.retire(node);
+ projection.forget(node);
+ projection.release();
+ let mut atoms = HashSet::default();
+ projection.collect_atoms(&mut atoms);
+ assert!(atoms.is_empty());
+ }
+
+ #[test]
+ fn the_tree_reads_links() {
+ let projection = document();
+ assert_eq!(
+ projection.children(element(1)).collect::<Vec<_>>(),
+ [element(2), element(3), element(4)]
+ );
+ assert_eq!(projection.preorder(element(1)).count(), 4);
+ assert_eq!(projection.ancestors(element(4)).collect::<Vec<_>>(), [element(1)]);
+ }
+
+ #[test]
+ fn an_element_without_facts_is_incomplete_rather_than_featureless() {
+ let mut projection = document();
+ projection.mint(element(5));
+ projection.commit();
+ assert!(projection.facts(element(5)).is_none());
+ let mut subject = projection.subject_on(TransactionFactSide::After);
+ assert!(matches!(subject.row(element(5)), Err(Incomplete::MissingFacts(_))));
+ projection.ensure_facts(element(5));
+ assert!(
+ projection
+ .subject_on(TransactionFactSide::After)
+ .row(element(5))
+ .is_err(),
+ "facts are read as the last transaction committed them"
+ );
+ projection.commit();
+ assert!(
+ projection
+ .subject_on(TransactionFactSide::After)
+ .row(element(5))
+ .is_ok()
+ );
+ }
+
+ #[test]
+ fn facts_are_kept_sorted_and_edits_that_change_nothing_are_free() {
+ let mut projection = document();
+ projection.set_class(element(2), StyleAtomID(5), true);
+ projection.set_class(element(2), StyleAtomID(50), true);
+ projection.set_class(element(2), ITEM, false);
+ projection.commit();
+ let facts = projection.facts(element(2)).unwrap();
+ assert_eq!(facts.classes(), [StyleAtomID(5), StyleAtomID(50)]);
+ projection.set_attribute(element(3), HREF, StyleAtomID(22), true);
+ projection.set_attribute(element(3), StyleAtomID(15), StyleAtomID::NONE, true);
+ projection.commit();
+ let attributes = projection.facts(element(3)).unwrap().attributes();
+ assert_eq!(
+ attributes
+ .iter()
+ .map(|attribute| (attribute.name, attribute.value))
+ .collect::<Vec<_>>(),
+ [(StyleAtomID(15), StyleAtomID::NONE), (HREF, StyleAtomID(22))]
+ );
+
+ let mut fork = projection.clone();
+ let version = fork.test_writer.rows_version();
+ fork.set_class(element(2), StyleAtomID(5), true);
+ fork.set_attribute(element(3), HREF, StyleAtomID(22), true);
+ assert_eq!(
+ fork.test_writer.rows_version(),
+ version,
+ "an edit that changes nothing copies no chunk"
+ );
+ }
+
+ #[test]
+ fn the_dispatch_bloom_follows_the_facts() {
+ let mut projection = document();
+ projection.note_attribute_name_forms(
+ HREF,
+ AttributeNameForms {
+ local: StyleAtomID(22),
+ folded_name: StyleAtomID::NONE,
+ folded_local: StyleAtomID::NONE,
+ },
+ );
+ projection.set_attribute(element(4), HREF, HREF_VALUE, true);
+ projection.commit();
+ let facts = projection.facts(element(4)).unwrap();
+ let mut probes = Vec::new();
+ projection.for_each_dispatch_probe(facts, true, |key, value| probes.push((key, value)));
+ assert!(probes.contains(&(DispatchKey::Root, None)));
+ assert!(probes.contains(&(DispatchKey::AttributeName(HREF), Some(HREF_VALUE))));
+ assert!(probes.contains(&(DispatchKey::AttributeName(StyleAtomID(22)), Some(HREF_VALUE))));
+ for (key, _) in probes {
+ assert_ne!(facts.dispatch_bloom(true) & dispatch_bloom_bit(key), 0);
+ }
+ assert_eq!(facts.dispatch_bloom(false) & dispatch_bloom_bit(DispatchKey::Root), 0);
+
+ projection.set_class(element(4), THEME, true);
+ assert_eq!(
+ projection.facts(element(4)).unwrap().dispatch_bloom(false) & dispatch_bloom_bit(DispatchKey::Class(THEME)),
+ 0,
+ "an uncommitted write is not read"
+ );
+ projection.commit();
+ assert_ne!(
+ projection.facts(element(4)).unwrap().dispatch_bloom(false) & dispatch_bloom_bit(DispatchKey::Class(THEME)),
+ 0
+ );
+ }
+
+ #[test]
+ fn written_links_are_noted_until_the_transaction_is_released() {
+ let mut projection = document();
+ projection.release();
+ assert!(!projection.has_written_links());
+
+ // Facts alone write no links.
+ projection.set_class(element(4), ITEM, true);
+ assert!(!projection.has_written_links());
+
+ let relations = projection.written_relations(element(4)).unwrap();
+
+ projection.write_relations(element(4), None);
+ projection.write_relations(
+ element(3),
+ Some(TreeRelations {
+ next_element_sibling: None,
+ ..projection.written_relations(element(3)).unwrap()
+ }),
+ );
+ assert!(projection.relations_were_written(element(4)));
+ assert!(projection.relations_were_written(element(3)));
+ assert!(!projection.relations_were_written(element(2)));
+ projection.set_first_element_child(element(2), None);
+ assert!(
+ !projection.relations_were_written(element(2)),
+ "a first element child is no relation"
+ );
+ assert_eq!(
+ projection.links_written().collect::<Vec<_>>(),
+ [element(4), element(3), element(2)]
+ );
+ assert_eq!(
+ projection.relations_written().collect::<Vec<_>>(),
+ [element(4), element(3)]
+ );
+ assert_eq!(projection.written_relations(element(4)), None);
+ assert_eq!(projection.committed_relations(element(4)), Some(relations));
+
+ projection.commit();
+ assert!(projection.has_written_links(), "the barrier settles what was written");
+ assert_eq!(projection.committed_relations(element(4)), None);
+ projection.release();
+ assert!(!projection.has_written_links());
+ assert!(!projection.relations_were_written(element(4)));
+ }
+
+ #[test]
+ fn a_fork_shares_rows_until_either_side_writes() {
+ let projection = document();
+ let mut fork = projection.clone();
+ fork.set_class(element(4), ITEM, true);
+ fork.set_folded_tag(element(4), StyleAtomID(2));
+ fork.set_folded_tag(element(3), DIV);
+ fork.commit();
+ assert!(projection.facts(element(4)).unwrap().classes().is_empty());
+ assert_eq!(fork.facts(element(4)).unwrap().classes(), [ITEM]);
+ assert_eq!(fork.facts(element(4)).unwrap().folded_tag(), StyleAtomID(2));
+ assert_eq!(fork.facts(element(3)).unwrap().folded_tag(), StyleAtomID::NONE);
+ // The class list of an untouched element is the same allocation on both sides.
+ let ours = projection.facts(element(2)).unwrap().classes();
+ let theirs = fork.facts(element(2)).unwrap().classes();
+ assert!(!ours.is_empty() && std::ptr::eq(ours.as_ptr(), theirs.as_ptr()));
+ }
+
+ #[test]
+ fn shadow_trees_and_slots_shape_the_style_order() {
+ // host(1) -> shadow root(2) -> slot(3); host's light child 4 is assigned to the slot, its
+ // light child 5 is not; text 1 is assigned too.
+ let mut projection = Projection::default();
+ for index in 1..=5 {
+ projection.mint(element(index));
+ }
+ projection.set_shadow_root(element(1), element(2));
+ projection.set_first_element_child(element(2), Some(element(3)));
+ projection.set_parent(element(3), Some(element(2)));
+ projection.set_first_element_child(element(1), Some(element(4)));
+ projection.set_parent(element(4), Some(element(1)));
+ projection.set_next_element_sibling(element(4), Some(element(5)));
+ projection.set_parent(element(5), Some(element(1)));
+ projection.set_previous_element_sibling(element(5), Some(element(4)));
+ projection.set_assigned_slot(element(4), Some(element(3)));
+ let text = StyleNodeID::text(1);
+ projection.set_assigned_nodes(element(3), &[element(4), text]);
+ projection.commit();
+
+ assert_eq!(projection.host_of(element(2)), Some(element(1)));
+ assert_eq!(projection.inheritance_parent(element(3)), Some(element(1)));
+ assert_eq!(projection.inheritance_parent(element(4)), Some(element(3)));
+ assert_eq!(projection.shadow_host_of(element(3)), Some(element(1)));
+ assert_eq!(projection.assigned_slot_of(text), Some(element(3)));
+ assert_eq!(
+ projection.style_preorder(element(1)).collect::<Vec<_>>(),
+ [element(1), element(3), element(4), element(5)]
+ );
+
+ projection.retire_texts([text]);
+ assert_eq!(projection.assigned_nodes_of(element(3)), [element(4)]);
+ projection.retire(element(4));
+ assert!(projection.assigned_nodes_of(element(3)).is_empty());
+ projection.retire(element(3));
+ projection.retire(element(2));
+ assert_eq!(projection.shadow_root_of(element(1)), None);
+
+ // A new root for the host unpairs the old one.
+ projection.mint(element(2));
+ projection.mint(element(6));
+ projection.set_shadow_root(element(1), element(2));
+ projection.set_shadow_root(element(1), element(6));
+ assert_eq!(projection.host_of(element(2)), None);
+ assert_eq!(projection.host_of(element(6)), Some(element(1)));
+ }
+
+ #[test]
+ fn forgotten_atoms_leave_the_catalogs() {
+ let mut projection = document();
+ let text: Vec<u16> = "https://example.com".encode_utf16().collect();
+ projection.set_attribute_value_text(HREF_VALUE, RetainedUtf16FlyString::from_utf16(&text));
+ projection.set_attribute_value_text(HREF_VALUE, RetainedUtf16FlyString::from_utf16(&[]));
+ assert_eq!(
+ projection
+ .attribute_value_text(HREF_VALUE)
+ .map(RetainedUtf16FlyString::to_utf16)
+ .as_deref(),
+ Some(&text[..])
+ );
+ projection.set_language(element(2), StyleAtomID(30));
+ projection.set_language_text(StyleAtomID(30), &[u16::from(b'e'), u16::from(b'n')]);
+ projection.commit();
+ assert_eq!(projection.language_tag_of(element(2)).len(), 2);
+ projection.forget_atoms(&[HREF_VALUE, StyleAtomID(30)]);
+ assert_eq!(projection.attribute_value_text(HREF_VALUE), None);
+ assert!(projection.language_tag_of(element(2)).is_empty());
+
+ projection.forget(element(2));
+ assert!(projection.facts(element(2)).is_some());
+ projection.commit();
+ assert!(projection.facts(element(2)).is_none());
+ assert!(projection.is_live(element(2)));
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/projection/fact_lists.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/projection/fact_lists.rs
new file mode 100644
index 00000000000..11093c2fa9b
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/projection/fact_lists.rs
@@ -0,0 +1,690 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The facts of an element beside its tag and states: its id, namespace, language,
+//! directionality, tree scope and assigned slot, and its lists of classes, attributes, parts and
+//! custom states. They are packed into one allocation behind one pointer, which holds only what the
+//! element has and which a row holding none of them leaves null. The process interns them by
+//! content: siblings and cousins published alike point at one allocation, in every generation of
+//! the rows.
+
+use super::super::super::index::AttributeFact;
+use super::super::super::index::StyleAtomID;
+use crate::css::style::tree::{StyleNodeID, TreeScopeID};
+use smallvec::SmallVec;
+use std::alloc::Layout;
+use std::ptr::NonNull;
+use std::sync::atomic::AtomicU32;
+use std::sync::atomic::Ordering;
+use std::sync::atomic::fence;
+
+/// Which optional atoms and lists an allocation holds.
+#[derive(Clone, Copy, Default, PartialEq, Eq)]
+struct Present(u16);
+
+impl Present {
+ // Atoms, in the order their words follow the header.
+ const FOLDED_TAG: u16 = 1 << 0;
+ const PART_EXPOSURE: u16 = 1 << 1;
+ const NAMESPACE: u16 = 1 << 2;
+ const ID: u16 = 1 << 3;
+ const LANGUAGE: u16 = 1 << 4;
+ const DIRECTIONALITY: u16 = 1 << 5;
+ const TREE_SCOPE: u16 = 1 << 6;
+ const ASSIGNED_SLOT: u16 = 1 << 7;
+ const ATOMS: u16 = 0xff;
+ // Lists, whose counts follow the atoms' words, in this order, and whose payloads follow the counts.
+ const CLASSES: u16 = 1 << 8;
+ const ATTRIBUTES: u16 = 1 << 9;
+ const PARTS: u16 = 1 << 10;
+ const CUSTOM_STATES: u16 = 1 << 11;
+ const LISTS: [u16; 4] = [Self::CLASSES, Self::ATTRIBUTES, Self::PARTS, Self::CUSTOM_STATES];
+
+ fn has(self, bit: u16) -> bool {
+ self.0 & bit != 0
+ }
+
+ /// How many words of `bits` that come before `bit` the allocation holds.
+ fn words_before(self, bits: u16, bit: u16) -> usize {
+ (self.0 & bits & (bit - 1)).count_ones() as usize
+ }
+
+ fn atom_words(self) -> usize {
+ (self.0 & Self::ATOMS).count_ones() as usize
+ }
+
+ fn count_words(self) -> usize {
+ (self.0 & !Self::ATOMS).count_ones() as usize
+ }
+}
+
+/// The start of a packed allocation: a word per atom the element has, then a count per list it has, then the lists'
+/// entries, classes, attributes (two words each), parts and custom states.
+#[repr(C)]
+struct Header {
+ references: AtomicU32,
+ present: Present,
+ // NB: Two bytes stay free here.
+ _free: u16,
+ /// The Bloom summary of the dispatch keys the lists carry, low half first.
+ bloom: [u32; 2],
+}
+
+const _: () = assert!(size_of::<Header>() == 16 && align_of::<Header>() == 4);
+// NB: Every word that follows the header is a u32.
+const _: () = assert!(align_of::<StyleAtomID>() == 4 && size_of::<StyleAtomID>() == 4);
+const _: () = assert!(align_of::<AttributeFact>() == 4 && size_of::<AttributeFact>() == 8);
+
+/// The rare facts of one element, shared by every copy of its row.
+#[derive(Default)]
+pub(super) struct FactLists(Option<NonNull<Header>>);
+
+// SAFETY: The allocation is immutable once made, and its reference count is atomic.
+unsafe impl Send for FactLists {}
+// SAFETY: As above.
+unsafe impl Sync for FactLists {}
+
+/// The identity of one allocation of lists, which interning makes one per content.
+#[derive(Clone, Copy, PartialEq, Eq)]
+pub(in crate::css::style) struct FactListsIdentity(Option<NonNull<Header>>);
+
+/// The words of every list's entries, by `Present::LISTS` order.
+fn entry_words(counts: [u32; 4]) -> [usize; 4] {
+ [
+ counts[0] as usize,
+ 2 * counts[1] as usize,
+ counts[2] as usize,
+ counts[3] as usize,
+ ]
+}
+
+fn layout(present: Present, counts: [u32; 4]) -> Layout {
+ let words = present.atom_words() + present.count_words() + entry_words(counts).iter().sum::<usize>();
+ Layout::from_size_align(size_of::<Header>() + 4 * words, align_of::<Header>())
+ .expect("an element's fact lists fit in memory")
+}
+
+impl FactLists {
+ fn new(edit: &FactListsEdit) -> Self {
+ if edit.is_empty() {
+ return Self(None);
+ }
+ let count = |length: usize| u32::try_from(length).expect("an element's fact list fits in u32");
+ let counts = [
+ count(edit.classes.len()),
+ count(edit.attributes.len()),
+ count(edit.parts.len()),
+ count(edit.custom_states.len()),
+ ];
+ let atoms: [(u16, u32); 8] = [
+ (Present::FOLDED_TAG, edit.folded_tag.0),
+ (Present::PART_EXPOSURE, edit.part_exposure.0),
+ (Present::NAMESPACE, edit.namespace.0),
+ (Present::ID, edit.id.0),
+ (Present::LANGUAGE, edit.language.0),
+ (Present::DIRECTIONALITY, edit.directionality.0),
+ (Present::TREE_SCOPE, edit.tree_scope.0),
+ (Present::ASSIGNED_SLOT, edit.assigned_slot.map_or(0, StyleNodeID::raw)),
+ ];
+ let mut present = Present::default();
+ for &(bit, word) in &atoms {
+ if word != 0 {
+ present.0 |= bit;
+ }
+ }
+ for (bit, &count) in Present::LISTS.iter().zip(&counts) {
+ if count != 0 {
+ present.0 |= bit;
+ }
+ }
+ let layout = layout(present, counts);
+ // SAFETY: The layout is never zero-sized, as it holds the header.
+ let pointer = unsafe { std::alloc::alloc(layout) }.cast::<Header>();
+ let Some(header) = NonNull::new(pointer) else {
+ std::alloc::handle_alloc_error(layout);
+ };
+ // SAFETY: The allocation holds the header and the words after it, and every write stays within it.
+ unsafe {
+ header.write(Header {
+ references: AtomicU32::new(1),
+ present,
+ _free: 0,
+ bloom: [edit.bloom as u32, (edit.bloom >> 32) as u32],
+ });
+ let mut cursor = header.as_ptr().add(1).cast::<u32>();
+ for &(_, word) in atoms.iter().filter(|&&(_, word)| word != 0) {
+ cursor.write(word);
+ cursor = cursor.add(1);
+ }
+ for &count in counts.iter().filter(|&&count| count != 0) {
+ cursor.write(count);
+ cursor = cursor.add(1);
+ }
+ let mut cursor = cursor.cast::<StyleAtomID>();
+ cursor.copy_from_nonoverlapping(edit.classes.as_ptr(), edit.classes.len());
+ cursor = cursor.add(edit.classes.len());
+ cursor
+ .cast::<AttributeFact>()
+ .copy_from_nonoverlapping(edit.attributes.as_ptr(), edit.attributes.len());
+ cursor = cursor.add(2 * edit.attributes.len());
+ cursor.copy_from_nonoverlapping(edit.parts.as_ptr(), edit.parts.len());
+ cursor = cursor.add(edit.parts.len());
+ cursor.copy_from_nonoverlapping(edit.custom_states.as_ptr(), edit.custom_states.len());
+ }
+ Self(Some(header))
+ }
+
+ fn header(&self) -> Option<&Header> {
+ // SAFETY: The allocation lives while this reference to it does.
+ self.0.map(|header| unsafe { header.as_ref() })
+ }
+
+ /// The words that follow the header.
+ fn words(header: &Header) -> *const u32 {
+ // SAFETY: The words follow the header in its allocation.
+ unsafe { std::ptr::from_ref(header).add(1).cast::<u32>() }
+ }
+
+ /// The word of the atom `bit`, where the allocation holds one.
+ fn atom(&self, bit: u16) -> Option<u32> {
+ let header = self.header()?;
+ if !header.present.has(bit) {
+ return None;
+ }
+ // SAFETY: A present atom's word is among the atom words that follow the header.
+ Some(unsafe {
+ Self::words(header)
+ .add(header.present.words_before(Present::ATOMS, bit))
+ .read()
+ })
+ }
+
+ /// The counts of every list, by `Present::LISTS` order.
+ fn counts(header: &Header) -> [u32; 4] {
+ let present = header.present;
+ let first_count = present.atom_words();
+ Present::LISTS.map(|bit| match present.has(bit) {
+ // SAFETY: A present list's count is among the count words that follow the atom words.
+ true => unsafe {
+ Self::words(header)
+ .add(first_count + present.words_before(!Present::ATOMS, bit))
+ .read()
+ },
+ false => 0,
+ })
+ }
+
+ /// The first atom of list `list`, an index into `Present::LISTS`, and its length.
+ fn list(&self, list: usize) -> Option<(*const StyleAtomID, usize)> {
+ let header = self.header()?;
+ if !header.present.has(Present::LISTS[list]) {
+ return None;
+ }
+ let counts = Self::counts(header);
+ let offset = header.present.atom_words()
+ + header.present.count_words()
+ + entry_words(counts).iter().take(list).sum::<usize>();
+ // SAFETY: The offset stays within the allocation, which holds every list.
+ let first = unsafe { Self::words(header).add(offset).cast::<StyleAtomID>() };
+ Some((first, counts[list] as usize))
+ }
+
+ fn atoms(&self, list: usize) -> &[StyleAtomID] {
+ match self.list(list) {
+ // SAFETY: The list was written when the allocation was made, and lives with it.
+ Some((first, length)) => unsafe { ak::slice_from_raw_parts(first, length) },
+ None => &[],
+ }
+ }
+
+ /// Sorted.
+ pub(super) fn classes(&self) -> &[StyleAtomID] {
+ self.atoms(0)
+ }
+
+ /// Sorted by name, each with the atom of its value.
+ pub(super) fn attributes(&self) -> &[AttributeFact] {
+ match self.list(1) {
+ // SAFETY: The attributes were written as such when the allocation was made, and live
+ // with it.
+ Some((first, length)) => unsafe { ak::slice_from_raw_parts(first.cast::<AttributeFact>(), length) },
+ None => &[],
+ }
+ }
+
+ pub(super) fn parts(&self) -> &[StyleAtomID] {
+ self.atoms(2)
+ }
+
+ pub(super) fn custom_states(&self) -> &[StyleAtomID] {
+ self.atoms(3)
+ }
+
+ pub(super) fn folded_tag(&self) -> StyleAtomID {
+ StyleAtomID(self.atom(Present::FOLDED_TAG).unwrap_or(0))
+ }
+
+ pub(super) fn part_exposure(&self) -> StyleAtomID {
+ StyleAtomID(self.atom(Present::PART_EXPOSURE).unwrap_or(0))
+ }
+
+ pub(super) fn namespace(&self) -> StyleAtomID {
+ StyleAtomID(self.atom(Present::NAMESPACE).unwrap_or(0))
+ }
+
+ pub(super) fn id(&self) -> StyleAtomID {
+ StyleAtomID(self.atom(Present::ID).unwrap_or(0))
+ }
+
+ pub(super) fn language(&self) -> StyleAtomID {
+ StyleAtomID(self.atom(Present::LANGUAGE).unwrap_or(0))
+ }
+
+ pub(super) fn directionality(&self) -> StyleAtomID {
+ StyleAtomID(self.atom(Present::DIRECTIONALITY).unwrap_or(0))
+ }
+
+ pub(super) fn tree_scope(&self) -> TreeScopeID {
+ self.atom(Present::TREE_SCOPE)
+ .map_or(TreeScopeID::DOCUMENT, TreeScopeID)
+ }
+
+ pub(super) fn assigned_slot(&self) -> Option<StyleNodeID> {
+ self.atom(Present::ASSIGNED_SLOT).and_then(StyleNodeID::from_raw)
+ }
+
+ /// The Bloom summary of the dispatch keys the lists carry.
+ pub(super) fn identity(&self) -> FactListsIdentity {
+ FactListsIdentity(self.0)
+ }
+
+ pub(super) fn bloom(&self) -> u64 {
+ self.header().map_or(0, |header| {
+ u64::from(header.bloom[0]) | (u64::from(header.bloom[1]) << 32)
+ })
+ }
+
+ /// The facts to edit, whose lists stay borrowed until an edit changes them.
+ pub(super) fn edit(&self) -> FactListsEdit<'_> {
+ FactListsEdit {
+ classes: EditedList::Held(self.classes()),
+ attributes: EditedList::Held(self.attributes()),
+ parts: EditedList::Held(self.parts()),
+ custom_states: EditedList::Held(self.custom_states()),
+ folded_tag: self.folded_tag(),
+ part_exposure: self.part_exposure(),
+ namespace: self.namespace(),
+ id: self.id(),
+ language: self.language(),
+ directionality: self.directionality(),
+ bloom: self.bloom(),
+ tree_scope: self.tree_scope(),
+ assigned_slot: self.assigned_slot(),
+ }
+ }
+
+ fn holds_the_same_as(&self, other: &Self) -> bool {
+ self.classes() == other.classes()
+ && self.attributes() == other.attributes()
+ && self.parts() == other.parts()
+ && self.custom_states() == other.custom_states()
+ && self.folded_tag() == other.folded_tag()
+ && self.part_exposure() == other.part_exposure()
+ && self.namespace() == other.namespace()
+ && self.id() == other.id()
+ && self.language() == other.language()
+ && self.directionality() == other.directionality()
+ && self.bloom() == other.bloom()
+ && self.tree_scope() == other.tree_scope()
+ && self.assigned_slot() == other.assigned_slot()
+ }
+
+ /// Whether the two hold the same facts of their elements, leaving aside their tree scopes and assigned slots, which
+ /// are their elements' links.
+ pub(super) fn says_the_same_as(&self, other: &Self) -> bool {
+ self.0 == other.0
+ || (self.classes() == other.classes()
+ && self.attributes() == other.attributes()
+ && self.parts() == other.parts()
+ && self.custom_states() == other.custom_states()
+ && self.folded_tag() == other.folded_tag()
+ && self.part_exposure() == other.part_exposure()
+ && self.namespace() == other.namespace()
+ && self.id() == other.id()
+ && self.language() == other.language()
+ && self.directionality() == other.directionality())
+ }
+
+ /// Whether these are the facts `edit` holds.
+ fn holds(&self, edit: &FactListsEdit) -> bool {
+ self.classes() == &*edit.classes
+ && self.attributes() == &*edit.attributes
+ && self.parts() == &*edit.parts
+ && self.custom_states() == &*edit.custom_states
+ && self.folded_tag() == edit.folded_tag
+ && self.part_exposure() == edit.part_exposure
+ && self.namespace() == edit.namespace
+ && self.id() == edit.id
+ && self.language() == edit.language
+ && self.directionality() == edit.directionality
+ && self.bloom() == edit.bloom
+ && self.tree_scope() == edit.tree_scope
+ && self.assigned_slot() == edit.assigned_slot
+ }
+
+ /// The hash of what the lists hold, as [`FactListsEdit::content_hash`] gives it for an edit holding the same.
+ fn content_hash(&self) -> u64 {
+ self.edit().content_hash()
+ }
+
+ /// How many references to the allocation are live, the interning table's among them.
+ fn references(&self) -> u32 {
+ self.header()
+ .map_or(0, |header| header.references.load(Ordering::Acquire))
+ }
+
+ pub(super) fn heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {
+ match self.header() {
+ // NB: The process's table holds an entry for every list, which the first document whose rows reach the
+ // list counts with it.
+ Some(header) if sizer.first_sight(std::ptr::from_ref(header)) => {
+ layout(header.present, Self::counts(header)).size()
+ + crate::heap_size::live_hash_table_bytes(1, size_of::<Self>())
+ }
+ _ => 0,
+ }
+ }
+}
+
+impl Clone for FactLists {
+ fn clone(&self) -> Self {
+ if let Some(header) = self.header() {
+ let references = header.references.fetch_add(1, Ordering::Relaxed);
+ assert!(references < u32::MAX / 2, "fact lists reference count overflow");
+ }
+ Self(self.0)
+ }
+}
+
+impl Drop for FactLists {
+ fn drop(&mut self) {
+ let Some(header) = self.header() else {
+ return;
+ };
+ if header.references.fetch_sub(1, Ordering::Release) != 1 {
+ return;
+ }
+ fence(Ordering::Acquire);
+ let layout = layout(header.present, Self::counts(header));
+ // SAFETY: This was the last reference, so nothing reads the allocation after this.
+ unsafe { std::alloc::dealloc(self.0.expect("the header was read").as_ptr().cast(), layout) };
+ }
+}
+
+impl PartialEq for FactLists {
+ fn eq(&self, other: &Self) -> bool {
+ self.0 == other.0 || (self.0.is_some() && other.0.is_some() && self.holds_the_same_as(other))
+ }
+}
+
+/// One list of an edit: the list as it stands until the edit changes it.
+pub(super) enum EditedList<'a, T: Copy, const INLINE: usize> {
+ Held(&'a [T]),
+ Changed(SmallVec<[T; INLINE]>),
+}
+
+impl<T: Copy, const INLINE: usize> EditedList<'_, T, INLINE> {
+ pub(super) fn to_mut(&mut self) -> &mut SmallVec<[T; INLINE]> {
+ if let Self::Held(list) = *self {
+ *self = Self::Changed(SmallVec::from_slice(list));
+ }
+ match self {
+ Self::Changed(list) => list,
+ Self::Held(_) => unreachable!("the list was just copied out"),
+ }
+ }
+}
+
+impl<T: Copy, const INLINE: usize> std::ops::Deref for EditedList<'_, T, INLINE> {
+ type Target = [T];
+
+ fn deref(&self) -> &[T] {
+ match self {
+ Self::Held(list) => list,
+ Self::Changed(list) => list,
+ }
+ }
+}
+
+/// The rare facts of an element, to edit.
+pub(super) struct FactListsEdit<'a> {
+ pub(super) classes: EditedList<'a, StyleAtomID, 4>,
+ pub(super) attributes: EditedList<'a, AttributeFact, 4>,
+ pub(super) parts: EditedList<'a, StyleAtomID, 2>,
+ pub(super) custom_states: EditedList<'a, StyleAtomID, 2>,
+ pub(super) folded_tag: StyleAtomID,
+ pub(super) part_exposure: StyleAtomID,
+ pub(super) namespace: StyleAtomID,
+ pub(super) id: StyleAtomID,
+ pub(super) language: StyleAtomID,
+ pub(super) directionality: StyleAtomID,
+ /// The Bloom summary of the dispatch keys the lists carry, which the writer computes before it makes them.
+ pub(super) bloom: u64,
+ pub(super) tree_scope: TreeScopeID,
+ pub(super) assigned_slot: Option<StyleNodeID>,
+}
+
+impl FactListsEdit<'_> {
+ fn is_empty(&self) -> bool {
+ self.classes.is_empty()
+ && self.attributes.is_empty()
+ && self.parts.is_empty()
+ && self.custom_states.is_empty()
+ && self.folded_tag.is_none()
+ && self.part_exposure.is_none()
+ && self.namespace.is_none()
+ && self.id.is_none()
+ && self.language.is_none()
+ && self.directionality.is_none()
+ && self.tree_scope == TreeScopeID::DOCUMENT
+ && self.assigned_slot.is_none()
+ }
+
+ fn content_hash(&self) -> u64 {
+ use std::hash::{Hash, Hasher};
+ let mut hasher = crate::fast_hash::fast_hasher();
+ self.classes.hash(&mut hasher);
+ for attribute in self.attributes.iter() {
+ (attribute.name, attribute.value).hash(&mut hasher);
+ }
+ self.parts.hash(&mut hasher);
+ self.custom_states.hash(&mut hasher);
+ (
+ self.folded_tag,
+ self.part_exposure,
+ self.namespace,
+ self.id,
+ self.language,
+ self.directionality,
+ self.bloom,
+ self.tree_scope,
+ self.assigned_slot,
+ )
+ .hash(&mut hasher);
+ hasher.finish()
+ }
+}
+
+/// The fact lists of the process, by content: one allocation per content while any row of any
+/// document holds it, so that rows holding the same facts hold the same pointer. Each entry is
+/// the lists' pointer alone, found by the hash of their content, which the table recomputes from
+/// the lists themselves as it grows.
+pub(crate) struct FactListsTable {
+ lists: hashbrown::HashTable<FactLists>,
+ /// How many lists the table holds before it drops those only it holds: twice as many as the
+ /// last drop kept, so dropping costs a constant per list interned.
+ drop_threshold: usize,
+}
+
+const _: () = assert!(size_of::<FactLists>() == 8);
+
+/// How many lists the table holds before it first drops those only it holds.
+const MINIMUM_DROP_THRESHOLD: usize = 1024;
+
+impl Default for FactListsTable {
+ fn default() -> Self {
+ Self {
+ lists: hashbrown::HashTable::new(),
+ drop_threshold: MINIMUM_DROP_THRESHOLD,
+ }
+ }
+}
+
+impl FactListsTable {
+ /// The fact lists holding what `edit` holds, whose content hashes to `hash`.
+ fn intern(&mut self, edit: &FactListsEdit, hash: u64) -> FactLists {
+ if let Some(lists) = self.lists.find(hash, |lists| lists.holds(edit)) {
+ return lists.clone();
+ }
+ if self.lists.len() >= self.drop_threshold {
+ self.drop_unheld();
+ }
+ let lists = FactLists::new(edit);
+ self.lists.insert_unique(hash, lists.clone(), FactLists::content_hash);
+ lists
+ }
+
+ /// Drops the lists no row holds any more.
+ fn drop_unheld(&mut self) {
+ self.lists.retain(|lists| lists.references() > 1);
+ self.drop_threshold = (2 * self.lists.len()).max(MINIMUM_DROP_THRESHOLD);
+ }
+}
+
+/// How many fact lists a writer keeps to share without asking the process's table, each in the slot its content
+/// hashes to.
+const RECENT_FACT_LISTS: usize = 64;
+
+/// The fact lists a writer made last, by the hash of what they hold, which an element made the same facts again shares
+/// without taking the process's table's lock, as siblings and cousins published alike do.
+#[derive(Clone)]
+pub(super) struct RecentFactLists(Box<[FactLists; RECENT_FACT_LISTS]>);
+
+impl Default for RecentFactLists {
+ fn default() -> Self {
+ Self(Box::new(std::array::from_fn(|_| FactLists::default())))
+ }
+}
+
+impl RecentFactLists {
+ /// Fact lists holding what `edit` holds: one made recently where one holds it, or the ones the
+ /// process's table interned.
+ pub(super) fn make(&mut self, edit: &FactListsEdit, table: &std::sync::Mutex<FactListsTable>) -> FactLists {
+ if edit.is_empty() {
+ return FactLists(None);
+ }
+ let hash = edit.content_hash();
+ let slot = &mut self.0[(hash % RECENT_FACT_LISTS as u64) as usize];
+ if slot.0.is_some() && slot.holds(edit) {
+ return slot.clone();
+ }
+ let lists = table
+ .lock()
+ .unwrap_or_else(std::sync::PoisonError::into_inner)
+ .intern(edit, hash);
+ *slot = lists.clone();
+ lists
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn lists_hash_as_the_edit_they_were_made_from() {
+ let edit = FactListsEdit {
+ classes: EditedList::Held(&[StyleAtomID(1), StyleAtomID(2)]),
+ attributes: EditedList::Held(&[AttributeFact {
+ name: StyleAtomID(3),
+ value: StyleAtomID(4),
+ }]),
+ parts: EditedList::Held(&[StyleAtomID(5)]),
+ custom_states: EditedList::Held(&[StyleAtomID(6)]),
+ folded_tag: StyleAtomID(7),
+ part_exposure: StyleAtomID(8),
+ namespace: StyleAtomID(9),
+ id: StyleAtomID(10),
+ language: StyleAtomID(11),
+ directionality: StyleAtomID(12),
+ bloom: 0x1234_5678_9abc_def0,
+ tree_scope: TreeScopeID(13),
+ assigned_slot: StyleNodeID::from_raw(14),
+ };
+ let lists = FactLists::new(&edit);
+ assert_eq!(lists.content_hash(), edit.content_hash());
+ assert!(lists.holds(&edit));
+ }
+
+ #[test]
+ fn every_combination_of_atoms_reads_back() {
+ for mask in 0_u32..256 {
+ let atom = |bit: u32, value: u32| if mask & (1 << bit) != 0 { value } else { 0 };
+ let empty = FactLists::default();
+ let mut edit = empty.edit();
+ edit.folded_tag = StyleAtomID(atom(0, 11));
+ edit.part_exposure = StyleAtomID(atom(1, 12));
+ edit.namespace = StyleAtomID(atom(2, 13));
+ edit.id = StyleAtomID(atom(3, 14));
+ edit.language = StyleAtomID(atom(4, 15));
+ edit.directionality = StyleAtomID(atom(5, 16));
+ edit.tree_scope = TreeScopeID(atom(6, 17));
+ edit.assigned_slot = StyleNodeID::from_raw(atom(7, 18));
+ edit.classes = EditedList::Changed(SmallVec::from_slice(&[StyleAtomID(20 + mask)]));
+ edit.parts = EditedList::Held(&[StyleAtomID(21), StyleAtomID(22)]);
+ let lists = FactLists::new(&edit);
+ assert!(lists.holds(&edit), "mask {mask:#x}");
+ assert_eq!(lists.classes(), &*edit.classes);
+ assert_eq!(lists.parts(), &*edit.parts);
+ assert!(lists.attributes().is_empty() && lists.custom_states().is_empty());
+ }
+ }
+
+ #[test]
+ fn long_lists_read_back() {
+ for length in [0_u32, 1, 70000] {
+ let empty = FactLists::default();
+ let mut edit = empty.edit();
+ edit.classes = EditedList::Changed((0..length).map(StyleAtomID).collect());
+ edit.attributes = EditedList::Changed(
+ (0..length)
+ .map(|index| AttributeFact {
+ name: StyleAtomID(index),
+ value: StyleAtomID(index + 1),
+ })
+ .collect(),
+ );
+ edit.custom_states = EditedList::Held(&[StyleAtomID(9)]);
+ let lists = FactLists::new(&edit);
+ assert_eq!(lists.classes(), &*edit.classes);
+ assert_eq!(lists.attributes(), &*edit.attributes);
+ assert_eq!(lists.custom_states(), &*edit.custom_states);
+ }
+ }
+
+ #[test]
+ fn the_table_hands_out_one_lists_per_content() {
+ let mut table = FactListsTable::default();
+ let empty = FactLists::default();
+ let mut edit = empty.edit();
+ edit.id = StyleAtomID(1);
+ let first = table.intern(&edit, edit.content_hash());
+ let second = table.intern(&edit, edit.content_hash());
+ assert_eq!(first.0, second.0);
+ edit.id = StyleAtomID(2);
+ assert_ne!(table.intern(&edit, edit.content_hash()).0, first.0);
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/projection/tree_reads.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/projection/tree_reads.rs
new file mode 100644
index 00000000000..5e0076bf7f8
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/projection/tree_reads.rs
@@ -0,0 +1,150 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Walks over the projection's links that answer what the host tree answers of an element's place
+//! in the shadow-including and flat trees.
+
+use super::super::super::tree::StyleNodeID;
+use super::Projection;
+
+impl Projection {
+ /// Every live element identity, including the roots of shadow trees, in element order.
+ #[cfg(test)]
+ pub(in crate::css::style) fn live_nodes(&self) -> impl Iterator<Item = StyleNodeID> + '_ {
+ (1..self.slot_count).filter_map(|index| {
+ let node = StyleNodeID::element(u32::try_from(index).expect("style node index space exhausted"));
+ self.is_live(node).then_some(node)
+ })
+ }
+
+ /// The element's parent in the tree it is in, or a shadow root's host. A text node has no row,
+ /// so its parent is the host tree's to answer.
+ #[must_use]
+ pub(in crate::css::style) fn parent_or_shadow_host(&self, node: StyleNodeID) -> Option<StyleNodeID> {
+ assert!(node.element_index().is_some(), "only an element has projection links");
+ self.parent(node).or_else(|| self.host_of(node))
+ }
+
+ /// Whether the element `node` is `root` or lies below it in the shadow-including tree: the climb
+ /// out of a shadow tree continues at the host rather than stopping there. A climb that runs out
+ /// of parents has reached a child of the document, which no element contains.
+ #[must_use]
+ pub(in crate::css::style) fn is_in_shadow_including_subtree_of(
+ &self,
+ node: StyleNodeID,
+ root: StyleNodeID,
+ ) -> bool {
+ assert!(node.element_index().is_some(), "only an element has projection links");
+ if root.text_index().is_some() {
+ return false;
+ }
+ let mut candidate = node;
+ loop {
+ if candidate == root {
+ return true;
+ }
+ candidate = match self.host_of(candidate).or_else(|| self.parent(candidate)) {
+ Some(next) => next,
+ None => return false,
+ };
+ }
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ fn element(index: u32) -> StyleNodeID {
+ StyleNodeID::element(index)
+ }
+
+ /// document(1) -> host(2) -> [light 4, light 5]; host's shadow root(3) -> slot(6) -> fallback 7.
+ /// Light 4 and text 1 are assigned to the slot. Element 8 is minted and never linked.
+ fn shadow_document() -> Projection {
+ let mut projection = Projection::default();
+ for index in 1..=8 {
+ projection.mint(element(index));
+ }
+ let link_children = |projection: &mut Projection, parent: u32, children: &[u32]| {
+ projection.set_first_element_child(element(parent), children.first().map(|&child| element(child)));
+ for (position, &child) in children.iter().enumerate() {
+ projection.set_parent(element(child), Some(element(parent)));
+ let previous = position.checked_sub(1).map(|previous| element(children[previous]));
+ projection.set_previous_element_sibling(element(child), previous);
+ projection
+ .set_next_element_sibling(element(child), children.get(position + 1).map(|&next| element(next)));
+ }
+ };
+ link_children(&mut projection, 1, &[2]);
+ link_children(&mut projection, 2, &[4, 5]);
+ link_children(&mut projection, 3, &[6]);
+ link_children(&mut projection, 6, &[7]);
+ projection.set_shadow_root(element(2), element(3));
+ projection.set_assigned_slot(element(4), Some(element(6)));
+ projection.set_assigned_nodes(element(6), &[element(4), StyleNodeID::text(1)]);
+ // Style reads an element's links as the last transaction committed them.
+ projection.commit();
+ projection
+ }
+
+ #[test]
+ fn live_nodes_are_the_minted_elements_that_did_not_retire() {
+ let mut projection = shadow_document();
+ assert_eq!(
+ projection.live_nodes().collect::<Vec<_>>(),
+ (1..=8).map(element).collect::<Vec<_>>()
+ );
+ projection.retire(element(5));
+ projection.retire(element(8));
+ assert_eq!(
+ projection.live_nodes().collect::<Vec<_>>(),
+ [1, 2, 3, 4, 6, 7].map(element)
+ );
+ }
+
+ #[test]
+ fn parent_or_shadow_host_climbs_from_a_shadow_root_to_its_host() {
+ let projection = shadow_document();
+ assert_eq!(projection.parent_or_shadow_host(element(6)), Some(element(3)));
+ assert_eq!(projection.parent_or_shadow_host(element(3)), Some(element(2)));
+ // A slotted element continues through its light-tree parent.
+ assert_eq!(projection.parent_or_shadow_host(element(4)), Some(element(2)));
+ assert_eq!(projection.parent_or_shadow_host(element(1)), None);
+ assert_eq!(projection.parent_or_shadow_host(element(8)), None);
+ }
+
+ #[test]
+ fn shadow_including_subtrees_cross_into_shadow_trees() {
+ let projection = shadow_document();
+ let is_in = |node, root| projection.is_in_shadow_including_subtree_of(element(node), element(root));
+ assert!(is_in(7, 7));
+ assert!(is_in(7, 3));
+ assert!(is_in(7, 2));
+ assert!(is_in(7, 1));
+ assert!(is_in(4, 2));
+ assert!(!is_in(4, 6));
+ assert!(!is_in(2, 3));
+ assert!(!is_in(5, 4));
+ assert!(!is_in(8, 1));
+ assert!(!projection.is_in_shadow_including_subtree_of(element(4), StyleNodeID::text(1)));
+ }
+
+ #[test]
+ fn flat_tree_parents_follow_shadow_roots_and_slots() {
+ let mut projection = shadow_document();
+ // The host's flat children are its shadow root's, and the slot's are its assigned nodes,
+ // which leave its fallback and the unassigned light child out.
+ assert_eq!(projection.flat_tree_parent(element(4)), Some(element(6)));
+ assert_eq!(projection.flat_tree_parent(element(5)), None);
+ assert_eq!(projection.flat_tree_parent(element(7)), None);
+
+ // With nothing assigned, the slot shows its fallback content.
+ projection.set_assigned_slot(element(4), None);
+ projection.set_assigned_nodes(element(6), &[]);
+ assert_eq!(projection.flat_tree_parent(element(7)), Some(element(6)));
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/projection/writer.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/projection/writer.rs
new file mode 100644
index 00000000000..ed00878e10d
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/projection/writer.rs
@@ -0,0 +1,838 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The host's side of the projection: the rows, which the host writes as its DOM changes and nothing else writes, and
+//! the catalogs that spell their atoms. At each barrier the host publishes them to the render owner's [`Projection`]:
+//! a generation of the rows that shares every chunk the host does not write again (the copy-on-write spine of a
+//! [`CowColumn`]), with the elements written since the last barrier. The render owner reads only what was published,
+//! so the host's writes beside a transaction in flight stay out of it without a copy.
+//!
+//! An element that left the tree is retired and forgotten here as its departure is published: the generations
+//! published before keep its facts, which is where the render owner reads what a departed element carried.
+
+use super::super::super::fast_hash::FastMap as HashMap;
+use super::super::super::index::AttributeFact;
+use super::super::super::index::AttributeNameForms;
+use super::super::super::index::StyleAtomID;
+use super::super::super::input_types::StateFact;
+use super::super::super::input_types::TreeRelations;
+use super::super::super::instrumentation::Counter;
+use super::super::super::instrumentation::Counters;
+use super::super::super::tree::StyleNodeID;
+
+use super::super::super::element_host_facts::HostFactSet;
+use super::super::super::element_host_facts::HostFactSets;
+use super::ArrivalFacts;
+use super::Catalogs;
+use super::ElementFacts;
+use super::Links;
+use super::ROWS_PER_CHUNK;
+use super::Row;
+use super::ShadowColumn;
+use super::ShadowLinks;
+use super::ShadowSnapshot;
+use super::SharedList;
+use super::WrittenRows;
+use super::fact_lists::FactLists;
+use super::fact_lists::RecentFactLists;
+use super::fact_lists::{EditedList, FactListsEdit};
+use super::list_bloom_of;
+use super::relations_of;
+use crate::cow_column::ColumnSnapshot;
+use crate::cow_column::CowColumn;
+use crate::css::retained_fly_string::RetainedUtf16FlyString;
+use smallvec::SmallVec;
+use std::sync::Arc;
+
+/// The counters a host's writes count, which a publication carries to the render owner's.
+const WRITE_COUNTERS: [Counter; 8] = [
+ Counter::RawMutationRecords,
+ Counter::TreeDeltas,
+ Counter::LocalFeatureDeltas,
+ Counter::StateDeltas,
+ Counter::ArrivingNodeFactsFolded,
+ Counter::TreeDepartureDeltas,
+ Counter::SlotAssignedNodeListsPublished,
+ Counter::LanguageTextsPublished,
+];
+
+/// The rows of a document's elements as its host writes them.
+#[derive(Clone, Default)]
+pub(in crate::css::style) struct ProjectionWriter {
+ rows: CowColumn<Row, ROWS_PER_CHUNK>,
+ /// The elements' shadow relations, made only as far as the last element that held any.
+ shadows: ShadowColumn,
+ /// The rows as the host last published them.
+ published: ColumnSnapshot<Row, ROWS_PER_CHUNK>,
+ /// One past the greatest element slot written.
+ slot_count: usize,
+ catalogs: Catalogs,
+ /// The distinct sets of host facts the rows name.
+ host_fact_sets: Arc<HostFactSets>,
+ recent_lists: RecentFactLists,
+ /// A slotted text node's slot. Text nodes have no rows, and a slotted one is rare.
+ text_assigned_slots: Arc<HashMap<StyleNodeID, StyleNodeID>>,
+ /// The elements whose rows were written since the last publication.
+ written: WrittenRows,
+ /// Of those, the elements whose links were written.
+ links_written: WrittenRows,
+ /// Of those, the elements whose own relations were written, rather than only their first element child.
+ relations_written: WrittenRows,
+ /// Whether the catalogs or the slots of text nodes were written since the last publication, which no row says.
+ catalogs_written: bool,
+ /// Whether the host facts of an element were written since the last publication, which the rows written do not
+ /// list: no transaction takes them.
+ host_facts_written: bool,
+ /// The elements the host took out of the tree since the last publication.
+ departures: Vec<StyleNodeID>,
+ /// What the writes since the last publication counted.
+ pub(in crate::css::style) counters: Counters,
+}
+
+/// What the host published of its rows at a barrier: the rows as written, which share every chunk with the host's
+/// until it writes there again, with the catalogs, and the elements written since the barrier before.
+pub(in crate::css::style) struct ProjectionPublication {
+ pub(super) rows: ColumnSnapshot<Row, ROWS_PER_CHUNK>,
+ pub(super) shadows: ShadowSnapshot,
+ pub(super) slot_count: usize,
+ pub(super) catalogs: Catalogs,
+ pub(super) host_fact_sets: Arc<HostFactSets>,
+ pub(super) text_assigned_slots: Arc<HashMap<StyleNodeID, StyleNodeID>>,
+ pub(super) written: Vec<StyleNodeID>,
+ pub(super) links_written: Vec<StyleNodeID>,
+ pub(super) relations_written: Vec<StyleNodeID>,
+ /// What the writes counted.
+ pub(in crate::css::style) counts: SmallVec<[(Counter, u64); 4]>,
+}
+
+impl ProjectionPublication {
+ /// How many elements' links the publication wrote, each of which may deepen the tree by a level.
+ #[must_use]
+ pub(in crate::css::style) fn link_rows_written(&self) -> usize {
+ self.links_written.len()
+ }
+
+ /// Whether the publication moves elements in the tree, or their shadow relations.
+ #[must_use]
+ pub(in crate::css::style) fn moves_links(&self) -> bool {
+ !self.links_written.is_empty()
+ }
+}
+
+impl ProjectionWriter {
+ /// Counts what the host's rows hold beside the projection: the chunks, shadow relations and
+ /// catalogs it wrote since the barrier, as those it shares with the published projection are
+ /// counted where they are seen first, and the lists of what it wrote. Like the generations a
+ /// transaction in flight holds, how much that is depends on when the report runs.
+ pub(in crate::css::style) fn report_memory(&self, report: &mut crate::css::style::memory_report::MemoryReport) {
+ use crate::heap_size::map_bytes;
+ let sizer = &mut report.sizer;
+ let mut bytes = self.rows.heap_size(sizer, Row::heap_size)
+ + self.shadows.heap_size(sizer, |shadow, sizer| {
+ super::shadow_links_heap_size(shadow.as_ref(), sizer)
+ })
+ + self.published.heap_size(sizer, Row::heap_size);
+ if sizer.arc_shallow(&self.host_fact_sets) != 0 {
+ bytes += crate::heap_size::ARC_HEADER_BYTES + size_of::<HostFactSets>() + self.host_fact_sets.heap_size();
+ }
+ let catalogs = &self.catalogs;
+ bytes += catalogs.name_forms.heap_size(sizer);
+ bytes += catalogs.value_texts.heap_size(sizer);
+ for texts in [&catalogs.substitution_names, &catalogs.language_texts] {
+ bytes += texts.heap_size(sizer);
+ bytes += texts.values().map(|text| size_of_val::<[u16]>(text)).sum::<usize>();
+ }
+ bytes += sizer.arc_shallow(&self.text_assigned_slots) + map_bytes(&self.text_assigned_slots);
+ bytes += [&self.written, &self.links_written, &self.relations_written]
+ .iter()
+ .map(|rows| rows.heap_size())
+ .sum::<usize>();
+ bytes += crate::heap_size::vec_bytes(&self.departures);
+ report.add(
+ crate::css::style::memory_report::MemoryOwner::ProjectionGenerations,
+ bytes,
+ );
+ }
+
+ /// The writes the host makes, with what they mean.
+ pub(in crate::css::style) fn writes(&mut self) -> super::super::super::projection_writes::ProjectionWrites<'_> {
+ super::super::super::projection_writes::ProjectionWrites { projection: self }
+ }
+
+ /// Whether anything was written since the last publication.
+ #[must_use]
+ pub(in crate::css::style) fn has_unpublished_writes(&self) -> bool {
+ !self.written.nodes.is_empty() || self.catalogs_written || self.host_facts_written
+ }
+
+ /// Publish the rows as written: the barrier the render owner takes them at. The elements that left the tree are
+ /// retired and forgotten as their departure is published.
+ pub(in crate::css::style) fn publish(&mut self) -> ProjectionPublication {
+ let mut departed = std::mem::take(&mut self.departures);
+ departed.retain(|&node| {
+ self.row(node)
+ .is_some_and(|row| row.live() && relations_of(row).is_none())
+ });
+ // NB: Nothing routes from a departed element's facts but the generations published before, which keep them.
+ for &node in &departed {
+ self.retire(node);
+ if let Some(mut row) = self.rows.row_mut(node.element_slot()) {
+ row.facts = row.facts.forgotten();
+ }
+ }
+ let rows = self.rows.publish();
+ self.catalogs_written = false;
+ self.host_facts_written = false;
+ let counts = WRITE_COUNTERS
+ .into_iter()
+ .filter_map(|counter| {
+ let count = self.counters.get(counter);
+ self.counters.set(counter, 0);
+ (count != 0).then_some((counter, count))
+ })
+ .collect();
+ let publication = ProjectionPublication {
+ rows: rows.clone(),
+ shadows: self.shadows.publish(),
+ slot_count: self.slot_count,
+ catalogs: self.catalogs.clone(),
+ host_fact_sets: Arc::clone(&self.host_fact_sets),
+ text_assigned_slots: Arc::clone(&self.text_assigned_slots),
+ written: self.written.take(),
+ links_written: self.links_written.take(),
+ relations_written: self.relations_written.take(),
+ counts,
+ };
+ self.published = rows;
+ publication
+ }
+
+ /// How many times the rows were written where an edit changed them, which a test reads to see that an edit that
+ /// changes nothing copies no chunk.
+ #[cfg(test)]
+ pub(super) fn rows_version(&self) -> u64 {
+ self.rows.version()
+ }
+
+ fn row(&self, node: StyleNodeID) -> Option<&Row> {
+ self.rows.get(node.element_slot())
+ }
+
+ fn note_written(&mut self, node: StyleNodeID, slot: usize) {
+ self.written.insert(node, slot);
+ }
+
+ fn note_links_written(&mut self, node: StyleNodeID) {
+ self.links_written.insert(node, node.element_slot());
+ }
+
+ /// The element's facts as written, or none where nothing was written of it.
+ #[must_use]
+ pub(in crate::css::style) fn written_facts(&self, node: StyleNodeID) -> Option<&ElementFacts> {
+ self.row(node).map(|row| &row.facts).filter(|facts| facts.resident())
+ }
+
+ /// How the element stands in the tree as written, or none where it stands in no tree.
+ #[must_use]
+ pub(in crate::css::style) fn written_relations(&self, node: StyleNodeID) -> Option<TreeRelations> {
+ self.row(node).and_then(relations_of)
+ }
+
+ /// Whether the relations of `node` were written since the last publication.
+ #[must_use]
+ pub(in crate::css::style) fn relations_were_written(&self, node: StyleNodeID) -> bool {
+ node.element_index().is_some() && self.relations_written.contains(node.element_slot())
+ }
+
+ /// Whether `node` arrives in the publication to come: it stood in no tree as last published, and stands in one as
+ /// written.
+ #[must_use]
+ pub(in crate::css::style) fn arrival_is_pending(&self, node: StyleNodeID) -> bool {
+ node.element_index().is_some()
+ && self.published.get(node.element_slot()).and_then(relations_of).is_none()
+ && self.written_relations(node).is_some()
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn shadow_root_of(&self, host: StyleNodeID) -> Option<StyleNodeID> {
+ self.shadow(host)?.shadow_root
+ }
+
+ #[must_use]
+ pub(in crate::css::style) fn host_of(&self, shadow_root: StyleNodeID) -> Option<StyleNodeID> {
+ self.shadow(shadow_root)?.host
+ }
+
+ fn assigned_nodes_of(&self, slot: StyleNodeID) -> &[StyleNodeID] {
+ self.shadow(slot).map_or(&[], |shadow| shadow.assigned_nodes.as_slice())
+ }
+
+ /// Edit the row of an element, making room for it first.
+ fn edit<R>(&mut self, node: StyleNodeID, edit: impl FnOnce(&mut Row) -> R) -> R {
+ let slot = node.element_slot();
+ assert!(node.element_index().is_some(), "only an element has a projection row");
+ self.note_written(node, slot);
+ self.rows.grow_to(slot + 1);
+ self.slot_count = self.slot_count.max(slot + 1);
+ let mut row = self.rows.row_mut(slot).expect("the row was just made room for");
+ let answer = edit(&mut row);
+ drop(row);
+ answer
+ }
+
+ fn edit_facts(&mut self, node: StyleNodeID, edit: impl FnOnce(&mut ElementFacts)) {
+ let slot = node.element_slot();
+ assert!(node.element_index().is_some(), "only an element has a projection row");
+ self.note_written(node, slot);
+ self.rows.grow_to(slot + 1);
+ self.slot_count = self.slot_count.max(slot + 1);
+ let mut row = self.rows.row_mut(slot).expect("the row was just made room for");
+ row.facts.set_flag(ElementFacts::RESIDENT, true);
+ edit(&mut row.facts);
+ row.facts.refresh_dispatch_bloom();
+ drop(row);
+ }
+
+ /// Edit the fact lists of an element as its links move, which `edit` says whether it changed, without publishing a
+ /// fact of it: its tree scope and assigned slot live in its lists, but say nothing of the element itself.
+ fn edit_lists_quietly(&mut self, node: StyleNodeID, edit: impl FnOnce(&mut FactListsEdit) -> bool) {
+ let empty = FactLists::default();
+ let mut lists = self
+ .rows
+ .get(node.element_slot())
+ .map_or_else(|| empty.edit(), |row| row.facts.lists.edit());
+ if !edit(&mut lists) {
+ return;
+ }
+ let lists = Self::make_lists(&mut self.recent_lists, &self.catalogs.name_forms, lists);
+ self.edit(node, |row| row.facts.lists = lists);
+ }
+
+ /// Edit the fact lists of an element, which `edit` says whether it changed. Lists made the same
+ /// as ones made recently share their allocation.
+ fn edit_lists(&mut self, node: StyleNodeID, edit: impl FnOnce(&mut FactListsEdit) -> bool) {
+ let empty = FactLists::default();
+ let mut lists = self
+ .rows
+ .get(node.element_slot())
+ .map_or_else(|| empty.edit(), |row| row.facts.lists.edit());
+ if !edit(&mut lists) {
+ self.edit_facts(node, |_| {});
+ return;
+ }
+ let lists = Self::make_lists(&mut self.recent_lists, &self.catalogs.name_forms, lists);
+ self.edit_facts(node, |facts| facts.lists = lists);
+ }
+
+ /// Fact lists holding what `lists` holds, with the Bloom summary of their dispatch keys, shared with any made the
+ /// same.
+ fn make_lists(
+ recent_lists: &mut RecentFactLists,
+ name_forms: &super::Catalog<AttributeNameForms>,
+ mut lists: FactListsEdit,
+ ) -> FactLists {
+ lists.bloom = list_bloom_of(&lists, name_forms);
+ recent_lists.make(&lists, &crate::render_state::process_style().fact_lists)
+ }
+
+ fn shadow(&self, node: StyleNodeID) -> Option<&ShadowLinks> {
+ self.shadows.get(node.element_slot())?.as_deref()
+ }
+
+ fn edit_shadow<R>(&mut self, node: StyleNodeID, edit: impl FnOnce(&mut ShadowLinks) -> R) -> R {
+ // NB: The element's row is written too, so that the publication lists the element.
+ self.edit(node, |_| ());
+ let slot = node.element_slot();
+ let mut shadow = self.shadow(node).cloned().unwrap_or_default();
+ let result = edit(&mut shadow);
+ let shadow = (shadow != ShadowLinks::default()).then(|| Arc::new(shadow));
+ if shadow.is_some() || self.shadows.get(slot).is_some_and(Option::is_some) {
+ self.shadows.grow_to(slot + 1);
+ self.shadows.set(slot, shadow);
+ }
+ result
+ }
+
+ /// Take the element's shadow relations, leaving it none.
+ fn take_shadow(&mut self, node: StyleNodeID) -> Option<Arc<ShadowLinks>> {
+ let slot = node.element_slot();
+ let shadow = self.shadows.get(slot).cloned().flatten()?;
+ self.shadows.set(slot, None);
+ Some(shadow)
+ }
+
+ /// Make the element identity `node` live, with no links yet.
+ pub(in crate::css::style) fn mint(&mut self, node: StyleNodeID) {
+ self.edit(node, |row| {
+ assert!(!row.live(), "minting an element identity that is live");
+ row.links = Links::default();
+ row.facts.set_flag(ElementFacts::LIVE, true);
+ row.facts.set_flag(ElementFacts::CONNECTED, false);
+ // NB: A departed element keeps its host facts until its identity is minted again, which may hand it to a
+ // shadow root or the document, which publish none of their own.
+ row.facts.host_facts = Default::default();
+ });
+ }
+
+ /// Retire the element identity `node`, dropping its links and every shadow relation that names
+ /// it. Its facts stay until [`Self::forget`].
+ pub(in crate::css::style) fn retire(&mut self, node: StyleNodeID) {
+ let slot = self.edit(node, |row| {
+ assert!(row.live(), "retiring an identity that is not live");
+ row.links = Links::default();
+ row.facts.set_flag(ElementFacts::LIVE, false);
+ row.facts.set_flag(ElementFacts::CONNECTED, false);
+ row.facts.lists.assigned_slot()
+ });
+ if slot.is_some() {
+ self.edit_lists_quietly(node, |lists| std::mem::take(&mut lists.assigned_slot).is_some());
+ }
+ let shadow = self.take_shadow(node);
+ if let Some(slot) = slot {
+ self.remove_assigned_node(slot, node);
+ }
+ let Some(shadow) = shadow else {
+ return;
+ };
+ for &assigned in shadow.assigned_nodes.as_slice() {
+ if assigned.text_index().is_some() {
+ if self.text_assigned_slots.get(&assigned) == Some(&node) {
+ Arc::make_mut(&mut self.text_assigned_slots).remove(&assigned);
+ }
+ } else if self.row(assigned).and_then(|row| row.facts.lists.assigned_slot()) == Some(node) {
+ self.edit_lists_quietly(assigned, |lists| std::mem::take(&mut lists.assigned_slot).is_some());
+ }
+ }
+ if let Some(root) = shadow.shadow_root {
+ self.edit_shadow(root, |links| links.host = None);
+ }
+ if let Some(host) = shadow.host {
+ self.edit_shadow(host, |links| links.shadow_root = None);
+ }
+ }
+
+ /// Retire text identities, dropping them from the slot each was assigned to.
+ pub(in crate::css::style) fn retire_texts(&mut self, nodes: impl IntoIterator<Item = StyleNodeID>) {
+ for node in nodes {
+ let Some(slot) = Arc::make_mut(&mut self.text_assigned_slots).remove(&node) else {
+ continue;
+ };
+ self.remove_assigned_node(slot, node);
+ }
+ }
+
+ fn remove_assigned_node(&mut self, slot: StyleNodeID, node: StyleNodeID) {
+ if !self.assigned_nodes_of(slot).contains(&node) {
+ return;
+ }
+ self.edit_shadow(slot, |links| {
+ let remaining: Vec<_> = links
+ .assigned_nodes
+ .as_slice()
+ .iter()
+ .copied()
+ .filter(|&assigned| assigned != node)
+ .collect();
+ links.assigned_nodes = SharedList::new(&remaining);
+ });
+ }
+
+ #[cfg(test)]
+ /// Drop the facts of an element that departed, now that nothing can still route from them.
+ /// They leave what style reads when the transaction is released.
+ pub(in crate::css::style) fn forget(&mut self, node: StyleNodeID) {
+ if self.row(node).is_some_and(|row| row.facts.resident()) {
+ self.edit(node, |row| row.facts = row.facts.forgotten());
+ }
+ }
+
+ /// Give a node a row without publishing a fact of it, as a shadow root, which is featureless,
+ /// still has to be readable.
+ pub(in crate::css::style) fn ensure_facts(&mut self, node: StyleNodeID) {
+ self.edit_facts(node, |_| {});
+ }
+
+ pub(in crate::css::style) fn set_tag(&mut self, node: StyleNodeID, tag: StyleAtomID) {
+ self.edit_facts(node, |facts| facts.tag = tag);
+ }
+
+ /// A folding equal to the name itself carries no information and is dropped.
+ pub(in crate::css::style) fn set_folded_tag(&mut self, node: StyleNodeID, folded: StyleAtomID) {
+ let tag = self.row(node).map_or(StyleAtomID::NONE, |row| row.facts.tag);
+ self.edit_lists(node, |lists| {
+ let folded = if folded == tag { StyleAtomID::NONE } else { folded };
+ std::mem::replace(&mut lists.folded_tag, folded) != folded
+ });
+ }
+
+ #[cfg(test)]
+ pub(in crate::css::style) fn set_namespace(&mut self, node: StyleNodeID, namespace: StyleAtomID) {
+ self.edit_lists(node, |lists| {
+ std::mem::replace(&mut lists.namespace, namespace) != namespace
+ });
+ }
+
+ pub(in crate::css::style) fn set_id(&mut self, node: StyleNodeID, id: StyleAtomID) {
+ self.edit_lists(node, |lists| std::mem::replace(&mut lists.id, id) != id);
+ }
+
+ pub(in crate::css::style) fn set_state(&mut self, node: StyleNodeID, fact: StateFact, value: bool) {
+ self.edit_facts(node, |facts| match value {
+ true => facts.states.insert(fact),
+ false => facts.states.remove(fact),
+ });
+ }
+
+ pub(in crate::css::style) fn set_language(&mut self, node: StyleNodeID, language: StyleAtomID) {
+ self.edit_lists(node, |lists| {
+ std::mem::replace(&mut lists.language, language) != language
+ });
+ }
+
+ pub(in crate::css::style) fn set_directionality(&mut self, node: StyleNodeID, directionality: StyleAtomID) {
+ self.edit_lists(node, |lists| {
+ std::mem::replace(&mut lists.directionality, directionality) != directionality
+ });
+ }
+
+ pub(in crate::css::style) fn set_part_exposure(&mut self, node: StyleNodeID, exposure: StyleAtomID) {
+ self.edit_lists(node, |lists| {
+ std::mem::replace(&mut lists.part_exposure, exposure) != exposure
+ });
+ }
+
+ /// The host facts of the element as written.
+ #[must_use]
+ pub(in crate::css::style) fn written_host_facts(&self, node: StyleNodeID) -> HostFactSet {
+ let id = self.row(node).map(|row| row.facts.host_facts).unwrap_or_default();
+ self.host_fact_sets.get(id)
+ }
+
+ /// Change the host facts of the element with `edit`, without noting its row written for a transaction: the host
+ /// facts are none of its selectors' facts. Answers the facts as they were.
+ pub(in crate::css::style) fn edit_host_facts(
+ &mut self,
+ node: StyleNodeID,
+ edit: impl FnOnce(&mut HostFactSet),
+ ) -> HostFactSet {
+ assert!(node.element_index().is_some(), "only an element has host facts");
+ let previous = self.written_host_facts(node);
+ let mut set = previous;
+ edit(&mut set);
+ if set == previous {
+ return previous;
+ }
+ let id = match self.host_fact_sets.id_of(&set) {
+ Some(id) => id,
+ None => Arc::make_mut(&mut self.host_fact_sets).intern(set),
+ };
+ let slot = node.element_slot();
+ self.rows.grow_to(slot + 1);
+ self.slot_count = self.slot_count.max(slot + 1);
+ self.rows
+ .row_mut(slot)
+ .expect("the row was just made room for")
+ .facts
+ .host_facts = id;
+ self.host_facts_written = true;
+ previous
+ }
+
+ pub(in crate::css::style) fn set_heading_level(&mut self, node: StyleNodeID, level: u8) {
+ self.edit_facts(node, |facts| facts.heading_level = level);
+ }
+
+ pub(in crate::css::style) fn set_has_text_content(&mut self, node: StyleNodeID, has_text_content: bool) {
+ self.edit_facts(node, |facts| {
+ facts.set_flag(ElementFacts::HAS_TEXT_CONTENT, has_text_content);
+ });
+ }
+
+ pub(in crate::css::style) fn set_class(&mut self, node: StyleNodeID, class: StyleAtomID, present: bool) {
+ self.edit_lists(node, |lists| {
+ match (present, lists.classes.binary_search(&class)) {
+ (true, Err(index)) => lists.classes.to_mut().insert(index, class),
+ (false, Ok(index)) => {
+ lists.classes.to_mut().remove(index);
+ }
+ _ => return false,
+ }
+ true
+ });
+ }
+
+ pub(in crate::css::style) fn set_attribute(
+ &mut self,
+ node: StyleNodeID,
+ name: StyleAtomID,
+ value: StyleAtomID,
+ present: bool,
+ ) {
+ self.edit_lists(node, |lists| {
+ let attributes = &mut lists.attributes;
+ match (
+ present,
+ attributes.binary_search_by_key(&name, |attribute| attribute.name),
+ ) {
+ (true, Ok(index)) if attributes[index].value == value => return false,
+ (true, Ok(index)) => attributes.to_mut()[index].value = value,
+ (true, Err(index)) => attributes.to_mut().insert(index, AttributeFact { name, value }),
+ (false, Ok(index)) => {
+ attributes.to_mut().remove(index);
+ }
+ (false, Err(_)) => return false,
+ }
+ true
+ });
+ }
+
+ /// Write every fact an element arrives with in one edit of its row: the facts it names are
+ /// set, its classes and attributes join any its row holds, and its states join those set.
+ pub(in crate::css::style) fn write_arrival_facts(&mut self, node: StyleNodeID, arrival: &ArrivalFacts<'_>) {
+ let empty = FactLists::default();
+ let mut lists = self
+ .rows
+ .get(node.element_slot())
+ .map_or_else(|| empty.edit(), |row| row.facts.lists.edit());
+ for &class in arrival.classes {
+ if let Err(index) = lists.classes.binary_search(&class) {
+ lists.classes.to_mut().insert(index, class);
+ }
+ }
+ for &attribute in arrival.attributes {
+ match lists
+ .attributes
+ .binary_search_by_key(&attribute.name, |written| written.name)
+ {
+ Ok(index) => lists.attributes.to_mut()[index].value = attribute.value,
+ Err(index) => lists.attributes.to_mut().insert(index, attribute),
+ }
+ }
+ lists.custom_states = EditedList::Held(arrival.custom_states);
+ lists.namespace = arrival.namespace;
+ if !arrival.id.is_none() {
+ lists.id = arrival.id;
+ }
+ if !arrival.language.is_none() {
+ lists.language = arrival.language;
+ }
+ if !arrival.directionality.is_none() {
+ lists.directionality = arrival.directionality;
+ }
+ lists.folded_tag = match arrival.folded_tag == arrival.tag {
+ true => StyleAtomID::NONE,
+ false => arrival.folded_tag,
+ };
+ let lists = Self::make_lists(&mut self.recent_lists, &self.catalogs.name_forms, lists);
+ self.edit_facts(node, |facts| {
+ facts.tag = arrival.tag;
+ facts.set_flag(ElementFacts::IS_SLOT, arrival.is_slot);
+ facts.set_flag(ElementFacts::HAS_TEXT_CONTENT, arrival.has_text_content);
+ facts.states.0 |= arrival.states.0;
+ if arrival.heading_level != 0 {
+ facts.heading_level = arrival.heading_level;
+ }
+ facts.lists = lists;
+ });
+ }
+
+ pub(in crate::css::style) fn set_parts(&mut self, node: StyleNodeID, parts: &[StyleAtomID]) {
+ self.edit_lists(node, |lists| {
+ if &*lists.parts == parts {
+ return false;
+ }
+ lists.parts = EditedList::Changed(SmallVec::from_slice(parts));
+ true
+ });
+ }
+
+ pub(in crate::css::style) fn set_custom_states(&mut self, node: StyleNodeID, states: &[StyleAtomID]) {
+ self.edit_lists(node, |lists| {
+ if &*lists.custom_states == states {
+ return false;
+ }
+ lists.custom_states = EditedList::Changed(SmallVec::from_slice(states));
+ true
+ });
+ }
+
+ /// Record the other names an attribute name answers to, where the two atoms are minted.
+ pub(in crate::css::style) fn note_attribute_name_forms(&mut self, name: StyleAtomID, forms: AttributeNameForms) {
+ if self.catalogs.name_forms.get(&name) != Some(&forms) {
+ self.catalogs.name_forms.insert(name, forms);
+ self.catalogs_written = true;
+ }
+ }
+
+ /// Record the local name an `attr()` reads the attribute `name` by, which is in no namespace.
+ pub(in crate::css::style) fn note_attribute_substitution_name(&mut self, name: StyleAtomID, local_name: &[u16]) {
+ if self.catalogs.substitution_names.get(&name).map(AsRef::as_ref) != Some(local_name) {
+ self.catalogs.substitution_names.insert(name, local_name.into());
+ self.catalogs_written = true;
+ }
+ }
+
+ /// Record what one attribute-value atom spells. The first spelling stands for as long as the
+ /// atom does.
+ pub(in crate::css::style) fn set_attribute_value_text(&mut self, value: StyleAtomID, text: RetainedUtf16FlyString) {
+ if !value.is_none() && !self.catalogs.value_texts.contains_key(&value) {
+ self.catalogs.value_texts.insert(value, text);
+ self.catalogs_written = true;
+ }
+ }
+
+ /// Record what one language atom spells. The first spelling stands for as long as the atom
+ /// does.
+ pub(in crate::css::style) fn set_language_text(&mut self, language: StyleAtomID, text: &[u16]) {
+ if !language.is_none() && !self.catalogs.language_texts.contains_key(&language) {
+ self.catalogs.language_texts.insert(language, text.into());
+ self.catalogs_written = true;
+ }
+ }
+
+ /// Drop everything the catalogs hold of atoms that are reclaimed, before an identity can be
+ /// reused to spell something else.
+ pub(in crate::css::style) fn forget_atoms(&mut self, atoms: &[StyleAtomID]) {
+ self.catalogs.name_forms.forget(atoms);
+ self.catalogs.substitution_names.forget(atoms);
+ self.catalogs.value_texts.forget(atoms);
+ self.catalogs.language_texts.forget(atoms);
+ }
+
+ /// Edit the relations of an element, which are all its links but its first element child.
+ fn edit_links(&mut self, node: StyleNodeID, edit: impl FnOnce(&mut Row)) {
+ self.relations_written.insert(node, node.element_slot());
+ self.edit_any_links(node, edit);
+ }
+
+ fn edit_any_links(&mut self, node: StyleNodeID, edit: impl FnOnce(&mut Row)) {
+ self.note_links_written(node);
+ self.edit(node, |row| {
+ assert!(row.live(), "linking an identity that is not live");
+ edit(row);
+ });
+ }
+
+ #[cfg(test)]
+ pub(in crate::css::style) fn set_parent(&mut self, node: StyleNodeID, parent: Option<StyleNodeID>) {
+ self.edit_links(node, |row| row.links.parent = parent);
+ }
+
+ pub(in crate::css::style) fn set_first_element_child(&mut self, node: StyleNodeID, child: Option<StyleNodeID>) {
+ self.edit_any_links(node, |row| row.links.first_element_child = child);
+ }
+
+ #[cfg(test)]
+ pub(in crate::css::style) fn set_previous_element_sibling(
+ &mut self,
+ node: StyleNodeID,
+ sibling: Option<StyleNodeID>,
+ ) {
+ self.edit_links(node, |row| row.links.previous_element_sibling = sibling);
+ }
+
+ #[cfg(test)]
+ pub(in crate::css::style) fn set_next_element_sibling(&mut self, node: StyleNodeID, sibling: Option<StyleNodeID>) {
+ self.edit_links(node, |row| row.links.next_element_sibling = sibling);
+ }
+
+ #[cfg(test)]
+ pub(in crate::css::style) fn set_connected(&mut self, node: StyleNodeID, connected: bool) {
+ self.edit_links(node, |row| row.facts.set_flag(ElementFacts::CONNECTED, connected));
+ }
+
+ #[cfg(test)]
+ /// Assign an element to `slot`, or to no slot.
+ pub(in crate::css::style) fn set_assigned_slot(&mut self, node: StyleNodeID, slot: Option<StyleNodeID>) {
+ self.note_links_written(node);
+ self.relations_written.insert(node, node.element_slot());
+ self.edit_lists_quietly(node, |lists| std::mem::replace(&mut lists.assigned_slot, slot) != slot);
+ }
+
+ /// Write how an element stands in the tree, or that it stands in none, leaving the links of
+ /// its neighbors to their own writes. An element leaving keeps its tree scope.
+ ///
+ /// The write is noted even where the row holds these relations already: the host moved them,
+ /// and an element it took out of a tree has to be settled as departed.
+ pub(in crate::css::style) fn write_relations(&mut self, node: StyleNodeID, relations: Option<TreeRelations>) {
+ let mut departed = false;
+ self.edit_links(node, |row| {
+ let links = &mut row.links;
+ match relations {
+ Some(relations) => {
+ links.parent = relations.parent;
+ links.previous_element_sibling = relations.previous_element_sibling;
+ links.next_element_sibling = relations.next_element_sibling;
+ }
+ None => {
+ departed = true;
+ links.parent = None;
+ links.previous_element_sibling = None;
+ links.next_element_sibling = None;
+ }
+ }
+ row.facts.set_flag(ElementFacts::CONNECTED, relations.is_some());
+ });
+ // NB: An element leaving keeps its tree scope.
+ let (tree_scope, assigned_slot) = match relations {
+ Some(relations) => (Some(relations.tree_scope), relations.assigned_slot),
+ None => (None, None),
+ };
+ self.edit_lists_quietly(node, |lists| {
+ let scope_moved = tree_scope.is_some_and(|scope| std::mem::replace(&mut lists.tree_scope, scope) != scope);
+ let slot_moved = std::mem::replace(&mut lists.assigned_slot, assigned_slot) != assigned_slot;
+ scope_moved || slot_moved
+ });
+ if departed {
+ self.departures.push(node);
+ }
+ }
+
+ /// Record that `host` hosts `shadow_root`, unpairing whichever root or host either had before.
+ pub(in crate::css::style) fn set_shadow_root(&mut self, host: StyleNodeID, shadow_root: StyleNodeID) {
+ let previous_root = self.edit_shadow(host, |links| links.shadow_root.replace(shadow_root));
+ if let Some(previous_root) = previous_root
+ && previous_root != shadow_root
+ && self.host_of(previous_root) == Some(host)
+ {
+ self.edit_shadow(previous_root, |links| links.host = None);
+ }
+ let previous_host = self.edit_shadow(shadow_root, |links| links.host.replace(host));
+ if let Some(previous_host) = previous_host
+ && previous_host != host
+ && self.shadow_root_of(previous_host) == Some(shadow_root)
+ {
+ self.edit_shadow(previous_host, |links| links.shadow_root = None);
+ }
+ }
+
+ /// Replace the ordered list of nodes `slot` has assigned to it. An element's own slot arrives
+ /// with its links; a text node has none, so this is where its slot comes from.
+ pub(in crate::css::style) fn set_assigned_nodes(&mut self, slot: StyleNodeID, nodes: &[StyleNodeID]) {
+ if nodes == self.assigned_nodes_of(slot) && nodes.is_empty() {
+ return;
+ }
+ let previous: Vec<_> = self.assigned_nodes_of(slot).to_vec();
+ let text_slots = Arc::make_mut(&mut self.text_assigned_slots);
+ // A tree-wide assignment can have moved a departing text node to another slot already,
+ // and this slot must not take that newer assignment away again.
+ for node in &previous {
+ if text_slots.get(node) == Some(&slot) {
+ text_slots.remove(node);
+ }
+ }
+ for &node in nodes {
+ if node.text_index().is_some() {
+ text_slots.insert(node, slot);
+ }
+ }
+ self.edit_shadow(slot, |links| links.assigned_nodes = SharedList::new(nodes));
+ }
+
+ pub(in crate::css::style) fn set_part_hosts(&mut self, node: StyleNodeID, pairs: &[(StyleAtomID, StyleNodeID)]) {
+ self.edit_shadow(node, |links| links.part_hosts = SharedList::new(pairs));
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/pointer_key.rs b/Libraries/LibWeb/Rust/src/css/style/pointer_key.rs
new file mode 100644
index 00000000000..1a9fcac7afa
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/pointer_key.rs
@@ -0,0 +1,102 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! Keys that find a counted value by its address and hold it, so that for as long as the key stands no other value can
+//! take the address. A key can only be made from a counted reference, so one holding a bare address cannot be written:
+//! `Meta/Linters/check_rust_address_keys.py` rejects the casts that would make one.
+
+use crate::css::style_value::RetainedStyleValueData;
+use std::borrow::Borrow;
+use std::hash::{Hash, Hasher};
+use std::sync::Arc;
+
+/// A counted reference, whose address names what it counts for as long as it is held.
+pub(crate) trait Counted: Clone {
+ fn address(&self) -> usize;
+}
+
+impl<T> Counted for Arc<T> {
+ fn address(&self) -> usize {
+ Arc::as_ptr(self).addr()
+ }
+}
+
+impl Counted for RetainedStyleValueData {
+ fn address(&self) -> usize {
+ self.pointer().addr()
+ }
+}
+
+/// What a map keyed by [`PointerKey`] is looked up by, which takes no count, so that a hit costs what one by the bare
+/// address would. It is made only from a counted reference, and a key is the only way to keep one in a map.
+#[derive(Clone, Copy, Eq, Hash, PartialEq)]
+pub(crate) struct PointerLookup<E = ()> {
+ address: usize,
+ extra: E,
+}
+
+impl<E> PointerLookup<E> {
+ pub(crate) fn new(value: &impl Counted, extra: E) -> Self {
+ Self {
+ address: value.address(),
+ extra,
+ }
+ }
+}
+
+/// A map key naming `T` by its address, with `E`, whatever else the key says. It holds a count of `T`.
+#[derive(Clone)]
+pub(crate) struct PointerKey<T: Counted, E = ()> {
+ lookup: PointerLookup<E>,
+ _held: T,
+}
+
+impl<T: Counted, E> PointerKey<T, E> {
+ pub(crate) fn new(value: &T, extra: E) -> Self {
+ Self {
+ lookup: PointerLookup::new(value, extra),
+ _held: value.clone(),
+ }
+ }
+}
+
+impl<T: Counted, E: Hash> Hash for PointerKey<T, E> {
+ fn hash<H: Hasher>(&self, state: &mut H) {
+ self.lookup.hash(state);
+ }
+}
+
+impl<T: Counted, E: Eq> PartialEq for PointerKey<T, E> {
+ fn eq(&self, other: &Self) -> bool {
+ self.lookup == other.lookup
+ }
+}
+
+impl<T: Counted, E: Eq> Eq for PointerKey<T, E> {}
+
+impl<T: Counted, E> Borrow<PointerLookup<E>> for PointerKey<T, E> {
+ fn borrow(&self) -> &PointerLookup<E> {
+ &self.lookup
+ }
+}
+
+#[cfg(test)]
+mod tests {
+ use super::*;
+
+ #[test]
+ fn a_key_keeps_its_value_alive_and_a_lookup_finds_it_by_identity() {
+ let mut map = crate::fast_hash::FastMap::default();
+ let value = Arc::new(1);
+ let equal = Arc::new(1);
+ map.insert(PointerKey::new(&value, 2_u8), "value");
+ assert_eq!(Arc::strong_count(&value), 2);
+ assert_eq!(map.get(&PointerLookup::new(&value, 2_u8)), Some(&"value"));
+ assert_eq!(map.get(&PointerLookup::new(&value, 3_u8)), None);
+ assert_eq!(map.get(&PointerLookup::new(&equal, 2_u8)), None);
+ assert_eq!(Arc::strong_count(&value), 2);
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/process_style.rs b/Libraries/LibWeb/Rust/src/css/style/process_style.rs
new file mode 100644
index 00000000000..40635193b5f
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/process_style.rs
@@ -0,0 +1,292 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! What every style engine of the process shares: the style atoms and the data built from the
+//! user agent's sheets, which every document records alike.
+
+use super::atoms::ProcessAtoms;
+use super::kept_past_release::KeptPastRelease;
+use super::pipeline::rule_store::{RuleDeclarations, RuleID, UserAgentRules};
+use super::*;
+use crate::css::declaration_block::SharedDeclarationBlock;
+
+/// The style data of the process, which the render owner holds and hands each style engine it
+/// makes.
+pub(crate) struct ProcessStyle {
+ /// The atoms every engine and document host of the process interns names in.
+ pub(super) atoms: Arc<ProcessAtoms>,
+ /// The serial the next selector arena of the process takes.
+ selector_arena_serials: std::sync::atomic::AtomicU64,
+ /// The sheets the process parsed, which a page of the same site finds as it parses them again.
+ parsed_sheets: Mutex<KeptPastRelease<crate::css::parser::syntax_parser::ParsedStyleSheet>>,
+ /// The newest table of the user agent's rules, which the process publishes once for each user
+ /// agent sheet a document first attaches.
+ user_agent_rules: Mutex<Arc<UserAgentRules>>,
+ /// The user agent rule indexes and sheet segments of the process, which engines whose atoms are
+ /// the process's share.
+ pub(super) rule_indexes: pipeline::ProcessRuleIndexes,
+ /// The fact lists of every document's projection rows, interned by content.
+ pub(super) fact_lists: Mutex<pipeline::projection::FactListsTable>,
+ /// The initial groups the documents of the process share, by the device pixel ratio lengths
+ /// snap by, which every initial length computes against.
+ initial_groups: Mutex<HashMap<u64, Vec<std::sync::Weak<SharedInitialGroups>>>>,
+ /// The groups of default values every computation starting from nothing starts from.
+ pub(super) default_groups: crate::css::computed_values::DefaultGroups,
+ /// Whether what is read of an element's values is checked against what its groups build from
+ /// them, which debug builds always do and LIBWEB_VERIFY_STYLE_CHUNKS asks release builds to.
+ pub(super) verifies_reads: bool,
+}
+
+/// The initial groups the documents of the process share: each group of a document's initial
+/// style but its font group, which holds the fonts of its document's font computer and is the
+/// default one here.
+pub(super) struct SharedInitialGroups(crate::css::computed_values::StyleGroups);
+
+impl SharedInitialGroups {
+ pub(super) fn groups(&self) -> &crate::css::computed_values::StyleGroups {
+ &self.0
+ }
+
+ /// Whether each group of `groups` but the font group holds what this one does.
+ fn hold_the_same_as(&self, groups: &crate::css::computed_values::StyleGroups) -> bool {
+ use crate::css::computed_values::StyleGroupIndex;
+ use crate::css::table_group_builder::group_index;
+ StyleGroupIndex::all()
+ .filter(|index| index.usize() != group_index::FONT)
+ .all(|index| {
+ // SAFETY: Both hold a reference to each of their groups.
+ unsafe {
+ crate::css::computed_values::groups_hold_the_same(
+ index.usize(),
+ self.0[index.usize()].as_ptr(),
+ groups[index.usize()].as_ptr(),
+ )
+ }
+ })
+ }
+}
+
+impl Default for ProcessStyle {
+ fn default() -> Self {
+ Self::with_atoms(Arc::<ProcessAtoms>::default())
+ }
+}
+
+impl ProcessStyle {
+ /// Style data of a process whose atoms are `atoms`.
+ pub(super) fn with_atoms(atoms: Arc<ProcessAtoms>) -> Self {
+ Self {
+ atoms,
+ selector_arena_serials: std::sync::atomic::AtomicU64::new(1),
+ parsed_sheets: Default::default(),
+ user_agent_rules: Default::default(),
+ rule_indexes: Default::default(),
+ fact_lists: Default::default(),
+ initial_groups: Default::default(),
+ default_groups: Default::default(),
+ verifies_reads: cfg!(debug_assertions) || std::env::var_os("LIBWEB_VERIFY_STYLE_CHUNKS").is_some(),
+ }
+ }
+}
+
+impl ProcessStyle {
+ /// The initial groups the documents of the process share that hold what `groups`, a
+ /// document's initial groups computed under the device pixel ratio
+ /// `device_pixels_per_css_pixel`, hold besides its font group: the ones another document
+ /// computed, or these.
+ pub(super) fn share_initial_groups(
+ &self,
+ device_pixels_per_css_pixel: f64,
+ groups: &crate::css::computed_values::StyleGroups,
+ ) -> Arc<SharedInitialGroups> {
+ use crate::css::computed_values::StyleGroupIndex;
+ use crate::css::table_group_builder::group_index;
+ let mut initial_groups = self
+ .initial_groups
+ .lock()
+ .expect("the initial groups lock is not poisoned");
+ let shared = initial_groups.entry(device_pixels_per_css_pixel.to_bits()).or_default();
+ shared.retain(|entry| entry.strong_count() != 0);
+ if let Some(shared) = shared
+ .iter()
+ .filter_map(std::sync::Weak::upgrade)
+ .find(|shared| shared.hold_the_same_as(groups))
+ {
+ return shared;
+ }
+ // NB: The font group is the default one, so that no document's fonts outlive it here.
+ let mut own = groups.clone();
+ own.share_group(self.default_groups.groups(), StyleGroupIndex::new(group_index::FONT));
+ let own = Arc::new(SharedInitialGroups(own));
+ shared.push(Arc::downgrade(&own));
+ own
+ }
+
+ /// Keep `sheet`, a sheet the parse cache just published, which holds about `bytes`.
+ pub(crate) fn keep_parsed_sheet(
+ &self,
+ sheet: &Arc<crate::css::parser::syntax_parser::ParsedStyleSheet>,
+ bytes: usize,
+ ) {
+ let left = self
+ .parsed_sheets
+ .lock()
+ .expect("the parsed sheets lock is not poisoned")
+ .keep(sheet, bytes);
+ drop(left);
+ }
+
+ /// Note that a document asked for the parsed sheet `sheet`.
+ pub(crate) fn note_parsed_sheet_use(&self, sheet: &Arc<crate::css::parser::syntax_parser::ParsedStyleSheet>) {
+ self.parsed_sheets
+ .lock()
+ .expect("the parsed sheets lock is not poisoned")
+ .note_use(sheet);
+ }
+
+ /// Let go of what only the process keeps and nothing asked for lately.
+ pub(crate) fn prune_kept_past_release(&self) {
+ let left = self
+ .parsed_sheets
+ .lock()
+ .expect("the parsed sheets lock is not poisoned")
+ .prune();
+ drop(left);
+ self.rule_indexes.prune_kept_segments();
+ }
+
+ /// Let go of everything only the process keeps, as the process is short of memory.
+ pub(crate) fn release_kept_past_release(&self) {
+ let left = self
+ .parsed_sheets
+ .lock()
+ .expect("the parsed sheets lock is not poisoned")
+ .release_all();
+ drop(left);
+ self.rule_indexes.release_kept_segments();
+ }
+
+ /// The newest table of the user agent's rules, holding every sheet the process published.
+ pub(super) fn user_agent_rules(&self) -> Arc<UserAgentRules> {
+ Arc::clone(
+ &self
+ .user_agent_rules
+ .lock()
+ .expect("the user agent rules lock is not poisoned"),
+ )
+ }
+
+ /// Whether the process published the user agent sheet compiled from the native sheet
+ /// `source_identity`.
+ pub(crate) fn has_user_agent_sheet(&self, source_identity: u64) -> bool {
+ self.user_agent_rules().sheet_of_source(source_identity).is_some()
+ }
+
+ /// Publish a user agent sheet compiled from the native sheet `source_identity`, whose rules
+ /// `write` writes to an engine of its own: rules of the sheet are written once per process
+ /// through what any sheet's are, and nothing edits them after.
+ pub(crate) fn publish_user_agent_sheet(
+ self: &Arc<Self>,
+ source_identity: u64,
+ write: impl FnOnce(&mut StyleEngine, SheetID),
+ ) {
+ let mut newest = self
+ .user_agent_rules
+ .lock()
+ .expect("the user agent rules lock is not poisoned");
+ if newest.sheet_of_source(source_identity).is_some() {
+ return;
+ }
+ let mut engine = StyleEngine::new();
+ engine.share_process_style(Arc::clone(self));
+ *engine.rules = newest.store().clone();
+ let sheet = engine.add_sheet(CascadeOrigin::UserAgent);
+ engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);
+ write(&mut engine, sheet);
+ engine.commit_staged_program();
+ let selectors = engine.selector_summary();
+ // NB: The names the sheet's rules declare stay for as long as the engine's atoms are held.
+ let table = newest.with_sheet(
+ (*engine.rules).clone(),
+ sheet,
+ source_identity,
+ selectors,
+ engine.retained.atoms.clone(),
+ );
+ *newest = Arc::new(table);
+ }
+
+ /// Build the user agent index of the documents deciding with the sheet published from the native
+ /// sheet `source_identity` alone, but for the native rules `failing`, on a thread of its own, where
+ /// no document waits for it: one that needs the index meanwhile waits for the lock it builds under.
+ pub(crate) fn index_user_agent_sheet_ahead(
+ self: &Arc<Self>,
+ source_identity: u64,
+ failing: &[u64],
+ ) -> Option<std::thread::JoinHandle<()>> {
+ let rules = self.user_agent_rules();
+ let variant = pipeline::rule_store::UserAgentVariant::of_published_sheet(&rules, source_identity, failing)?;
+ let process = Arc::clone(self);
+ let thread = std::thread::Builder::new()
+ .name("Style UA index".into())
+ .spawn(move || process.rule_indexes.index_ahead(rules.store(), &variant))
+ .expect("the thread indexing the user agent's rules starts");
+ Some(thread)
+ }
+
+ /// The atoms every engine and document host of the process interns names in.
+ pub(crate) fn atoms(&self) -> &Arc<ProcessAtoms> {
+ &self.atoms
+ }
+
+ /// The serial the next selector arena of the process takes.
+ pub(crate) fn next_selector_arena_serial(&self) -> crate::css::selector_arena::SelectorArenaSerial {
+ crate::css::selector_arena::SelectorArenaSerial::next(&self.selector_arena_serials)
+ }
+}
+
+impl StyleEngine {
+ /// Share the style data of `process` with the other engines of the process. Nothing is indexed
+ /// yet.
+ pub(crate) fn share_process_style(&mut self, process: Arc<ProcessStyle>) {
+ debug_assert!(self.retained.live_style.is_none());
+ self.retained.atoms.share_process_atoms(&process.atoms);
+ self.retained.process_style = process;
+ }
+
+ /// Have `rule` declare `block`, making the block's cascade data where no engine of the
+ /// process published the block before, and naming its custom properties in the engine's
+ /// atoms.
+ pub(super) fn publish_block_declarations(&mut self, rule: RuleID, block: &SharedDeclarationBlock) {
+ let custom_names: Vec<_> = block
+ .custom_properties()
+ .iter()
+ .map(|property| {
+ let name = property.name.to_fly_string();
+ let atom = self.atoms.intern_raw(name.raw());
+ // SAFETY: The fly string is live for the call, and the engine takes a reference of its own.
+ unsafe { self.note_custom_property_name(atom, name.raw()) };
+ atom
+ })
+ .collect();
+ let (declarations, made) = RuleDeclarations::of_block(block.clone(), &custom_names);
+ self.retained.counters.bump(match made {
+ true => Counter::SheetDeclarationsInterned,
+ false => Counter::SheetDeclarationsShared,
+ });
+ self.stage_rule_declarations(rule, declarations);
+ }
+}
+
+impl RetainedState {
+ /// The user agent indexes the engine shares with the others of the process, or none where its
+ /// atoms are its own, which no other engine's selectors name.
+ pub(super) fn process_rule_indexes(&self) -> Option<&pipeline::ProcessRuleIndexes> {
+ self.atoms
+ .is_process_global()
+ .then_some(&self.process_style.rule_indexes)
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/projection_writes.rs b/Libraries/LibWeb/Rust/src/css/style/projection_writes.rs
new file mode 100644
index 00000000000..0195dd99626
--- /dev/null
+++ b/Libraries/LibWeb/Rust/src/css/style/projection_writes.rs
@@ -0,0 +1,489 @@
+/*
+ * Copyright (c) 2026-present, the Ladybird developers.
+ *
+ * SPDX-License-Identifier: BSD-2-Clause
+ */
+
+//! The writes a document's host makes to the projection of its elements, as the DOM changes: an element arriving with
+//! its facts, a fact or a state moving, an element taking its place in the tree or leaving it.
+//!
+//! Every such write is the host's writer's alone, made on the host's thread as the DOM changes, and reaches the render
+//! owner only as the writer publishes its rows at a barrier. What a transaction changed is read back from the published
+//! rows, so a write here records no input beyond its count: the projection is the whole of what the host publishes
+//! about its elements' facts and relations.
+
+use super::bridge::ElementBoxKind;
+use super::index::AttributeFact;
+use super::index::FeatureValue;
+use super::index::LocalFeatureKey;
+use super::index::StateSet;
+use super::index::StyleAtomID;
+use super::input_types::InputKey;
+use super::input_types::StateFact;
+use super::input_types::TreeRelations;
+use super::instrumentation::Counter;
+use super::pipeline::projection::ArrivalFacts;
+use super::pipeline::projection::ProjectionWriter;
+use super::tree::StyleNodeID;
+
+/// The host's writer of a document's projection, with what its writes mean.
+pub(in crate::css::style) struct ProjectionWrites<'a> {
+ pub(in crate::css::style) projection: &'a mut ProjectionWriter,
+}
+
+/// What one element arrives with beside its tree relations, every fact of it its selectors test.
+pub(in crate::css::style) struct ElementArrivalFacts<'a> {
+ pub(in crate::css::style) tag: StyleAtomID,
+ pub(in crate::css::style) folded_tag: StyleAtomID,
+ pub(in crate::css::style) namespace: StyleAtomID,
+ pub(in crate::css::style) id: StyleAtomID,
+ pub(in crate::css::style) language: StyleAtomID,
+ pub(in crate::css::style) directionality: StyleAtomID,
+ pub(in crate::css::style) heading_level: u8,
+ pub(in crate::css::style) backing_pseudo_kind_plus_one: u8,
+ pub(in crate::css::style) is_slot: bool,
+ pub(in crate::css::style) has_text_content: bool,
+ pub(in crate::css::style) states: StateSet,
+ /// What the host publishes of the element beside the facts its selectors test.
+ pub(in crate::css::style) adjustment_facts: u32,
+ pub(in crate::css::style) construction_facts: u32,
+ pub(in crate::css::style) box_kind: ElementBoxKind,
+ /// The element's custom states, then its classes, then its attributes as name and value atom pairs.
+ pub(in crate::css::style) atoms: &'a [u32],
+ pub(in crate::css::style) custom_state_count: usize,
+ pub(in crate::css::style) class_count: usize,
+}
+
+impl ProjectionWrites<'_> {
+ /// Count one input the projection says, as the transaction's routing reads it from the rows.
+ fn count(&self, key: InputKey) {
+ let counters = &self.projection.counters;
+ counters.bump(Counter::RawMutationRecords);
+ if let Some(counter) = key.counter() {
+ counters.bump(counter);
+ }
+ if let InputKey::LocalFeature(node, _) | InputKey::State(node, _) = key
+ && self.projection.arrival_is_pending(node)
+ {
+ // Every fact of an arriving element is said by its arrival.
+ counters.bump(Counter::ArrivingNodeFactsFolded);
+ }
+ }
+
+ // -- Identities ----------------------------------------------------------------------------
+
+ /// Make the element identities of `nodes`, which the host minted, live, with no links yet.
+ pub(in crate::css::style) fn mint(&mut self, nodes: impl IntoIterator<Item = StyleNodeID>) {
+ for node in nodes {
+ if node.element_index().is_some() {
+ self.projection.mint(node);
+ }
+ }
+ }
+
+ // -- Tree ----------------------------------------------------------------------------------
+
+ /// Write a structural change into the projection. The relation tree settles it at the next transaction barrier.
+ pub(in crate::css::style) fn record_tree_delta(
+ &mut self,
+ node: StyleNodeID,
+ old: Option<TreeRelations>,
+ new: Option<TreeRelations>,
+ ) {
+ if old != new {
+ self.stage_tree_delta(node, old, new);
+ }
+ }
+
+ /// Stage one structural delta and the neighbor rows it derives.
+ fn stage_tree_delta(&mut self, node: StyleNodeID, old: Option<TreeRelations>, new: Option<TreeRelations>) {
+ if let Some(old) = old {
+ if let Some(previous) = old.previous_element_sibling {
+ self.stage_connected_tree_row(previous, |relations| {
+ relations.next_element_sibling = old.next_element_sibling;
+ });
+ } else if let Some(parent) = old.parent {
+ self.stage_first_child(parent, old.next_element_sibling);
+ }
+ if let Some(next) = old.next_element_sibling {
+ self.stage_connected_tree_row(next, |relations| {
+ relations.previous_element_sibling = old.previous_element_sibling;
+ });
+ }
+ }
+ if let Some(new) = new {
+ if let Some(previous) = new.previous_element_sibling {
+ self.stage_connected_tree_row(previous, |relations| {
+ relations.next_element_sibling = Some(node);
+ });
+ } else if let Some(parent) = new.parent {
+ self.stage_first_child(parent, Some(node));
+ }
+ if let Some(next) = new.next_element_sibling {
+ self.stage_connected_tree_row(next, |relations| {
+ relations.previous_element_sibling = Some(node);
+ });
+ }
+ }
+ self.stage_tree_row(node, old, new);
+ }
+
+ #[inline]
+ fn stage_tree_row(
+ &mut self,
+ node: StyleNodeID,
+ old_if_unwritten: Option<TreeRelations>,
+ new: Option<TreeRelations>,
+ ) {
+ let old = match self.projection.relations_were_written(node) {
+ true => self.projection.written_relations(node),
+ false => old_if_unwritten,
+ };
+ if old == new {
+ return;
+ }
+ self.count(InputKey::TreeRelations(node));
+ if old.is_some() && new.is_none() {
+ self.projection.counters.bump(Counter::TreeDepartureDeltas);
+ }
+ self.projection.write_relations(node, new);
+ }
+
+ fn stage_connected_tree_row(&mut self, node: StyleNodeID, update: impl FnOnce(&mut TreeRelations)) {
+ let Some(old) = self.projection.written_relations(node) else {
+ debug_assert!(
+ !self.projection.relations_were_written(node),
+ "a pending neighbor must remain connected"
+ );
+ return;
+ };
+ // A subtree can preallocate sibling identities before publishing their insertions. Such
+ // a neighbor has no parent yet; its own insertion will supply its links. Synthesizing a
+ // connected before-row here would hide that arrival from transaction normalization.
+ if old.parent.is_none() {
+ return;
+ }
+ let mut new = old;
+ update(&mut new);
+ self.stage_tree_row(node, Some(old), Some(new));
+ }
+
+ pub(in crate::css::style) fn stage_first_child(&mut self, parent: StyleNodeID, child: Option<StyleNodeID>) {
+ self.projection.set_first_element_child(parent, child);
+ }
+
+ /// Record that `host` hosts `shadow_root`, answering whether the host takes a root it did not have.
+ pub(in crate::css::style) fn set_shadow_root(&mut self, host: StyleNodeID, shadow_root: StyleNodeID) -> bool {
+ let attached = self.projection.shadow_root_of(host) != Some(shadow_root);
+ self.projection.set_shadow_root(host, shadow_root);
+ attached
+ }
+
+ /// Replace the ordered list of nodes a slot has assigned to it, text nodes included.
+ pub(in crate::css::style) fn set_slot_assigned_nodes(&mut self, slot: StyleNodeID, nodes: &[StyleNodeID]) {
+ self.projection.counters.bump(Counter::SlotAssignedNodeListsPublished);
+ self.projection.set_assigned_nodes(slot, nodes);
+ }
+
+ /// Record what a language atom spells, so `:lang()` can compare its ranges against the tag.
+ pub(in crate::css::style) fn set_language_text(&mut self, language: StyleAtomID, text: &[u16]) {
+ self.projection.counters.bump(Counter::LanguageTextsPublished);
+ self.projection.set_language_text(language, text);
+ }
+
+ // -- Facts ---------------------------------------------------------------------------------
+
+ /// Write every fact an element arrives with in one edit of its row.
+ pub(in crate::css::style) fn record_element_arrival(
+ &mut self,
+ node: StyleNodeID,
+ arrival: &ElementArrivalFacts<'_>,
+ ) {
+ let (custom_states, rest) = arrival.atoms.split_at(arrival.custom_state_count);
+ let (classes, attributes) = rest.split_at(arrival.class_count);
+ let custom_states = StyleAtomID::slice_of_raw(custom_states);
+ let classes = StyleAtomID::slice_of_raw(classes);
+ let attributes = AttributeFact::slice_of_raw(attributes.as_chunks::<2>().0);
+ // NB: Each fact the arrival carries counts as a delta folded onto it, as each was once published apiece.
+ let folded = 2
+ + u64::from(!arrival.id.is_none())
+ + u64::from(!arrival.language.is_none())
+ + u64::from(!arrival.directionality.is_none())
+ + u64::from(arrival.heading_level != 0)
+ + u64::from(arrival.folded_tag != arrival.tag)
+ + (custom_states.len() + classes.len() + attributes.len()) as u64
+ + u64::from(arrival.states.0.count_ones());
+ self.projection.counters.add(Counter::ArrivingNodeFactsFolded, folded);
+ self.projection.counters.add(Counter::RawMutationRecords, folded);
+ self.projection.counters.add(Counter::LocalFeatureDeltas, folded);
+ self.projection.write_arrival_facts(
+ node,
+ &ArrivalFacts {
+ tag: arrival.tag,
+ folded_tag: arrival.folded_tag,
+ namespace: arrival.namespace,
+ id: arrival.id,
+ language: arrival.language,
+ directionality: arrival.directionality,
+ heading_level: arrival.heading_level,
+ is_slot: arrival.is_slot,
+ has_text_content: arrival.has_text_content,
+ states: arrival.states,
+ classes,
+ attributes,
+ custom_states,
+ },
+ );
+ self.projection.edit_host_facts(node, |set| {
+ set.adjustment_facts = arrival.adjustment_facts;
+ set.construction_facts = arrival.construction_facts;
+ set.set_box_kind(arrival.box_kind);
+ set.associated_pseudo_kind_plus_one = arrival.backing_pseudo_kind_plus_one;
+ });
+ }
+
+ /// Replace the element facts the style computation's adjustments read, answering the bits that moved.
+ pub(in crate::css::style) fn set_element_adjustment_facts(&mut self, node: StyleNodeID, facts: u32) -> u32 {
+ let previous = self
+ .projection
+ .edit_host_facts(node, |set| set.adjustment_facts = facts);
+ previous.adjustment_facts ^ facts
+ }
+
+ /// Replace the element facts a layout row built for the element records.
+ pub(in crate::css::style) fn set_element_construction_facts(&mut self, node: StyleNodeID, facts: u32) {
+ self.projection
+ .edit_host_facts(node, |set| set.construction_facts = facts);
+ }
+
+ /// Record which principal box the element asks for, answering whether that moved.
+ pub(in crate::css::style) fn set_element_box_kind(&mut self, node: StyleNodeID, box_kind: ElementBoxKind) -> bool {
+ self.projection
+ .edit_host_facts(node, |set| set.set_box_kind(box_kind))
+ .box_kind()
+ != box_kind
+ }
+
+ /// Record one local fact of `node` moving from `old` to `new`, which an arriving element's arrival says.
+ pub(in crate::css::style) fn record_feature(
+ &mut self,
+ node: StyleNodeID,
+ feature: LocalFeatureKey,
+ new: FeatureValue,
+ arriving_node: bool,
+ ) {
+ if arriving_node {
+ self.projection.counters.bump(Counter::ArrivingNodeFactsFolded);
+ self.projection.counters.bump(Counter::RawMutationRecords);
+ self.projection.counters.bump(Counter::LocalFeatureDeltas);
+ } else {
+ self.count(InputKey::LocalFeature(node, feature));
+ }
+ self.apply_feature(node, feature, new);
+ }
+
+ /// Record a state publication against the fact the projection holds, answering whether the state moved.
+ ///
+ /// State invalidators may conservatively republish a related group of pseudo-classes when one
+ /// member changes. The written fact is therefore the old side; assuming every publication is
+ /// a Boolean toggle would invent transitions for the unchanged members of that group. Such a
+ /// member is no input at all.
+ pub(in crate::css::style) fn record_state(
+ &mut self,
+ node: StyleNodeID,
+ fact: StateFact,
+ new_value: bool,
+ arriving_node: bool,
+ ) -> bool {
+ let old_value = self
+ .projection
+ .written_facts(node)
+ .is_some_and(|facts| facts.states().contains(fact));
+ if old_value == new_value && !arriving_node {
+ return false;
+ }
+ if arriving_node {
+ self.projection.counters.bump(Counter::ArrivingNodeFactsFolded);
+ self.projection.counters.bump(Counter::RawMutationRecords);
+ self.projection.counters.bump(Counter::LocalFeatureDeltas);
+ } else {
+ self.count(InputKey::State(node, fact));
+ }
+ self.projection.set_state(node, fact, new_value);
+ true
+ }
+
+ /// Write one local fact of `node` into its row.
+ pub(in crate::css::style) fn apply_feature(
+ &mut self,
+ node: StyleNodeID,
+ feature: LocalFeatureKey,
+ value: FeatureValue,
+ ) {
+ let atom = |value: FeatureValue| match value {
+ FeatureValue::Atom(atom) => atom,
+ _ => StyleAtomID::NONE,
+ };
+ let projection = &mut *self.projection;
+ match feature {
+ LocalFeatureKey::TagName => {
+ if let FeatureValue::Atom(atom) = value {
+ projection.set_tag(node, atom);
+ }
+ }
+ LocalFeatureKey::PartExposure => projection.set_part_exposure(node, atom(value)),
+ LocalFeatureKey::Language => projection.set_language(node, atom(value)),
+ LocalFeatureKey::Directionality => projection.set_directionality(node, atom(value)),
+ LocalFeatureKey::HeadingLevel => {
+ let level = match value {
+ FeatureValue::Number(level) => level as u8,
+ _ => 0,
+ };
+ projection.set_heading_level(node, level);
+ }
+ LocalFeatureKey::FoldedTagName => projection.set_folded_tag(node, atom(value)),
+ // Parts and custom states are published as complete sets after their individual
+ // deltas have been recorded. Arrival is only a routing key.
+ LocalFeatureKey::Part(_) | LocalFeatureKey::CustomState(_) => {}
+ // A text node is not a style node, so nothing in the tree can say it is there.
+ // `Present` on this key means the element is empty.
+ LocalFeatureKey::Emptiness => projection.set_has_text_content(node, !value.holds()),
+ LocalFeatureKey::Id => projection.set_id(node, atom(value)),
+ LocalFeatureKey::Class(class) => projection.set_class(node, class, value.holds()),
+ LocalFeatureKey::Attribute(name) => {
+ // The value's atom rides on the same delta. Presence is what routing reads; the
+ // value is what an exact test compares, and a cold pass has no DOM to ask.
+ projection.set_attribute(node, name, atom(value), value.holds());
+ }
+ }
+ }
+
+ /// Record the shadow parts an element exposes.
+ ///
+ /// A part is a fact about the element like a class is: posted so `::part()` rules can be
+ /// enumerated from it, and recorded so a change to the `part` attribute routes. The plain
+ /// name set is derived here from the name-to-host pairs exact matching needs, so the two views
+ /// cannot disagree.
+ pub(in crate::css::style) fn set_element_parts(&mut self, node: StyleNodeID, pairs: &[(StyleAtomID, StyleNodeID)]) {
+ let mut parts = Vec::new();
+ for &(part, _) in pairs {
+ if !parts.contains(&part) {
+ parts.push(part);
+ }
+ }
+ let written = self
+ .projection
+ .written_facts(node)
+ .map_or(&[][..], |facts| facts.parts());
+ if written != parts {
+ let previous: Vec<StyleAtomID> = written.to_vec();
+ for part in previous.iter().filter(|part| !parts.contains(part)) {
+ self.count(InputKey::LocalFeature(node, LocalFeatureKey::Part(*part)));
+ }
+ for part in parts.iter().filter(|part| !previous.contains(part)) {
+ self.count(InputKey::LocalFeature(node, LocalFeatureKey::Part(*part)));
+ }
+ self.projection.set_parts(node, &parts);
+ }
+ self.projection.set_part_hosts(node, pairs);
+ }
+
+ /// Write one atom-valued local fact of `node`, which says nothing where it holds that value already.
+ fn set_atom_fact(
+ &mut self,
+ node: StyleNodeID,
+ feature: LocalFeatureKey,
+ previous: StyleAtomID,
+ value: StyleAtomID,
+ ) {
+ if previous == value {
+ return;
+ }
+ self.count(InputKey::LocalFeature(node, feature));
+ let value = match value.is_none() {
+ true => FeatureValue::Absent,
+ false => FeatureValue::Atom(value),
+ };
+ self.apply_feature(node, feature, value);
+ }
+
+ /// Report the outermost host a `::part()` rule can address this element from.
+ ///
+ /// What an `exportparts` change moves is which scopes can name an element, not which names it
+ /// carries - the forwarded name is usually the one it already had. So the exposure is the fact,
+ /// and an element whose reach did not move says nothing.
+ pub(in crate::css::style) fn set_element_part_exposure(&mut self, node: StyleNodeID, exposure: StyleAtomID) {
+ let previous = self
+ .projection
+ .written_facts(node)
+ .map_or(StyleAtomID::NONE, |facts| facts.part_exposure());
+ self.set_atom_fact(node, LocalFeatureKey::PartExposure, previous, exposure);
+ }
+
+ /// Record the element-backed pseudo-element kind of its host the element stands for, one plus
+ /// the kind, or zero for none.
+ pub(in crate::css::style) fn set_element_backing_pseudo_kind(
+ &mut self,
+ node: StyleNodeID,
+ pseudo_kind_plus_one: u8,
+ ) {
+ self.projection
+ .edit_host_facts(node, |set| set.associated_pseudo_kind_plus_one = pseudo_kind_plus_one);
+ }
+
+ pub(in crate::css::style) fn set_element_heading_level(&mut self, node: StyleNodeID, level: u8) {
+ let previous = self
+ .projection
+ .written_facts(node)
+ .map_or(0, |facts| facts.heading_level());
+ if previous == level {
+ return;
+ }
+ self.count(InputKey::LocalFeature(node, LocalFeatureKey::HeadingLevel));
+ self.apply_feature(
+ node,
+ LocalFeatureKey::HeadingLevel,
+ FeatureValue::Number(u32::from(level)),
+ );
+ }
+
+ pub(in crate::css::style) fn set_element_language(&mut self, node: StyleNodeID, language: StyleAtomID) {
+ let previous = self
+ .projection
+ .written_facts(node)
+ .map_or(StyleAtomID::NONE, |facts| facts.language());
+ self.set_atom_fact(node, LocalFeatureKey::Language, previous, language);
+ }
+
+ /// Report the element's resolved directionality, which `:dir()` tests.
+ pub(in crate::css::style) fn set_element_directionality(&mut self, node: StyleNodeID, directionality: StyleAtomID) {
+ let previous = self
+ .projection
+ .written_facts(node)
+ .map_or(StyleAtomID::NONE, |facts| facts.directionality());
+ self.set_atom_fact(node, LocalFeatureKey::Directionality, previous, directionality);
+ }
+
+ /// Replace the custom states an element is in.
+ ///
+ /// A custom state is a named fact about one element, exactly like a class, so it is published as
+ /// one: the names that arrived and the names that left are each a local feature moving, and
+ /// `:state()` reaches its subjects through the same postings every other name does.
+ pub(in crate::css::style) fn set_element_custom_states(&mut self, node: StyleNodeID, states: &[StyleAtomID]) {
+ let written = self
+ .projection
+ .written_facts(node)
+ .map_or(&[][..], |facts| facts.custom_states());
+ if written == states {
+ return;
+ }
+ let previous: Vec<StyleAtomID> = written.to_vec();
+ for state in previous.iter().filter(|state| !states.contains(state)) {
+ self.count(InputKey::LocalFeature(node, LocalFeatureKey::CustomState(*state)));
+ }
+ for state in states.iter().filter(|state| !previous.contains(state)) {
+ self.count(InputKey::LocalFeature(node, LocalFeatureKey::CustomState(*state)));
+ }
+ self.projection.set_custom_states(node, states);
+ }
+}
diff --git a/Libraries/LibWeb/Rust/src/css/style/routing.rs b/Libraries/LibWeb/Rust/src/css/style/routing.rs
deleted file mode 100644
index 47f361e910a..00000000000
--- a/Libraries/LibWeb/Rust/src/css/style/routing.rs
+++ /dev/null
@@ -1,5138 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-use super::column::advance_epoch;
-use super::prefix::PrefixTransitionContext;
-use super::sorted_merge::{SortedMergeEntry, merge_sorted_by};
-use super::*;
-
-/// The elements that left in one transaction, and which dispatch keys any of them carried as it
-/// left. Relational sequence routing asks the same few keys once per touched parent. Without a
-/// complete list of the elements that left, any of them may have been a witness.
-pub(super) struct DepartedWitnessKeys<'a> {
- departed: Option<&'a [StyleNodeID]>,
- keys: Vec<(DispatchKey, bool)>,
-}
-
-impl RetainedState {
- /// Whether the locally evaluable compound containing an input changed truth on that element.
- fn route_origin_truth_flipped(
- &mut self,
- program: SelectorProgramID,
- origin: selector::SelectorNodeID,
- node: StyleNodeID,
- ) -> Option<bool> {
- let view = self.transaction_fact_view.as_ref()?;
- let compiled = self.programs.get(program);
- if !compiled.selector_node_reads_only_local_facts(origin) {
- return None;
- }
- let resident_facts = self.facts.primary();
- let old = MatchEvaluator::new(&self.tree, resident_facts)
- .with_transaction_fact_view(view, TransactionFactSide::Before)
- .matches_node(compiled, origin, node, &self.counters)
- .ok()?;
- let new = MatchEvaluator::new(&self.tree, resident_facts)
- .with_transaction_fact_view(view, TransactionFactSide::After)
- .matches_node(compiled, origin, node, &self.counters)
- .ok()?;
- Some(old != new)
- }
-
- /// Whether one attribute input changed the route's origin test. Presence and case-sensitive
- /// interned equality are answered directly; text operators use the selector evaluator.
- fn route_attribute_origin_truth_flipped(
- &mut self,
- input: &NormalizedInput,
- program: SelectorProgramID,
- origin: selector::SelectorNodeID,
- node: StyleNodeID,
- ) -> Option<bool> {
- let InputKey::LocalFeature(_, LocalFeatureKey::Attribute(_)) = input.key else {
- return None;
- };
- let compiled = self.programs.get(program);
- if let SelectorOp::Feature(selector::FeatureTest::Attribute(test)) = compiled.node(origin) {
- let value = |input: InputValue| match input {
- InputValue::Feature(value) => Some(value),
- _ => None,
- };
- let old = value(input.old)?;
- let new = value(input.new)?;
- if test.operator == selector::AttributeOperator::Presence {
- return Some(old.holds() != new.holds());
- }
- if test.operator == selector::AttributeOperator::Exact
- && test.case == selector::AttributeCase::Sensitive
- && !test.value_atom.is_none()
- {
- let matches = |value: FeatureValue| match value {
- FeatureValue::Absent => Some(false),
- FeatureValue::Atom(atom) => Some(atom == test.value_atom),
- _ => None,
- };
- return Some(matches(old)? != matches(new)?);
- }
- }
- self.route_origin_truth_flipped(program, origin, node)
- }
-
- /// Route one non-program input to the region its transpose routes reach.
- ///
- /// The region a path folds to is often much wider than the subjects that can actually change:
- /// `.guard:hover .target` reaches a whole subtree, but only the `.target` elements inside it
- /// have a rule whose truth depends on that hover. So a region wider than a single node is
- /// narrowed to the candidates of the subject's own rightmost feature that lie inside it, which
- /// is a posting lookup plus a membership proof per candidate rather than a walk of the region.
- ///
- /// Narrowing is attempted only while the candidate source is small relative to the region. Past
- /// that, streaming the region is the cheaper plan and the region stands.
- #[allow(clippy::too_many_arguments)]
- pub(super) fn route_input(
- &mut self,
- input: &NormalizedInput,
- changed_sheets: &[SheetID],
- changed_programs: &[SelectorProgramID],
- tree_routing: TreeRoutingMode<'_>,
- sibling_entries: &[SiblingEntry],
- sibling_candidates: &mut SiblingCandidateWorkspace,
- pending_sibling_routes: &mut PendingSiblingRoutes,
- pending_routes: &mut PendingRoutes,
- pending_prefix_producers: &mut Vec<PendingPrefixProducer>,
- prefix_producer_admission: Option<&(ScopeProgramID, Arc<RuleDispatch>)>,
- prefix_producer_seen: &mut Vec<u32>,
- sequences: &mut SequenceChanges,
- regions: &mut ImpactRegions,
- ) {
- // A declaration sourced from the element changes what wins on that element and nothing
- // else. There is no selector to transpose: the region is the element itself.
- if let InputKey::ElementDeclaration(node, _) = input.key {
- regions.add(ImpactRegion::Node(node));
- return;
- }
-
- // Other element-owned style inputs do not change matching at all. Publish the retained
- // answer as an exact reaction without asking the selector evaluator to prove it again.
- if let InputKey::ElementStyleInput(node) = input.key {
- regions.add(ImpactRegion::Node(node));
- return;
- }
-
- // An element's part exposure moving is that element becoming addressable from somewhere it
- // was not, or ceasing to be. No selector names the exposure, so there is nothing to
- // transpose: the region is the element whose reach moved.
- if let InputKey::LocalFeature(node, LocalFeatureKey::PartExposure) = input.key {
- self.record_selector_truth_refresh(node, None);
- regions.add(ImpactRegion::Node(node));
- return;
- }
-
- // A tree delta is not a feature moving on a node: it is the node's place in the tree
- // moving, which changes positional truth across a whole child sequence.
- if let InputKey::TreeRelations(node) = input.key {
- self.route_tree_delta(
- node,
- input.old,
- input.new,
- tree_routing,
- sibling_entries,
- sibling_candidates,
- pending_sibling_routes,
- sequences,
- regions,
- );
- return;
- }
-
- let in_flux = Self::feature_in_flux(input);
- let is_arrival = matches!(input.key, InputKey::LocalFeature(_, LocalFeatureKey::ArrivingFacts));
- let keys = match input.key {
- InputKey::LocalFeature(node, LocalFeatureKey::ArrivingFacts) => self.routing_keys_of_arriving_facts(node),
- // A `[*|x]` rule registers under the any-namespace form of the name, which the pure
- // mapping cannot produce: it is a property of the atom rather than of the input. An
- // attribute change has to reach those rules as well as the ones naming its own namespace.
- InputKey::LocalFeature(_, LocalFeatureKey::Attribute(name)) => {
- let mut keys = routing_keys_for_input(input);
- for other in self.facts.attribute_name_keys(name) {
- if other != name {
- keys.push(RoutingKey::AttributeName(other));
- }
- }
- keys
- }
- _ => routing_keys_for_input(input),
- };
- if keys.is_empty() {
- return;
- }
- let routing = Arc::clone(&self.routing);
- let route_liveness = routing.route_liveness(&self.program);
- for key in keys {
- // A maintained relation already accounts for these selectors' complete changes.
- // Prove coverage once per input key before expanding its individual routes.
- if self
- .transaction_fact_view
- .as_ref()
- .is_some_and(|view| view.prefix.is_some())
- && input
- .key
- .style_node()
- .is_some_and(|node| self.tree.tree_scope(node) == TreeScopeID::DOCUMENT)
- && let Some((program, dispatch)) = prefix_producer_admission
- && let Lookup::Known(states) = self.prefix_caches.borrow_mut().states.lookup_mut(*program)
- && let Some(relation) = states.relation.as_mut()
- {
- let covered = relation.handled_routing_keys.entry(key).or_insert_with(|| {
- routing
- .routes_for(key)
- .iter()
- .all(|&route| self.route_is_prefix_convergence_eligible(&routing, dispatch, route))
- });
- if *covered {
- continue;
- }
- }
- // The tree delta already puts an arriving element and its subtree in the plan. Its
- // individual facts only have work left to do as possible witnesses of relational
- // selectors whose anchors live outside that subtree, or on the left side of sibling
- // selectors whose subjects follow it.
- let routes = match is_arrival {
- true => routing.arrival_routes_for(key),
- false => routing.routes_for(key),
- };
- self.counters.add(Counter::RoutedEntryPoints, routes.len() as u64);
-
- let Some(node) = input.key.style_node() else {
- continue;
- };
- for &route in routes {
- let route_is_live = route_liveness.contains(route.index());
- // A rule that decides nothing right now cannot be reached through. Its entry
- // points stay registered, because the rule still holds its position and its sheet
- // can come back.
- let rule = routing.rule_of(route);
- if !route_is_live
- && !self.program.rule_can_decide(rule)
- && !changed_sheets.contains(&self.program.rule_sheet(rule))
- {
- continue;
- }
- let point = routing.route(route);
- let (selector_program, selector_entry) = self.programs.entry_location(point.entry);
- // A rule that was given a new selector list keeps its identity, so the routes
- // of the program it left behind are still registered under it. They describe a
- // selector the rule no longer has, and following them would route a mutation
- // through a selector nobody wrote.
- if !route_is_live
- && self.program.rule_version(rule).selector_program != Some(selector_program)
- && !changed_programs.contains(&selector_program)
- {
- continue;
- }
- let sheet = self.program.rule_sheet(rule);
- if !self.programs.get(selector_program).can_leave_its_scope()
- && !changed_sheets.contains(&sheet)
- && !self
- .program
- .sheet_rules_apply_in_scope(sheet, self.tree.tree_scope(node))
- {
- self.counters.bump(Counter::ScopeConfinedRoutesSkipped);
- continue;
- }
- let path = routing.path_of(route);
- if !is_arrival
- && point.anchor.is_none()
- && !path.is_empty()
- && matches!(input.key, InputKey::LocalFeature(_, LocalFeatureKey::Attribute(_)))
- {
- let truth_flipped = self.route_attribute_origin_truth_flipped(
- input,
- selector_program,
- point.selector_node.expect("attribute route has no selector node"),
- node,
- );
- if truth_flipped == Some(false) {
- self.counters.bump(Counter::OriginTruthRoutesSkipped);
- continue;
- }
- self.counters.bump(Counter::OriginTruthRoutesFired);
- }
- // The element the input happened to must satisfy the rest of the compound the input
- // occurs in, or this route cannot be reached from it at all.
- if !self.node_carries_any(routing.origin_dispatch_of(route), node, in_flux) {
- continue;
- }
- if !self.node_carries_all(routing.origin_required_of(route), node, in_flux) {
- continue;
- }
- let exact_tree_evaluation = if is_arrival && tree_routing.use_exact {
- if tree_routing.has_before_sibling_relations
- && self.entry_can_use_before_sibling_relations(selector_program, selector_entry)
- {
- Some(
- if matches!(path.first(), Some(InverseStep::FollowingSiblings))
- && self.entry_is_monotone_in_the_tree(selector_program, selector_entry)
- {
- ExactTreeEvaluation::MonotonicArrival
- } else {
- ExactTreeEvaluation::BeforeSiblingRelations
- },
- )
- } else if self.entry_is_monotone_in_the_tree(selector_program, selector_entry) {
- Some(ExactTreeEvaluation::Arrival)
- } else {
- None
- }
- } else {
- None
- };
- let site = RoutingSite {
- subject: routing.subject_dispatch_of(route),
- subject_required: routing.subject_required_of(route),
- position: routing.subject_position_of(route),
- path,
- waypoints: routing.waypoints_of(route),
- in_flux,
- exact_entry: Some((rule, point.entry)),
- refresh_rule: Some((rule, point.entry)),
- // One side decides for a monotonic tree change, and only where nothing the
- // change carries can turn the entry the other way. A negation, `:empty` and a
- // positional test each can, and each is answered on both sides as usual.
- exact_tree_evaluation,
- };
- match point.anchor {
- // A relational input resolves its anchors first. Folding the anchor step into
- // the path would compose "the ancestors of the changed node" with whatever the
- // outer selector adds, and ancestors-then-descendants is the document.
- Some(anchor) => self.route_from_anchors(node, selector_program, anchor, &site, regions),
- None => {
- let region = ImpactRegion::follow(node, path, &self.tree);
- let is_sibling_route = exact_tree_evaluation.is_some()
- && matches!(
- path.first(),
- Some(InverseStep::NextSibling | InverseStep::FollowingSiblings)
- )
- && sibling_entries
- .binary_search_by_key(&route, |entry| entry.route)
- .is_ok();
- let routes = if is_sibling_route {
- pending_sibling_routes.regions_for(PendingSiblingRoute {
- route,
- kind: SiblingRouteKind::ExactUnion,
- exact_tree_evaluation,
- })
- } else {
- if let Some((scope_program, prefix_dispatch)) = prefix_producer_admission
- && matches!(input.key, InputKey::LocalFeature(..) | InputKey::State(..))
- && self.route_is_prefix_convergence_eligible(&routing, prefix_dispatch, route)
- && let Some(producer) = prefix_dispatch
- .prefixes()
- .route_producer(point.entry, routing.path_of(route).len())
- && let Lookup::Known(states) = self.prefix_caches.borrow().states.lookup(*scope_program)
- {
- let node_stamp = node.raw();
- assert_ne!(node_stamp, 0, "a node identity used as an epoch stamp must be nonzero");
- if prefix_producer_seen.len() <= producer.index() {
- prefix_producer_seen.resize(producer.index() + 1, 0);
- }
- if prefix_producer_seen[producer.index()] != node_stamp {
- prefix_producer_seen[producer.index()] = node_stamp;
- if states.producer_is_active(prefix_dispatch.prefixes(), node, producer) {
- pending_prefix_producers.push(PendingPrefixProducer { node, producer });
- }
- }
- }
- pending_routes.regions_for(PendingRoute {
- route,
- exact_tree_evaluation,
- })
- };
- self.push_pending_region(routes, region);
- }
- }
- }
- }
- }
-
- /// Route a node's place in the tree changing.
- ///
- /// A node that is still connected brings its whole subtree: those nodes are new to this scope,
- /// or their ancestor context is. Positional truth changes across the whole child sequence the
- /// node joined or left, and emptiness and only-child truth change for its parent. Those matter
- /// only if some attached selector asks positional questions, which the registry answers in one
- /// lookup - so a document with no positional selectors pays nothing for the possibility.
- #[allow(clippy::too_many_arguments)]
- pub(super) fn route_tree_delta(
- &mut self,
- node: StyleNodeID,
- old: InputValue,
- new: InputValue,
- tree_routing: TreeRoutingMode<'_>,
- sibling_entries: &[SiblingEntry],
- sibling_candidates: &mut SiblingCandidateWorkspace,
- pending_sibling_routes: &mut PendingSiblingRoutes,
- sequences: &mut SequenceChanges,
- regions: &mut ImpactRegions,
- ) {
- let relations = |value: InputValue| match value {
- InputValue::TreeRelations(relations) => relations,
- _ => None,
- };
- let old = relations(old);
- let new = relations(new);
-
- // A node whose parent departed in the same transaction departed with it, so nothing that
- // remains was its sibling or in its sequence.
- if new.is_none()
- && let Some(old) = old
- && old.parent.is_some_and(|parent| !self.tree.is_live(parent))
- {
- return;
- }
-
- if new.is_some()
- && (old.is_none()
- || old.and_then(|relations| relations.parent) != new.and_then(|relations| relations.parent))
- {
- regions.add(ImpactRegion::Subtree(node));
- }
-
- // A slottable's assigned slot is its parent in the flat tree, so a slot name change moves it
- // there without moving it in the DOM at all. Nothing about the child sequence it is in has
- // moved, and no feature of its own has changed - what reaches it is the element itself,
- // which is the subject `::slotted()` names and the element whose inheritance parent moved.
- if let (Some(old), Some(new)) = (old, new)
- && old.assigned_slot != new.assigned_slot
- {
- self.record_selector_truth_refresh(node, None);
- regions.add(ImpactRegion::Node(node));
- }
-
- // A node crossing a parent boundary leaves one child sequence and joins another. A node
- // whose place inside one moved leaves and joins the same sequence, changing both seams
- // around it. A one-seam change instead describes a stationary neighbour, and counting it
- // would shift every count the sequence answers.
- let parent_of = |side: Option<TreeRelations>| side.and_then(|relations| relations.parent);
- let preceded_by = |side: Option<TreeRelations>| side.and_then(|relations| relations.previous_element_sibling);
- let followed_by = |side: Option<TreeRelations>| side.and_then(|relations| relations.next_element_sibling);
- let crossed_a_parent = parent_of(old) != parent_of(new);
- let place_moved = !crossed_a_parent
- && parent_of(old).is_some()
- && preceded_by(old) != preceded_by(new)
- && followed_by(old) != followed_by(new);
-
- // A node that stayed put and gained a new neighbour is what an adjacent- or general-sibling
- // selector constrains: `A + B` is a constraint on B, and what changed is B's relation. The
- // node that moved is the other side of the same constraint, and its old place is as much of
- // the change as its new one.
- if let (Some(old), Some(new)) = (old, new) {
- if old.previous_element_sibling != new.previous_element_sibling {
- self.route_sibling_relations_to_constrained_side(
- node,
- old,
- new,
- place_moved || crossed_a_parent,
- tree_routing,
- sibling_entries,
- sibling_candidates,
- pending_sibling_routes,
- );
- }
- if place_moved || crossed_a_parent {
- self.route_departure_to_siblings(
- node,
- old,
- tree_routing,
- sibling_entries,
- sibling_candidates,
- pending_sibling_routes,
- );
- self.route_arrival_to_siblings(
- node,
- tree_routing,
- sibling_entries,
- sibling_candidates,
- pending_sibling_routes,
- );
- }
- }
-
- // A departing subtree takes its facts with it, and routing runs after it has already been
- // detached, so no walk from it finds anything and no feature is left to route from. Its old
- // relations are still on the delta, though, and they say where its anchors were.
- if new.is_none()
- && let Some(relations) = old
- && relations.parent.is_some()
- {
- self.route_departure_to_siblings(
- node,
- relations,
- tree_routing,
- sibling_entries,
- sibling_candidates,
- pending_sibling_routes,
- );
- }
-
- // An element joining, leaving, or moving within a sequence moves which of its members are
- // siblings of which, and a relational query reaching across a seam can gain or lose its
- // witness without any witness having changed. Nothing the moved element's features say
- // covers that, so the seam is recorded here and the anchors around it are asked once per
- // touched parent by the deferred relational sequence pass. A node crossing a parent
- // boundary departs one sequence and arrives in the other even when it stays connected.
- let relational_routes_exist = !self.routing.relational_routes().is_empty();
-
- for side in [old, new] {
- let Some(relations) = side else {
- continue;
- };
- // A removed node cannot be walked from, so its old neighbours anchor the sequence.
- if let Some(parent) = relations.parent {
- if crossed_a_parent || place_moved {
- let change = sequences.get_or_insert_with(parent, || {
- let children: Vec<StyleNodeID> = self.tree.children(parent).collect();
- let (children, _, _) = self
- .match_workspace
- .publish_sibling_sequence(children, MatchEvaluationSide::Current);
-
- SequenceChange::new(children)
- });
- let tag = self.facts.tag_of_node(node);
- let changed_type = (!tag.is_none()).then(|| (tag, self.facts.namespace_of(node)));
- let relocated = old.is_some() && new.is_some();
- let relational = match (relational_routes_exist, relocated, side == new) {
- (false, ..) => None,
- (true, true, true) => Some(if crossed_a_parent {
- SequenceSide::Reparented
- } else {
- SequenceSide::Moved
- }),
- (true, true, false) => Some(if crossed_a_parent {
- SequenceSide::Departed
- } else {
- SequenceSide::Moved
- }),
- (true, false, true) => Some(SequenceSide::Arrived),
- (true, false, false) => Some(SequenceSide::Departed),
- };
- change.record(relations, side == new, relocated, changed_type, node, relational);
- }
- continue;
- }
- let anchor = match side == new {
- true => Some(node),
- false => relations.previous_element_sibling.or(relations.next_element_sibling),
- };
- if let Some(anchor) = anchor {
- regions.add(ImpactRegion::SiblingSequence(anchor));
- }
- }
- }
-
- /// Route what the transaction did to child sequences into the relational queries it moves.
- ///
- /// A subtree leaving takes the witnesses with it, so the anchors cannot be found by walking
- /// from them. What is still true is that any anchor of a query the subtree witnessed is the old
- /// parent or one of its ancestors, and that it carries the anchor compound's own feature -
- /// which is the same filter that keeps an ordinary anchor set small.
- ///
- /// Joining is normally routed from the arriving element's own features, but two things no
- /// feature says. Which elements are siblings of which moved: `#subject:has(+ #s2)` stops
- /// matching when anything at all lands between the two, and that element need not be named by
- /// any selector in the document. And a query whose witness compound distinguishes nothing -
- /// `:has(:not(.test))`, `:has(*)` - has no feature for an arrival to carry, so the arriving
- /// element is asked directly whether it is a witness rather than waiting to be named as one.
- ///
- /// Runs once per touched parent rather than once per changed child. The anchors a sibling-axis
- /// query can reach from k seams in one sequence are the union of k predecessor prefixes, which
- /// is the single prefix of the rightmost seam - so a batch of arrivals pays one walk over the
- /// sequence instead of one per arrival.
- pub(super) fn route_relational_sequence_changes(
- &mut self,
- sequences: &SequenceChanges,
- departed: Option<&[StyleNodeID]>,
- regions: &mut ImpactRegions,
- ) {
- let routing = Arc::clone(&self.routing);
- if routing.relational_routes().is_empty() {
- return;
- }
- if sequences.iter().all(|(_, change)| change.relational_records.is_empty()) {
- return;
- }
- let live = routing.live_relational_routes(&self.program);
-
- for &LiveRelationalRoute { route, program, anchor } in live {
- // An argument that reaches its witness across a sibling relation of its own holds
- // because of an adjacency the query names nothing near. Any element landing in any
- // sequence breaks it while carrying nothing, so the query is asked from its witnesses
- // rather than from anything the change could be recognised as - and since that asks
- // nothing about the seam itself, once per transaction answers every seam.
- if anchor.argument_spans_siblings {
- let site = route_site(&routing, route);
- self.route_from_possible_witnesses(program, anchor, &site, regions);
- }
- }
-
- let mut departed_witnesses = DepartedWitnessKeys {
- departed,
- keys: Vec::new(),
- };
- for (parent, change) in sequences.iter() {
- if change.relational_records.is_empty() {
- continue;
- }
- self.route_relational_sequence_change(parent, change, live, &routing, &mut departed_witnesses, regions);
- }
- }
-
- /// Whether an element that left in this transaction could have been a witness of `anchor`'s
- /// query.
- ///
- /// A departure removes a witness only by taking one with it: every element under it leaves
- /// too, so a witness that stays is not one whose answer moved - as long as the query reads
- /// nothing but the witness's own facts. Those facts are still in the store until the
- /// transaction is released, and the witness has to have carried the query's dispatch key.
- /// The departure check has to look at the key before the transaction as well, since a witness
- /// can lose its class and leave in the same one.
- fn departure_can_remove_a_witness(
- &self,
- program: SelectorProgramID,
- anchor: RelativeAnchor,
- departed_witnesses: &mut DepartedWitnessKeys<'_>,
- ) -> bool {
- const MAX_DEPARTED_ELEMENTS_TO_PROVE: usize = 256;
- let key = anchor.witness_dispatch;
- if anchor.witness_is_featureless || !key.has_selector_posting() {
- return true;
- }
- let program = self.programs.get(program);
- if !program.selector_node_reads_only_local_facts(program.relative_query(anchor.query).compound) {
- return true;
- }
- if let Some(&(_, carried)) = departed_witnesses.keys.iter().find(|(known, _)| *known == key) {
- return carried;
- }
- let Some(departed) = departed_witnesses.departed else {
- return true;
- };
- let carried = departed.len() > MAX_DEPARTED_ELEMENTS_TO_PROVE
- || departed.iter().any(|&node| self.node_carries(key, node, None));
- departed_witnesses.keys.push((key, carried));
- carried
- }
-
- /// One parent's share of the relational sequence routing: the candidate anchors each live
- /// route can reach from this sequence's seams, filtered by the anchor compound's own feature.
- #[allow(clippy::too_many_arguments)]
- pub(super) fn route_relational_sequence_change(
- &mut self,
- parent: StyleNodeID,
- change: &SequenceChange,
- live: &[LiveRelationalRoute],
- routing: &RoutingRegistry,
- departed_witnesses: &mut DepartedWitnessKeys<'_>,
- regions: &mut ImpactRegions,
- ) {
- let children = &change.children;
- // Where the seams are, with a record nobody could place widened to the whole sequence.
- let clamp = |at: u32| match at == RELATIONAL_RECORD_UNLOCATED {
- true => children.len(),
- false => (at as usize).min(children.len()),
- };
- let mut any_arrived = false;
- let mut any_reparented = false;
- let mut any_departed = false;
- let mut max_any = 0usize;
- let mut max_departed = 0usize;
- let mut max_arrived = 0usize;
- for &(at, side) in &change.relational_records {
- let at = clamp(at);
- max_any = max_any.max(at);
- match side {
- SequenceSide::Arrived | SequenceSide::Reparented => {
- any_arrived = true;
- any_reparented |= side == SequenceSide::Reparented;
- max_arrived = max_arrived.max(at);
- }
- SequenceSide::Departed => {
- any_departed = true;
- max_departed = max_departed.max(at);
- }
- SequenceSide::Moved => {}
- }
- }
-
- // The anchor ranges that do not depend on where in the sequence a seam is, built at most
- // once per parent: the parent and its ancestors - which for an arrival are the arriving
- // element's own ancestors, exactly where a descendant or child query anchors on a witness -
- // and the elements before each of them, where `X:has(~ div .test)` anchors on an `X` that
- // precedes the div a departed witness sat in.
- let mut above: Option<Vec<StyleNodeID>> = None;
- let mut ancestor_predecessors: Option<Vec<StyleNodeID>> = None;
-
- for &LiveRelationalRoute { route, program, anchor } in live {
- let site = route_site(routing, route);
- let anchor_posting = anchor
- .anchor_dispatch
- .has_selector_posting()
- .then_some(anchor.anchor_dispatch);
- // A connecting element publishes its facts, which route feature-bearing witnesses.
- // A reparented element keeps its facts, so every query must also check the new
- // sequence for a witness. Featureless witnesses always need this sequence route.
- let witnessing_arrival = any_reparented || (any_arrived && anchor.witness_is_featureless);
-
- // An in-shadow-tree query anchors on the host of the tree the change happened in. A
- // child query's anchor hosts the tree the parent belongs to and a descendant query's
- // hosts the tree at the top of that chain, so either way there is at most one anchor.
- // A sibling axis leaves the hosted tree, so an in-shadow-tree query on one witnesses
- // nothing and is compiled away rather than reaching here.
- if anchor.match_in_shadow_tree {
- if !any_departed && !witnessing_arrival {
- continue;
- }
- let host = match anchor.axis {
- RelativeAxis::Child => self.tree.host_of(parent),
- RelativeAxis::Descendant => {
- let anchors_above = above.get_or_insert_with(|| {
- std::iter::once(parent).chain(self.tree.ancestors(parent)).collect()
- });
- anchors_above.last().and_then(|&top| self.tree.host_of(top))
- }
- _ => None,
- };
- if let Some(host) = host {
- self.route_relational_anchor(host, program, anchor.query, anchor_posting, &site, regions);
- }
- continue;
- }
-
- match anchor.axis {
- // A descendant stays a descendant of whatever it was a descendant of, and a move
- // inside one sequence changes no ancestor at all, so these reach only through the
- // element being a witness that arrived, or one that left and cannot say so.
- RelativeAxis::Descendant | RelativeAxis::Child => {
- let departure_reaches =
- any_departed && self.departure_can_remove_a_witness(program, anchor, departed_witnesses);
- if !departure_reaches && !witnessing_arrival {
- continue;
- }
- let anchors_above = above
- .get_or_insert_with(|| std::iter::once(parent).chain(self.tree.ancestors(parent)).collect());
- let candidates: &[StyleNodeID] = match anchor.axis {
- // A witness of a child query is a child of its anchor. One that left from under
- // this parent was this parent's, and one that left from deeper took its anchor
- // with it.
- RelativeAxis::Child => &anchors_above[..1],
- _ => anchors_above,
- };
- for &candidate in candidates {
- self.route_relational_anchor(candidate, program, anchor.query, anchor_posting, &site, regions);
- }
- }
- // The seam moves which elements are siblings of which, whoever made it, and the
- // anchors are as far back as the argument's leading chain reaches.
- RelativeAxis::NextSibling => {
- for &(at, _) in &change.relational_records {
- let at = clamp(at);
- let reach = at.min(anchor.adjacent_reach as usize);
- for &candidate in children[at - reach..at].iter().rev() {
- self.route_relational_anchor(
- candidate,
- program,
- anchor.query,
- anchor_posting,
- &site,
- regions,
- );
- }
- }
- }
- RelativeAxis::FollowingSibling => {
- for &candidate in &children[..max_any] {
- self.route_relational_anchor(candidate, program, anchor.query, anchor_posting, &site, regions);
- }
- }
- // A witness under a sibling is not a sibling, so a witness that left, or arrived
- // carrying nothing, has to be looked for under a sibling of an ancestor as well as
- // under one of its own. A seam somebody else made still reaches back only as far as
- // the argument's leading chain does.
- RelativeAxis::NextSiblingSubtree => {
- if any_departed || witnessing_arrival {
- let wide_max = match anchor.witness_is_featureless {
- true => max_departed.max(max_arrived),
- false => max_departed,
- };
- for &candidate in &children[..wide_max] {
- self.route_relational_anchor(
- candidate,
- program,
- anchor.query,
- anchor_posting,
- &site,
- regions,
- );
- }
- self.route_relational_ancestor_predecessors(
- parent,
- &mut above,
- &mut ancestor_predecessors,
- program,
- anchor.query,
- anchor_posting,
- &site,
- regions,
- );
- }
- for &(at, side) in &change.relational_records {
- let seam_only = match side {
- SequenceSide::Moved => true,
- SequenceSide::Arrived => !anchor.witness_is_featureless,
- SequenceSide::Departed | SequenceSide::Reparented => false,
- };
- if !seam_only {
- continue;
- }
- let at = clamp(at);
- let reach = at.min(anchor.adjacent_reach as usize);
- for &candidate in children[at - reach..at].iter().rev() {
- self.route_relational_anchor(
- candidate,
- program,
- anchor.query,
- anchor_posting,
- &site,
- regions,
- );
- }
- }
- }
- RelativeAxis::FollowingSiblingSubtree => {
- for &candidate in &children[..max_any] {
- self.route_relational_anchor(candidate, program, anchor.query, anchor_posting, &site, regions);
- }
- if any_departed || witnessing_arrival {
- self.route_relational_ancestor_predecessors(
- parent,
- &mut above,
- &mut ancestor_predecessors,
- program,
- anchor.query,
- anchor_posting,
- &site,
- regions,
- );
- }
- }
- }
- }
- }
-
- /// Route the elements before the parent and before each of its ancestors, which is where a
- /// sibling-subtree query anchors when its witness cannot be walked from.
- #[allow(clippy::too_many_arguments)]
- pub(super) fn route_relational_ancestor_predecessors(
- &mut self,
- parent: StyleNodeID,
- above: &mut Option<Vec<StyleNodeID>>,
- ancestor_predecessors: &mut Option<Vec<StyleNodeID>>,
- program: SelectorProgramID,
- query: RelativeQueryID,
- anchor_posting: Option<PostingKey>,
- site: &RoutingSite<'_>,
- regions: &mut ImpactRegions,
- ) {
- if ancestor_predecessors.is_none() {
- let anchors_above =
- above.get_or_insert_with(|| std::iter::once(parent).chain(self.tree.ancestors(parent)).collect());
- let mut found = Vec::new();
- for &ancestor in anchors_above.iter() {
- let mut sibling = self.tree.previous_element_sibling(ancestor);
- while let Some(previous) = sibling {
- found.push(previous);
- sibling = self.tree.previous_element_sibling(previous);
- }
- }
- *ancestor_predecessors = Some(found);
- }
- for &candidate in ancestor_predecessors.as_ref().unwrap() {
- self.route_relational_anchor(candidate, program, query, anchor_posting, site, regions);
- }
- }
-
- /// One candidate anchor: an element that does not carry the anchor compound's feature is not
- /// an anchor of this query at all, and the rest have the route's path applied from them.
- #[allow(clippy::too_many_arguments)]
- pub(super) fn route_relational_anchor(
- &mut self,
- candidate: StyleNodeID,
- program: SelectorProgramID,
- query: RelativeQueryID,
- anchor_posting: Option<PostingKey>,
- site: &RoutingSite<'_>,
- regions: &mut ImpactRegions,
- ) {
- if let Some(key) = anchor_posting {
- match self.facts.postings().lookup(key) {
- Lookup::Known(posting) if !posting.contains(candidate) => return,
- Lookup::KnownAbsent => return,
- Lookup::Known(_) | Lookup::Missing(_) => {}
- }
- }
- // An anchor whose retained witness still witnesses it was true and stays true: only
- // zero/nonzero witness transitions can affect selector truth, so nothing reached through
- // this anchor has moved and it drops out of the plan.
- if matches!(
- self.retained_witness_for_anchor(program, query, candidate),
- Lookup::Known(_)
- ) {
- self.counters.bump(Counter::RelationalAnchorsSkippedByWitness);
- return;
- }
- let region = ImpactRegion::follow(candidate, site.path, &self.tree);
- self.add_narrowed_region(region, site, regions);
- }
-
- /// Route a node whose neighbour moved to what a sibling combinator reaches through it.
- ///
- /// `A + B` and `A ~ B` are constraints on B, so B's truth moves when what precedes it does - and
- /// B need not be the subject. In `A + B .target` the sibling step is above the subject, and what
- /// the change reaches is what the rest of the path leads to from B. Both are one walk, because
- /// the node is exactly where the sibling step lands: the remaining steps run from it.
- ///
- /// An adjacent step names one element on either side of the change, so only a neighbour carrying
- /// the origin compound's own feature can have been the `A`. A general step reaches back through
- /// the whole sequence and is not bounded that way.
- #[allow(clippy::too_many_arguments)]
- pub(super) fn route_sibling_relations_to_constrained_side(
- &mut self,
- node: StyleNodeID,
- old: TreeRelations,
- new: TreeRelations,
- constrained_side_moved: bool,
- tree_routing: TreeRoutingMode<'_>,
- sibling_entries: &[SiblingEntry],
- sibling_candidates: &mut SiblingCandidateWorkspace,
- pending: &mut PendingSiblingRoutes,
- ) {
- let routing = Arc::clone(&self.routing);
- if constrained_side_moved {
- sibling_candidates.begin();
- sibling_candidates.candidates.extend(0..sibling_entries.len());
- } else {
- let origins = [old.previous_element_sibling, new.previous_element_sibling]
- .into_iter()
- .flatten();
- self.sibling_entry_candidates(origins, sibling_candidates);
- }
- for &index in &sibling_candidates.candidates {
- let entry = &sibling_entries[index];
- let point = routing.route(entry.route);
- let origin = routing.origin_dispatch_of(entry.route);
- let origin_required = routing.origin_required_of(entry.route);
- let path = routing.path_of(entry.route);
- let origin_can_match = |neighbour: Option<StyleNodeID>| {
- neighbour.is_some_and(|neighbour| {
- self.node_carries_any(origin, neighbour, None)
- && self.node_carries_all(origin_required, neighbour, None)
- })
- };
- let (origin_was_beside_it, exact_tree_evaluation) = match path.first() {
- Some(InverseStep::NextSibling) => {
- let old_can_match = origin_can_match(old.previous_element_sibling);
- let new_can_match = origin_can_match(new.previous_element_sibling);
- // A predecessor that could not satisfy the compound leaves the whole entry
- // unsatisfied, so an arrival can be decided from the new side alone. A
- // departure-only transaction can instead compare the complete live entry with
- // the reconstructed old sibling sequence, including when both predecessors pass
- // this inexpensive compound prefilter.
- let one_sided = !old_can_match
- && new_can_match
- && tree_routing.use_exact
- && self.entry_is_monotone_in_the_tree_id(point.entry);
- let exact = match (
- tree_routing.use_exact
- && tree_routing.has_before_sibling_relations
- && self.entry_can_use_before_sibling_relations_id(point.entry),
- one_sided,
- ) {
- (true, _) => Some(ExactTreeEvaluation::BeforeSiblingRelations),
- (false, true) => Some(ExactTreeEvaluation::Arrival),
- (false, false) => None,
- };
- (old_can_match || new_can_match, exact)
- }
- // A general-sibling constraint reads the set of preceding siblings, not which one
- // is immediately adjacent. A neighbour landing beside this stationary node changes
- // that set only through its own facts, which arrival or departure routing handles.
- // The seam itself matters only when the constrained node moved to another position.
- Some(InverseStep::FollowingSiblings) => (constrained_side_moved, None),
- _ => (false, None),
- };
- if !origin_was_beside_it {
- continue;
- }
- let region = ImpactRegion::follow(node, &path[1..], &self.tree);
- let routes = pending.regions_for(PendingSiblingRoute {
- route: entry.route,
- kind: exact_tree_evaluation.map_or(SiblingRouteKind::BeyondSibling, |_| SiblingRouteKind::ExactUnion),
- exact_tree_evaluation,
- });
- self.push_pending_region(routes, region);
- }
- }
-
- /// Route a node that moved to the siblings looking at it from where it landed.
- ///
- /// The mirror of routing its departure: `A + B` reaches B from A, so an `A` that moved is asked
- /// the same question from its new place as its old one. Nothing about its features changed, so
- /// no other path routes it.
- pub(super) fn route_arrival_to_siblings(
- &mut self,
- node: StyleNodeID,
- tree_routing: TreeRoutingMode<'_>,
- sibling_entries: &[SiblingEntry],
- sibling_candidates: &mut SiblingCandidateWorkspace,
- pending: &mut PendingSiblingRoutes,
- ) {
- let routing = Arc::clone(&self.routing);
- let candidate_entries = self.sibling_entry_candidates([node], sibling_candidates);
- for &index in candidate_entries {
- let entry = &sibling_entries[index];
- let point = routing.route(entry.route);
- let origin = routing.origin_dispatch_of(entry.route);
- let origin_required = routing.origin_required_of(entry.route);
- let path = routing.path_of(entry.route);
- if !self.node_carries_any(origin, node, None) {
- continue;
- }
- if !self.node_carries_all(origin_required, node, None) {
- continue;
- }
- let region = ImpactRegion::follow(node, path, &self.tree);
- let exact_tree_evaluation = (tree_routing.use_exact
- && tree_routing.has_before_sibling_relations
- && self.entry_can_use_before_sibling_relations_id(point.entry))
- .then(|| {
- if matches!(path.first(), Some(InverseStep::FollowingSiblings))
- && self.entry_is_monotone_in_the_tree_id(point.entry)
- {
- ExactTreeEvaluation::MonotonicArrival
- } else {
- ExactTreeEvaluation::BeforeSiblingRelations
- }
- });
- let routes = pending.regions_for(PendingSiblingRoute {
- route: entry.route,
- kind: exact_tree_evaluation.map_or(SiblingRouteKind::Full, |_| SiblingRouteKind::ExactUnion),
- exact_tree_evaluation,
- });
- self.push_pending_region(routes, region);
- }
- }
-
- pub(super) fn sibling_entry_candidates<'a>(
- &self,
- nodes: impl IntoIterator<Item = StyleNodeID>,
- workspace: &'a mut SiblingCandidateWorkspace,
- ) -> &'a [usize] {
- workspace.begin();
- for node in nodes {
- let mut append = |key| {
- for &route in self.routing.sibling_first_routes_for_origin(key) {
- workspace.append(route);
- }
- };
- append(DispatchKey::Universal);
- self.for_each_dispatch_key_of_node(node, &mut append);
- for fact in self.facts.states_of_node(node).facts() {
- append(DispatchKey::State(fact));
- }
- if self.facts.heading_level_of(node) != 0 {
- append(DispatchKey::Heading);
- }
- if self.tree.parent(node).is_none() {
- append(DispatchKey::Root);
- }
- }
- &workspace.candidates
- }
-
- /// Route an element leaving to the siblings that were looking at it.
- ///
- /// `A + B` and `A ~ B` are constraints on B written in terms of an element beside it, so an `A`
- /// leaving changes B's truth. Those are also the only non-relational paths that reach outside
- /// the departing subtree: a descendant or child step from the element lands on nodes that left
- /// with it. The element's own facts say which selectors named it, and its old relations say
- /// where the path starts from now that it is gone.
- pub(super) fn route_departure_to_siblings(
- &mut self,
- node: StyleNodeID,
- relations: TreeRelations,
- tree_routing: TreeRoutingMode<'_>,
- sibling_entries: &[SiblingEntry],
- sibling_candidates: &mut SiblingCandidateWorkspace,
- pending: &mut PendingSiblingRoutes,
- ) {
- if sibling_entries.is_empty() {
- return;
- }
- let routing = Arc::clone(&self.routing);
- self.sibling_entry_candidates([node], sibling_candidates);
- // The live state row may already reflect a clear recorded in this transaction, but the old
- // sibling route still depends on every state the node carried before it departed.
- let before_states = self
- .transaction_fact_view
- .as_ref()
- .and_then(|view| view.row_of(TransactionFactSide::Before, self.facts.primary(), node))
- .map(|(facts, row)| facts.states_of(row));
- if let Some(before_states) = before_states {
- for state in before_states.facts() {
- for &route in routing.sibling_first_routes_for_origin(DispatchKey::State(state)) {
- sibling_candidates.append(route);
- }
- }
- }
- let candidate_entries = &sibling_candidates.candidates;
- let state_moved = before_states.is_some_and(|before| before != self.facts.states_of_node(node));
- let old_next_relocated = relations.next_element_sibling.is_some_and(|next| {
- self.tree.parent(next) == relations.parent
- && self.tree.previous_element_sibling(next) != relations.previous_element_sibling
- && tree_routing.tree_position_changed(next)
- });
- for &index in candidate_entries {
- let entry = &sibling_entries[index];
- let point = routing.route(entry.route);
- let origin = routing.origin_dispatch_of(entry.route);
- let origin_required = routing.origin_required_of(entry.route);
- let path = routing.path_of(entry.route);
- // The element has to have satisfied the compound the sibling combinator constrains, or
- // the selector never reached past it in the first place.
- if !self.node_carries_any(origin, node, None) {
- continue;
- }
- if !self.node_carries_all(origin_required, node, None) {
- continue;
- }
- let Some(region) = self.follow_from_departed_position(relations, path, old_next_relocated) else {
- continue;
- };
- // Exact old-tree evaluation shares current local facts. It cannot prove a route whose
- // departing origin also changed state because that state has already been committed.
- let departure_can_be_compared_exactly = tree_routing.use_exact
- && tree_routing.has_before_sibling_relations
- && !state_moved
- && self.entry_can_use_before_sibling_relations_id(point.entry);
- // The waypoints are the compounds the path passes through, checked by walking back from
- // a candidate. That walk arrives at the place the element had, which no longer leads to
- // it, so the candidate stands on its own features.
- let exact_tree_evaluation = departure_can_be_compared_exactly.then(|| {
- if matches!(path.first(), Some(InverseStep::FollowingSiblings))
- && self.entry_is_monotone_in_the_tree_id(point.entry)
- {
- ExactTreeEvaluation::MonotonicDeparture
- } else {
- ExactTreeEvaluation::BeforeSiblingRelations
- }
- });
- let routes = pending.regions_for(PendingSiblingRoute {
- route: entry.route,
- kind: exact_tree_evaluation.map_or(SiblingRouteKind::Departure, |_| SiblingRouteKind::ExactUnion),
- exact_tree_evaluation,
- });
- self.push_pending_region(routes, region);
- }
- }
-
- /// Follow a transpose path from the place a departed element had.
- ///
- /// Only the first step needs the old relations: it is the one taken from the element itself, and
- /// the element is no longer on the tree to be stepped from. Every step after it starts from a
- /// node that is still there.
- pub(super) fn follow_from_departed_position(
- &self,
- relations: TreeRelations,
- path: &[InverseStep],
- old_next_relocated: bool,
- ) -> Option<ImpactRegion> {
- let first = match path.first()? {
- InverseStep::NextSibling => ImpactRegion::Node(relations.next_element_sibling?),
- // Everything past the place the element had starts at its old next sibling. Anchor
- // the range at that node's live position: the old previous sibling may itself have
- // moved to another parent in this transaction. If the next sibling moved too, the
- // old parent's current children are the narrowest live-tree range which still covers
- // every resident subject past the departure.
- InverseStep::FollowingSiblings => {
- let parent = relations.parent?;
- let next = relations.next_element_sibling?;
- if old_next_relocated || self.tree.parent(next) != Some(parent) {
- ImpactRegion::Children(parent)
- } else if let Some(previous) = self.tree.previous_element_sibling(next) {
- ImpactRegion::FollowingSiblings(previous)
- } else {
- ImpactRegion::Children(parent)
- }
- }
- _ => return None,
- };
- Some(
- path[1..]
- .iter()
- .fold(first, |region, &step| region.step(step, &self.tree)),
- )
- }
- pub(super) fn sequence_origin_candidates<'a>(
- &self,
- node: StyleNodeID,
- index: &'a mut NthSequenceEntryIndex,
- ) -> &'a [usize] {
- advance_epoch(&mut index.epoch, 1, &mut [&mut index.candidate_epochs]);
- index.candidates.clear();
- let mut append_candidate = |candidate: usize| {
- if index.candidate_epochs.mark(candidate, index.epoch) {
- index.candidates.push(candidate);
- }
- };
- for candidate in index.unindexed.iter().copied() {
- append_candidate(candidate);
- }
- let mut append = |key| {
- if let Some(entries) = index.by_origin.get(&key) {
- for candidate in entries.iter().copied() {
- append_candidate(candidate);
- }
- }
- };
- self.for_each_dispatch_key_of_node(node, &mut append);
- &index.candidates
- }
-
- pub(super) fn for_each_dispatch_key_of_node(&self, node: StyleNodeID, mut callback: impl FnMut(DispatchKey)) {
- let tag = self.facts.tag_of_node(node);
- if !tag.is_none() {
- callback(DispatchKey::TagName(tag));
- }
- let folded_tag = self.facts.folded_tag_of_node(node);
- if !folded_tag.is_none() && folded_tag != tag {
- callback(DispatchKey::TagName(folded_tag));
- }
- let id = self.facts.id_of_node(node);
- if !id.is_none() {
- callback(DispatchKey::Id(id));
- }
- for &class in self.facts.classes_of_node(node) {
- callback(DispatchKey::Class(class));
- }
- for attribute in self.facts.attributes_of_node(node) {
- for name in self.facts.attribute_name_keys(attribute) {
- callback(DispatchKey::AttributeName(name));
- }
- }
- let directionality = self.facts.directionality_of(node);
- if !directionality.is_none() {
- callback(DispatchKey::Directionality(directionality));
- }
- if let Some(row) = self.facts.primary().row_of(node) {
- for &state in self.facts.primary().custom_states_of(row) {
- callback(DispatchKey::CustomState(state));
- }
- for &part in self.facts.primary().parts_of(row) {
- callback(DispatchKey::Part(part));
- }
- }
- // The facts describe where the node ended up carrying what it ended up with. A key this
- // transaction is taking away named the node when a route still read it, so include that key.
- for &key in self.moved_features_of(node) {
- callback(key);
- }
- }
-
- /// Route what the transaction did to the child sequences it touched.
- ///
- /// The lookup that asks whether any attached selector depends on a child sequence at all is
- /// done once for the transaction rather than once per mutation, so a document with no
- /// positional selectors pays one lookup however much of its tree moved.
- pub(super) fn route_sequence_changes(
- &mut self,
- sequences: &SequenceChanges,
- changed_sheets: &[SheetID],
- tree_routing: TreeRoutingMode<'_>,
- regions: &mut ImpactRegions,
- workspace: &mut ImpactPlanningWorkspace,
- ) -> DeferredSequenceRoutes {
- if sequences.entries.is_empty() {
- return DeferredSequenceRoutes::default();
- }
- let routing = Arc::clone(&self.routing);
- let exact_before_sibling_relations = tree_routing.use_exact && tree_routing.has_before_sibling_relations;
- let use_cached_index = changed_sheets.is_empty();
- let mut entries = if use_cached_index {
- routing.live_sequence_entries(&self.program).to_vec()
- } else {
- let route_liveness = routing.route_liveness(&self.program);
- // A sheet changing attachment needs the routes from both sides of the transaction. The
- // current-program cache intentionally contains only the final side, so build this rare
- // union directly.
- let mut entries = Vec::new();
- for &route in routing.routes_for(RoutingKey::Structural) {
- let route_is_live = route_liveness.contains(route.index());
- let rule = routing.rule_of(route);
- if !route_is_live
- && !self.program.rule_can_decide(rule)
- && !changed_sheets.contains(&self.program.rule_sheet(rule))
- {
- continue;
- }
- let point = routing.route(route);
- let (selector_program, _) = self.programs.entry_location(point.entry);
- if !route_is_live && self.program.rule_version(rule).selector_program != Some(selector_program) {
- continue;
- }
- let operator = self
- .programs
- .get(selector_program)
- .node(point.selector_node.expect("structural route has no operator"));
- if !matches!(operator, SelectorOp::Empty | SelectorOp::NthPosition(_)) {
- continue;
- }
- entries.push(SequenceEntry {
- route,
- operator,
- can_compare_exactly: self.entry_can_use_before_sibling_relations_id(point.entry),
- });
- }
- entries
- };
- for entry in &mut entries {
- entry.can_compare_exactly &= exact_before_sibling_relations;
- }
- if entries.is_empty() {
- return DeferredSequenceRoutes::default();
- }
-
- // An entry the automaton answers exactly waits for the convergence walk: when the walk
- // re-compares every member of every touched sequence, its exact diffs subsume this
- // route's generic narrowing entirely, so routing it here would only be discarded. Shadow-
- // scope sequences stay on the immediate path, since the walk serves only the document
- // scope. Should the walk fail to cover, the held entries are routed afterwards.
- let sequences_are_document_scoped = sequences
- .iter()
- .all(|(parent, _)| self.tree.tree_scope(parent) == TreeScopeID::DOCUMENT);
- let (_, dispatch) = self.prepare_scope_program(TreeScopeID::DOCUMENT);
- let deferred_mask: Vec<bool> = entries
- .iter()
- .map(|entry| {
- sequences_are_document_scoped && dispatch.prefixes().contains_entry(routing.route(entry.route).entry)
- })
- .collect();
-
- let any_deferred = deferred_mask.iter().any(|&deferred| deferred);
- let any_immediate = deferred_mask.iter().any(|&deferred| !deferred);
- if any_immediate {
- let mut cached_entry_index = use_cached_index.then(|| routing.live_sequence_index(&self.program));
- let mut owned_entry_index = (!use_cached_index).then(|| SequenceEntryIndex::build(&entries, &routing));
- let entry_index = match (&mut cached_entry_index, &mut owned_entry_index) {
- (Some(cached), None) => &mut **cached,
- (None, Some(owned)) => owned,
- _ => unreachable!(),
- };
-
- self.route_sequence_entries(
- sequences,
- &entries,
- entry_index,
- SequenceEntrySelection {
- mask: &deferred_mask,
- route_masked: false,
- },
- regions,
- workspace,
- );
- }
-
- let mut deferred = DeferredSequenceRoutes::default();
- if any_deferred {
- deferred.entries = entries;
- deferred.deferred = deferred_mask;
- }
-
- deferred
- }
-
- /// Route the selected sequence entries through every touched child sequence and narrow each
- /// entry's routed regions.
- #[allow(clippy::too_many_arguments)]
- fn route_sequence_entries(
- &mut self,
- sequences: &SequenceChanges,
- entries: &[SequenceEntry],
- entry_index: &mut SequenceEntryIndex,
- selection: SequenceEntrySelection<'_>,
- regions: &mut ImpactRegions,
- workspace: &mut ImpactPlanningWorkspace,
- ) {
- let routing = Arc::clone(&self.routing);
- let parent_emptiness = entry_index
- .empty
- .iter()
- .any(|&empty_index| selection.selects(empty_index));
- let mut pending_regions: Vec<Vec<ImpactRegion>> = (0..entries.len()).map(|_| Vec::new()).collect();
-
- for (parent, change) in sequences.iter() {
- // The parent's own emptiness moved with the child count, and nothing else about it
- // did, so it is named only when something asks, attributed to the asking rules so a
- // retained answer refreshes those instead of poisoning to a full re-derivation.
- if parent_emptiness {
- for &empty_index in &entry_index.empty {
- if !selection.selects(empty_index) {
- continue;
- }
- let route = entries[empty_index].route;
- let point = self.routing.route(route);
- self.record_selector_truth_refresh(parent, Some((self.routing.rule_of(route), point.entry)));
- }
- regions.add(ImpactRegion::Node(parent));
- }
- self.add_sequence_region(
- parent,
- change,
- entries,
- entry_index,
- selection,
- &mut pending_regions,
- regions,
- );
- }
- for (entry, routed_regions) in entries.iter().zip(&mut pending_regions) {
- if routed_regions.is_empty() {
- continue;
- }
- routed_regions.sort_unstable();
- routed_regions.dedup();
- let site = entry.site(&routing);
- self.discard_regions_covered_by_subtree(routed_regions, &site, regions);
- self.add_narrowed_regions_with_workspace(routed_regions, &site, regions, workspace);
- }
- }
-
- /// Flush the sequence routes held back for the convergence walk: drop them when the walk's
- /// exact diffs covered every touched sequence, route and narrow them the ordinary way
- /// otherwise.
- pub(super) fn flush_deferred_sequence_routes(
- &mut self,
- mut deferred: DeferredSequenceRoutes,
- covered: bool,
- sequences: &SequenceChanges,
- regions: &mut ImpactRegions,
- workspace: &mut ImpactPlanningWorkspace,
- ) {
- let entries = std::mem::take(&mut deferred.entries);
- let deferred_mask = std::mem::take(&mut deferred.deferred);
- let covered = covered || regions.covers_document();
- if covered || entries.is_empty() {
- return;
- }
- let routing = Arc::clone(&self.routing);
- let mut entry_index = SequenceEntryIndex::build(&entries, &routing);
-
- self.route_sequence_entries(
- sequences,
- &entries,
- &mut entry_index,
- SequenceEntrySelection {
- mask: &deferred_mask,
- route_masked: true,
- },
- regions,
- workspace,
- );
- }
-
- /// Whether an of-type position kept the same truth across this transaction.
- fn nth_of_type_truth_unchanged(
- &mut self,
- nth: NthPosition,
- node: StyleNodeID,
- workspace: &mut MatchScratch,
- ) -> bool {
- let Some(view) = self
- .transaction_fact_view
- .as_ref()
- .filter(|view| view.before_sibling_relations_available)
- else {
- return false;
- };
- let resident_facts = self.facts.primary();
- let old_count = MatchEvaluator::new(&self.tree, resident_facts)
- .with_transaction_fact_view(view, TransactionFactSide::Before)
- .with_match_workspace(workspace, MatchEvaluationSide::OldTree)
- .indexed_sibling_position(nth, node)
- .ok()
- .flatten();
- let new_count = MatchEvaluator::new(&self.tree, resident_facts)
- .with_transaction_fact_view(view, TransactionFactSide::After)
- .with_match_workspace(workspace, MatchEvaluationSide::Current)
- .indexed_sibling_position(nth, node)
- .ok()
- .flatten();
- old_count
- .zip(new_count)
- .is_some_and(|(old, new)| nth.matches_count(old) == nth.matches_count(new))
- }
-
- /// Name the children whose position in the sequence actually moved.
- ///
- /// A child arriving or leaving at index `i` shifts the count-from-the-start of everything from
- /// `i` onwards, and the count-from-the-end of everything before it. Each positional selector
- /// then decides for itself which of those it can name: `:first-child` asks about one position
- /// and `:nth-child(3)` about three, and a selector with a step sees the whole sequence. A
- /// selector whose subject carries features narrows further, so an insertion between two divs
- /// costs nothing to a document whose positional rules are about table cells.
- #[allow(clippy::too_many_arguments)]
- pub(super) fn add_sequence_region(
- &mut self,
- parent: StyleNodeID,
- change: &SequenceChange,
- entries: &[SequenceEntry],
- entry_index: &mut SequenceEntryIndex,
- selection: SequenceEntrySelection<'_>,
- pending_regions: &mut [Vec<ImpactRegion>],
- regions: &mut ImpactRegions,
- ) {
- let routing = Arc::clone(&self.routing);
- let children = &change.children;
- if children.is_empty() {
- return;
- }
- let mut sequence_match_workspace = MatchScratch::default();
- // What an entry's selector says about the parent of its positional test holds for the
- // whole sequence, so it is decided once per entry here rather than once per moved child.
- const PARENT_UNDECIDED: u8 = 0;
- const PARENT_ADMITS: u8 = 1;
- const PARENT_REJECTS: u8 = 2;
- let mut parent_verdicts = vec![PARENT_UNDECIDED; entries.len()];
-
- // Where in the sequence the earliest and the latest change happened. A change nobody could
- // place leaves the whole sequence moved, because that is all that is still provable.
- let (first_moved, last_moved) = match change.span {
- Some(span) if !change.unlocated => span,
- _ => (0, children.len()),
- };
-
- // A child arriving or leaving changes whether the parent is empty, and nothing else about
- // it. The parent is the element that test is asked of, so it is the witness.
- for &entry_index in &entry_index.empty {
- if !selection.selects(entry_index) {
- continue;
- }
- let entry = &entries[entry_index];
- let point = routing.route(entry.route);
- let path = routing.path_of(entry.route);
- let site = RoutingSite {
- subject: routing.subject_dispatch_of(entry.route),
- subject_required: routing.subject_required_of(entry.route),
- position: routing.subject_position_of(entry.route),
- path,
- waypoints: routing.waypoints_of(entry.route),
- in_flux: None,
- exact_entry: None,
- exact_tree_evaluation: None,
- refresh_rule: Some((routing.rule_of(entry.route), point.entry)),
- };
- match point.anchor {
- Some(anchor) => {
- let (program, _) = self.programs.entry_location(point.entry);
- self.route_from_anchors(parent, program, anchor, &site, regions);
- }
- None => {
- let region = ImpactRegion::follow(parent, path, &self.tree);
- self.push_pending_region(&mut pending_regions[entry_index], region);
- }
- }
- }
-
- for group in &mut entry_index.nth {
- let nth = group.nth;
- // Only the side of the change that moved can have moved: counted from the start, the
- // children at or after the earliest change; counted from the end, those before the
- // latest one - plus the place an element relocated into, whose own count from the end
- // moved with it while nothing after it moved at all.
- let last_from_end = match change.last_relocation {
- Some(at) => last_moved.max(at.saturating_add(1)),
- None => last_moved,
- };
- let moved = match nth.from_end {
- true => 0..last_from_end.min(children.len()),
- false => first_moved.min(children.len())..children.len(),
- };
- // A test that counts a subsequence - `:nth-of-type()`, `:nth-child(... of ...)` - counts
- // something other than the places in this sequence, so a place cannot be turned into a
- // count and back.
- let counts_this_sequence = !nth.of_type && nth.of_selector.is_none();
- // `:nth-child(k)` matches at one position, so an element's answer flips only if its
- // count crossed k - which happens at k-1 and k, and nowhere else. A test with a step
- // matches at many positions, and every count on the moved side shifts.
- // The positional test is not always on the subject: `#list > :first-child .leaf` moves
- // for the descendants of the child whose count crossed. So the entry's own path is
- // followed from each such child to the subjects it reaches.
- let mut name = |engine: &mut Self, at: usize| {
- if !moved.contains(&at) {
- return;
- }
- let Some(&child) = children.get(at) else {
- return;
- };
- if nth.of_type && !change.has_unidentified_type {
- let tag = engine.facts.tag_of_node(child);
- if !tag.is_none() && !change.changed_types.contains(&(tag, engine.facts.namespace_of(child))) {
- return;
- }
- }
- let candidates = engine.sequence_origin_candidates(child, group);
- if !candidates.iter().any(|&candidate| selection.selects(candidate)) {
- return;
- }
- // The moved side names every child whose count COULD have crossed the test, but
- // multiple mutations in one flush routinely cancel: a child shifted by a net even
- // amount keeps its `2n+1` truth. The retained before-side sequence holds the exact
- // old position, so evaluate the test on both sides and drop the children whose
- // truth provably did not move. A relative positional input stays routed: it is a
- // possible witness, and witness truth is judged at its anchors, not here.
- let truth_unchanged_on_both_sides = change.arriving_nodes.binary_search(&child).is_err()
- && match counts_this_sequence {
- true => engine.transaction_fact_view.as_ref().is_some_and(|view| {
- view.before_sibling_relations_available
- && view
- .before_sibling_geometry
- .sibling_positions(child)
- .is_some_and(|old| {
- let new_count = match nth.from_end {
- true => children.len() - at,
- false => at + 1,
- } as i64;
- let old_count = i64::from(match nth.from_end {
- true => old.from_end,
- false => old.from_start,
- });
- nth.matches_count(new_count) == nth.matches_count(old_count)
- })
- }),
- false if nth.of_type => {
- engine.nth_of_type_truth_unchanged(nth, child, &mut sequence_match_workspace)
- }
- false => false,
- };
- for &entry_index in candidates {
- if !selection.selects(entry_index) {
- continue;
- }
- let entry = &entries[entry_index];
- let point = routing.route(entry.route);
- if truth_unchanged_on_both_sides && point.anchor.is_none() {
- continue;
- }
- let path = routing.path_of(entry.route);
- // A whole sibling sequence shares one parent, so what the selector says the
- // parent of the positional test is rejects the sequence in one lookup.
- let parent_verdict = &mut parent_verdicts[entry_index];
- if *parent_verdict == PARENT_UNDECIDED {
- *parent_verdict =
- match engine.node_carries_any(routing.parent_dispatch_of(entry.route), parent, None) {
- true => PARENT_ADMITS,
- false => PARENT_REJECTS,
- };
- }
- if *parent_verdict == PARENT_REJECTS {
- continue;
- }
- // A non-relational positional input sits in one compound of the selector. A
- // child that cannot satisfy the rest of that compound cannot route through it.
- //
- // A relational position routes a possible witness to its anchors. Keep that
- // conservative: a relocation has two witness positions, while this sequence
- // scan sees only the final node and its facts.
- if point.anchor.is_none()
- && (!engine.node_carries_any(routing.origin_dispatch_of(entry.route), child, None)
- || !engine.node_carries_all(routing.origin_required_of(entry.route), child, None))
- {
- continue;
- }
- let site = entry.site(&routing);
- // A positional test inside a `:has()` argument makes the child a possible
- // witness, not a subject: its anchors have to be resolved before the path
- // continues.
- match point.anchor {
- Some(anchor) => {
- let (program, _) = engine.programs.entry_location(point.entry);
- engine.route_from_anchors(child, program, anchor, &site, regions);
- }
- None => {
- let region = ImpactRegion::follow(child, path, &engine.tree);
- engine.push_pending_region(&mut pending_regions[entry_index], region);
- }
- }
- }
- };
- // A subsequence-counting test names every element on the moved side of an affected
- // subsequence instead; the closure above restricts an `of-type` subsequence to the
- // qualified types that actually joined or left.
- match counts_this_sequence && nth.step == 0 && nth.offset >= 1 {
- true => {
- // An arrival pushes counts up and a departure pulls them down, so an element
- // whose count is `c` now held anything from `c - arrivals` to `c + departures`.
- // It crossed the one count the selector names exactly when that lies in the
- // range, which is what bounds the positions to name. One mutation of one
- // sequence therefore names two of them, and nothing widens except by as much as
- // the sequence actually moved.
- let offset = nth.offset as usize;
- let lowest = offset.saturating_sub(change.departures as usize).max(1);
- let highest = offset.saturating_add(change.arrivals as usize);
- for count in lowest..=highest {
- let at = match nth.from_end {
- true => match children.len().checked_sub(count) {
- Some(at) => at,
- None => continue,
- },
- false => count - 1,
- };
- name(self, at);
- }
- }
- false
- if nth.of_type
- && nth.step == 0
- && nth.offset >= 1
- && !change.has_unidentified_type
- && change.last_relocation.is_none() =>
- {
- // The same bound holds within each subsequence of one type, whose count moved by
- // at most as much as the whole sequence did. Only the types that joined or left
- // moved at all, so their children are counted from the end the test counts from,
- // which stops once every such type is past the highest count that can have
- // crossed. A child whose type is unknown could be of any of them, which leaves
- // the moved side as the bound.
- let offset = nth.offset as usize;
- let lowest = offset.saturating_sub(change.departures as usize).max(1);
- let highest = offset.saturating_add(change.arrivals as usize);
- let mut counts: SmallVec<[usize; 4]> = smallvec::smallvec![0; change.changed_types.len()];
- let mut types_past_highest = 0;
- let mut crossing: SmallVec<[usize; 8]> = SmallVec::new();
- let mut bounded = true;
- for step in 0..children.len() {
- if types_past_highest == counts.len() {
- break;
- }
- let at = match nth.from_end {
- true => children.len() - 1 - step,
- false => step,
- };
- let child = children[at];
- let tag = self.facts.tag_of_node(child);
- if tag.is_none() {
- bounded = false;
- break;
- }
- let child_type = (tag, self.facts.namespace_of(child));
- let Some(type_index) = change.changed_types.iter().position(|&changed| changed == child_type)
- else {
- continue;
- };
- counts[type_index] += 1;
- let count = counts[type_index];
- if count == highest + 1 {
- types_past_highest += 1;
- }
- if (lowest..=highest).contains(&count) {
- crossing.push(at);
- }
- }
- if bounded {
- for at in crossing {
- name(self, at);
- }
- } else {
- for at in moved.clone() {
- name(self, at);
- }
- }
- }
- false => {
- for at in moved.clone() {
- if counts_this_sequence && change.last_relocation.is_none() {
- let Some(&child) = children.get(at) else {
- continue;
- };
- if change.arriving_nodes.binary_search(&child).is_err() {
- let current = match nth.from_end {
- true => children.len() - at,
- false => at + 1,
- } as i64;
- let first = (current - i64::from(change.arrivals)).max(1);
- let last = current + i64::from(change.departures);
- if !nth.could_change_from_range(current, first, last) {
- continue;
- }
- }
- }
- name(self, at);
- }
- }
- }
- }
- drop(parent_verdicts);
-
- drop(sequence_match_workspace);
- }
-
- /// Route a possible relational witness through the anchors whose truth it can flip.
- ///
- /// The anchor set is bounded by the inverse of the query's axis - one element for a child or
- /// adjacent-sibling query, the ancestor path for a descendant one - and then filtered to the
- /// ones that actually carry the anchor compound's own feature. `.card:has(.error) .button`
- /// therefore reaches the `.button` elements under the `.card` ancestors of the changed
- /// `.error`, rather than every descendant of every ancestor.
- pub(super) fn route_from_anchors(
- &mut self,
- witness: StyleNodeID,
- program: SelectorProgramID,
- anchor: RelativeAnchor,
- site: &RoutingSite<'_>,
- regions: &mut ImpactRegions,
- ) {
- if anchor.input_is_on_the_anchor {
- self.counters.bump(Counter::RelationalAnchorsConsidered);
- let region = ImpactRegion::follow(witness, site.path, &self.tree);
- self.add_narrowed_region(region, site, regions);
- return;
- }
-
- // The input is a step away from the witness, so no walk from it finds the anchors: the
- // step can leave the anchor's subtree, which puts the changed element above the anchor
- // rather than below it. What the query still says is what a witness of it must carry, and
- // the elements carrying that are enumerable. Route from each of them instead.
- if !anchor.input_is_on_the_witness {
- self.route_from_possible_witnesses(program, anchor, site, regions);
- return;
- }
-
- // OPTIMIZATION: Resolve the anchor posting once before walking the inverse axis. A known
- // empty posting rules out every anchor, regardless of the number of witnesses.
- let anchor_posting = if anchor.anchor_dispatch.has_selector_posting() {
- match self.facts.postings().lookup(anchor.anchor_dispatch) {
- Lookup::Known(posting) => Some(posting),
- Lookup::KnownAbsent => return,
- Lookup::Missing(_) => None,
- }
- } else {
- None
- };
- let mut anchors = Vec::new();
- let mut considered = 0;
- let mut visit = |candidate| {
- considered += 1;
- if anchor_posting.is_none_or(|posting| posting.contains(candidate)) {
- anchors.push(candidate);
- }
- };
- match anchor.match_in_shadow_tree {
- true => possible_hosting_anchors(anchor.axis, witness, &self.tree, &mut visit),
- false => possible_anchors(anchor.axis, witness, &self.tree, None, &mut visit),
- }
- self.counters.add(Counter::RelationalAnchorsConsidered, considered);
-
- for candidate in anchors {
- self.route_possible_anchor(candidate, program, anchor, site, regions);
- }
- }
-
- /// Route one element that may be an anchor whose relational truth moved.
- fn route_possible_anchor(
- &mut self,
- candidate: StyleNodeID,
- program: SelectorProgramID,
- anchor: RelativeAnchor,
- site: &RoutingSite<'_>,
- regions: &mut ImpactRegions,
- ) {
- // An anchor whose retained witness still witnesses it was true and stays true: only
- // zero/nonzero witness transitions can affect selector truth, so nothing reached
- // through this anchor has moved and it drops out of the plan. A position-testing
- // argument is excluded: a sibling mutation can flip such a witness without ever
- // touching it, so its retained record proves nothing here.
- if !self
- .programs
- .get(program)
- .subtree_tests_position(self.programs.get(program).relative_query(anchor.query).compound)
- && matches!(
- self.retained_witness_for_anchor(program, anchor.query, candidate),
- Lookup::Known(_)
- )
- {
- self.counters.bump(Counter::RelationalAnchorsSkippedByWitness);
- return;
- }
- let region = ImpactRegion::follow(candidate, site.path, &self.tree);
- self.add_narrowed_region(region, site, regions);
- }
-
- /// Route a relational query from every element that could witness it.
- ///
- /// Used when no single changed element stands in for the witness: the input is a step away
- /// from one, or the change reshaped a child sequence the argument reaches across. What the
- /// query still says is what a witness of it must carry, and the elements carrying that are
- /// enumerable from the posting.
- pub(super) fn route_from_possible_witnesses(
- &mut self,
- program: SelectorProgramID,
- anchor: RelativeAnchor,
- site: &RoutingSite<'_>,
- regions: &mut ImpactRegions,
- ) {
- // Every anchor a witness walk can find carries the anchor compound's own feature, so when
- // fewer elements carry that than could be witnesses, the anchors are the cheaper side to
- // enumerate. `.item:has(+ .divider + [data-selected])` names a handful of items and every
- // cell of a table as a possible witness.
- if anchor.anchor_dispatch.has_selector_posting() {
- let witness_count = match anchor.witness_dispatch.has_selector_posting() {
- true => match self.facts.postings().lookup(anchor.witness_dispatch) {
- Lookup::Known(posting) => Some(posting.len()),
- Lookup::KnownAbsent => Some(0),
- Lookup::Missing(_) => None,
- },
- false => None,
- };
- match self.facts.postings().lookup(anchor.anchor_dispatch) {
- Lookup::KnownAbsent => return,
- Lookup::Known(posting)
- if witness_count.is_none_or(|count| posting.len() < count)
- && (posting.len() <= SMALL_CANDIDATE_SOURCE
- || posting.len() * SELECTIVE_SHARE_DIVISOR
- <= self.tree.connected_element_count().max(1) as usize) =>
- {
- let anchors: Vec<StyleNodeID> = posting.candidates().collect();
- self.counters
- .add(Counter::RelationalAnchorsConsidered, anchors.len() as u64);
- for candidate in anchors {
- if self.tree.is_live(candidate) {
- self.route_possible_anchor(candidate, program, anchor, site, regions);
- }
- }
- return;
- }
- Lookup::Known(_) | Lookup::Missing(_) => {}
- }
- }
- if !anchor.witness_dispatch.has_selector_posting() {
- self.add_narrowed_region(ImpactRegion::Document, site, regions);
- return;
- }
- let candidates: Vec<StyleNodeID> = match self.facts.postings().lookup(anchor.witness_dispatch) {
- Lookup::Known(posting) => posting.candidates().collect(),
- Lookup::KnownAbsent => Vec::new(),
- Lookup::Missing(_) => {
- self.add_narrowed_region(ImpactRegion::Document, site, regions);
- return;
- }
- };
- if candidates.len() > SMALL_CANDIDATE_SOURCE
- && candidates.len() * SELECTIVE_SHARE_DIVISOR > self.tree.connected_element_count().max(1) as usize
- {
- self.add_narrowed_region(ImpactRegion::Document, site, regions);
- return;
- }
- for candidate in candidates {
- self.route_from_anchors(
- candidate,
- program,
- RelativeAnchor {
- input_is_on_the_witness: true,
- input_is_on_the_anchor: false,
- ..anchor
- },
- site,
- regions,
- );
- }
- }
-
- /// Whether `key` names the fact the input moved on `node`.
- ///
- /// An attribute has two names - its own, and the any-namespace form `[*|x]` dispatches under -
- /// and an input names only the first. The element is removed from both postings as the attribute
- /// leaves, so a `[*|x]` subject would find no candidate at all unless the shared form counts as
- /// in flux too. This is what keeps a removal routable: the posting no longer lists the element,
- /// and the fact that just moved is the reason it does not.
- pub(super) fn key_is_in_flux(
- &self,
- key: DispatchKey,
- node: StyleNodeID,
- in_flux: Option<(StyleNodeID, DispatchKey)>,
- ) -> bool {
- let Some((flux_node, flux_key)) = in_flux else {
- return false;
- };
- if flux_node != node {
- return false;
- }
- if flux_key == key {
- return true;
- }
- match (flux_key, key) {
- (DispatchKey::AttributeName(moved), DispatchKey::AttributeName(named)) => self
- .facts
- .attribute_name_keys(moved)
- .any(|candidate| candidate == named),
- _ => false,
- }
- }
-
- /// Whether `node` carries at least one of `keys`. An empty set distinguishes nothing, so it
- /// admits every node rather than rejecting every one. A feature moving in this transaction is
- /// admitted from either side: structural routing has no one feature input to pass as `in_flux`.
- pub(super) fn node_carries_any(
- &self,
- keys: &[DispatchKey],
- node: StyleNodeID,
- in_flux: Option<(StyleNodeID, DispatchKey)>,
- ) -> bool {
- if keys.is_empty() {
- return true;
- }
- keys.iter().any(|&key| self.node_carries(key, node, in_flux))
- }
-
- /// Whether `node` carries every independently necessary key of one compound.
- pub(super) fn node_carries_all(
- &self,
- keys: &[DispatchKey],
- node: StyleNodeID,
- in_flux: Option<(StyleNodeID, DispatchKey)>,
- ) -> bool {
- keys.iter().all(|&key| self.node_carries(key, node, in_flux))
- }
-
- pub(super) fn node_carries(
- &self,
- key: DispatchKey,
- node: StyleNodeID,
- in_flux: Option<(StyleNodeID, DispatchKey)>,
- ) -> bool {
- if self.key_is_in_flux(key, node, in_flux) || self.moved_features_of(node).contains(&key) {
- return true;
- }
- let is_root = self.tree.parent(node).is_none();
- let resident_facts = self.facts.primary();
- if resident_facts
- .row_of(node)
- .is_some_and(|row| resident_facts.carries_dispatch_key(row, key, is_root))
- {
- return true;
- }
- if self
- .transaction_fact_view
- .as_ref()
- .and_then(|view| view.row_of(TransactionFactSide::Before, resident_facts, node))
- .map(|(facts, row)| facts.carries_dispatch_key(row, key, is_root))
- == Some(true)
- {
- return true;
- }
- if resident_facts.row_of(node).is_some() {
- return false;
- }
- self.facts.carries_local_dispatch_key(node, key).unwrap_or_else(|| {
- !key.has_selector_posting()
- || match self.facts.postings().lookup(key) {
- Lookup::Known(posting) => posting.contains(node),
- Lookup::KnownAbsent => false,
- Lookup::Missing(_) => true,
- }
- })
- }
-
- /// Whether the path a route takes to `node` can actually be walked back.
- ///
- /// A region says where a change reaches; it says nothing about what the selector required on
- /// the way. Walking the path backwards from a candidate and demanding each intermediate
- /// compound's key at the node that step lands on is a necessary condition of the selector, so a
- /// candidate that fails it could not have matched before the change either.
- ///
- /// The frontier is bounded: past a handful of nodes the membership checks cost more than the
- /// rejections save, and the candidate stands.
- pub(super) fn path_meets_waypoints(
- &self,
- path: &[InverseStep],
- waypoints: &[DispatchKey],
- node: StyleNodeID,
- in_flux: Option<(StyleNodeID, DispatchKey)>,
- ) -> bool {
- const MAX_FRONTIER: usize = 32;
- if waypoints.len() != path.len() || path.is_empty() {
- return true;
- }
- // A shadow or sequence step anywhere in the path breaks the walk back: a node inside a
- // shadow tree has no ancestor chain that reaches its host, so a later ancestral step would
- // find nothing and reject a candidate that does match.
- if !path.iter().all(|step| {
- matches!(
- step,
- InverseStep::Descendants
- | InverseStep::Children
- | InverseStep::NextSibling
- | InverseStep::FollowingSiblings
- )
- }) {
- return true;
- }
- let mut frontier = [None; MAX_FRONTIER];
- frontier[0] = Some(node);
- let mut frontier_len = 1;
- for index in (1..path.len()).rev() {
- let mut next = [None; MAX_FRONTIER];
- let mut next_len = 0;
- let mut append = |candidate| {
- if next_len == MAX_FRONTIER {
- return false;
- }
- next[next_len] = Some(candidate);
- next_len += 1;
- true
- };
- for current in frontier[..frontier_len].iter().flatten().copied() {
- match path[index] {
- InverseStep::Descendants => {
- for ancestor in self.tree.ancestors(current) {
- if !append(ancestor) {
- return true;
- }
- }
- }
- InverseStep::Children => {
- if let Some(parent) = self.tree.parent(current)
- && !append(parent)
- {
- return true;
- }
- }
- InverseStep::NextSibling => {
- if let Some(previous) = self.tree.previous_element_sibling(current)
- && !append(previous)
- {
- return true;
- }
- }
- InverseStep::FollowingSiblings => {
- let mut sibling = self.tree.previous_element_sibling(current);
- while let Some(previous) = sibling {
- if !append(previous) {
- return true;
- }
- sibling = self.tree.previous_element_sibling(previous);
- }
- }
- _ => return true,
- }
- }
- let key = waypoints[index - 1];
- if key != DispatchKey::Universal {
- let mut kept = 0;
- for read in 0..next_len {
- let candidate = next[read].unwrap();
- if self.node_carries_any(std::slice::from_ref(&key), candidate, in_flux) {
- next[kept] = Some(candidate);
- kept += 1;
- }
- }
- next_len = kept;
- }
- if next_len == 0 {
- return false;
- }
- frontier = next;
- frontier_len = next_len;
- }
- true
- }
-
- /// Whether an entry is monotonic under a positive tree arrival.
- ///
- /// An arriving element is routed from the facts it publishes, so the new side alone decides
- /// unless a negation, `:empty`, or a positional test can turn another element's answer off.
- #[must_use]
- pub(super) fn entry_is_monotone_in_the_tree(&self, program: SelectorProgramID, entry: u32) -> bool {
- let compiled = self.programs.get(program);
- compiled
- .entries()
- .get(entry as usize)
- .is_some_and(|entry| entry.is_monotone_under_arrivals())
- }
-
- #[must_use]
- fn entry_is_monotone_in_the_tree_id(&self, entry: EntryID) -> bool {
- let (program, index) = self.programs.entry_location(entry);
- self.entry_is_monotone_in_the_tree(program, index)
- }
-
- #[must_use]
- pub(super) fn entry_can_use_before_sibling_relations(&self, program: SelectorProgramID, entry: u32) -> bool {
- let compiled = self.programs.get(program);
- compiled
- .entries()
- .get(entry as usize)
- .is_some_and(|entry| entry.can_use_before_sibling_relations() && entry.observes_sibling_relation())
- }
-
- #[must_use]
- fn entry_can_use_before_sibling_relations_id(&self, entry: EntryID) -> bool {
- let (program, index) = self.programs.entry_location(entry);
- self.entry_can_use_before_sibling_relations(program, index)
- }
-
- pub(super) fn candidate_changes_exact_tree(
- &mut self,
- node: StyleNodeID,
- program: SelectorProgramID,
- entry: u32,
- evaluation: ExactTreeEvaluation,
- ) -> ExactEntryResult {
- let mut covered = std::mem::take(&mut self.exact_covered_scratch);
- covered.clear();
- covered.push(node);
- let mut sibling_window = INITIAL_SIBLING_FACT_WINDOW;
- let old_matches = match evaluation {
- ExactTreeEvaluation::Arrival => None,
- ExactTreeEvaluation::MonotonicArrival
- | ExactTreeEvaluation::MonotonicDeparture
- | ExactTreeEvaluation::BeforeSiblingRelations => self
- .transaction_fact_view
- .as_ref()
- .filter(|view| view.retained_truth_available)
- .and_then(|_| self.retained_entry_matches(node, program, entry)),
- };
- let change = loop {
- let result = {
- let compiled = self.programs.get(program);
- let exact_entry = &compiled.entries()[entry as usize];
- evaluation.candidate_changes(
- &self.tree,
- self.facts.primary(),
- (compiled, exact_entry),
- node,
- old_matches,
- self.transaction_fact_view.as_ref(),
- &mut self.match_workspace,
- &self.counters,
- )
- };
- match result {
- Ok(change) => break change,
- Err(incomplete) => {
- if self
- .widen_fact_coverage(&mut covered, incomplete, &mut sibling_window)
- .is_err()
- {
- break Lookup::Missing(ExactEntryGap);
- }
- }
- }
- };
- self.exact_covered_scratch = covered;
- change
- }
-
- /// Whether one routed entry actually changes truth on this candidate.
- ///
- /// Transpose routing deliberately produces a bounded superset. When the transaction only moved
- /// local facts, both sides of the exact match program are available: the fact store is the
- /// new side and the journal retained the old values. This rejects redundant witnesses such as
- /// adding `.guard` above a `.target` that already had a nearer `.guard` ancestor.
- pub(super) fn candidate_changes_exact_entry(
- &mut self,
- node: StyleNodeID,
- site: &RoutingSite<'_>,
- ) -> ExactEntryResult {
- let Some((rule, entry_id)) = site.exact_entry else {
- return Lookup::Missing(ExactEntryGap);
- };
- let (program, entry) = self.programs.entry_location(entry_id);
- if self.transaction_fact_view.is_none() {
- return Lookup::Missing(ExactEntryGap);
- }
- {
- let compiled = self.programs.get(program);
- let sheet = self.program.rule_sheet(rule);
- if self.tree.tree_scope(node) != TreeScopeID::DOCUMENT
- || compiled.can_leave_its_scope()
- || !self
- .program
- .sheet_attachments(sheet)
- .iter()
- .any(|attachment| attachment.tree_scope == TreeScopeID::DOCUMENT)
- {
- return Lookup::Missing(ExactEntryGap);
- }
- if compiled.entries().get(entry as usize).is_none() {
- return Lookup::Missing(ExactEntryGap);
- }
- }
-
- if let Some(exact_tree_evaluation) = site.exact_tree_evaluation {
- return self.candidate_changes_exact_tree(node, program, entry, exact_tree_evaluation);
- }
-
- if !self
- .transaction_fact_view
- .as_ref()
- .is_some_and(|view| view.retained_truth_available)
- {
- return Lookup::Missing(ExactEntryGap);
- }
-
- let retained_old_matches = self
- .transaction_fact_view
- .as_ref()
- .filter(|view| view.retained_truth_available)
- .and_then(|_| self.retained_entry_matches(node, program, entry));
- let mut covered = std::mem::take(&mut self.exact_covered_scratch);
- covered.clear();
- covered.push(node);
- let mut sibling_window = INITIAL_SIBLING_FACT_WINDOW;
- let changed = loop {
- let result = {
- let resident_facts = self.facts.primary();
- let view = self
- .transaction_fact_view
- .as_ref()
- .expect("exact evaluation has a transaction fact view");
- let compiled = self.programs.get(program);
- let exact_entry = &compiled.entries()[entry as usize];
- let new_matches = MatchEvaluator::new(&self.tree, resident_facts)
- .with_transaction_fact_view(view, TransactionFactSide::After)
- .matches_entry_for_program(program, compiled, exact_entry, node, &self.counters);
- let old_matches = match retained_old_matches {
- Some(old_matches) => Ok(old_matches),
- None => MatchEvaluator::new(&self.tree, resident_facts)
- .with_transaction_fact_view(view, TransactionFactSide::Before)
- .matches_entry_for_program(program, compiled, exact_entry, node, &self.counters),
- };
- (old_matches, new_matches)
- };
- match result {
- (Ok(old_matches), Ok(new_matches)) if old_matches != new_matches => {
- break Lookup::Known(if new_matches {
- SetChange::Added
- } else {
- SetChange::Removed
- });
- }
- (Ok(_), Ok(_)) => break Lookup::KnownAbsent,
- (Err(incomplete), _) | (_, Err(incomplete)) => {
- if self
- .widen_fact_coverage(&mut covered, incomplete, &mut sibling_window)
- .is_err()
- {
- break Lookup::Missing(ExactEntryGap);
- }
- }
- }
- };
- self.exact_covered_scratch = covered;
- changed
- }
-
- #[must_use]
- pub(super) fn exact_batch_is_available(&self, routed_regions: &[ImpactRegion], site: &RoutingSite<'_>) -> bool {
- site.exact_entry.is_some()
- && (site.exact_tree_evaluation.is_some()
- || self
- .transaction_fact_view
- .as_ref()
- .is_some_and(|view| view.retained_truth_available))
- && !routed_regions
- .iter()
- .any(|region| matches!(region, ImpactRegion::Document | ImpactRegion::TreeScope(_)))
- }
-
- pub(super) fn compile_region_batch(
- &mut self,
- routed_regions: &[ImpactRegion],
- plan: &ImpactRegions,
- workspace: Option<&mut ImpactPlanningWorkspace>,
- ) -> Arc<ImpactRegionBatch> {
- if let Some(workspace) = workspace {
- if let Some(batch) = workspace.batches.get(routed_regions) {
- return Arc::clone(batch);
- }
-
- let batch = Arc::new(plan.compile_union(routed_regions, &self.tree, None));
- self.record_compiled_region_batch(&batch);
- workspace.insert_batch(routed_regions, Arc::clone(&batch));
-
- return batch;
- }
-
- let batch = Arc::new(plan.compile_union(routed_regions, &self.tree, None));
- self.record_compiled_region_batch(&batch);
- batch
- }
-
- pub(super) fn record_compiled_region_batch(&mut self, batch: &ImpactRegionBatch) {
- if let Some(intervals) = batch.interval_count() {
- self.counters.add(Counter::ExactRegionBatchIntervals, intervals as u64);
- }
- self.counters
- .add(Counter::ExactRegionBatchNodes, batch.node_count() as u64);
- }
-
- /// Run one exact candidate pass over the union of several transpose regions.
- pub(super) fn add_exact_batch_regions(
- &mut self,
- routed_regions: &[ImpactRegion],
- site: &RoutingSite<'_>,
- regions: &mut ImpactRegions,
- workspace: Option<&mut ImpactPlanningWorkspace>,
- compiled_batch: Option<Arc<ImpactRegionBatch>>,
- ) -> bool {
- if !self.exact_batch_is_available(routed_regions, site) {
- return false;
- }
-
- let batch = compiled_batch.unwrap_or_else(|| self.compile_region_batch(routed_regions, regions, workspace));
- let mut candidates = Vec::new();
- let attributed_rule = site.attribution();
- regions.for_each_batch(&batch, |candidate| {
- // A node the entry's subject cannot name matches it on neither side, so it has no
- // delta to contribute - whether or not an earlier route already planned it. Filtering
- // before the already-planned check keeps every entry whose batch merely contains a
- // planned node from queueing a full exact evaluation of that node later.
- if !(self.node_carries_any(site.subject, candidate, site.in_flux)
- && self.node_carries_all(site.subject_required, candidate, site.in_flux)
- && self.path_meets_waypoints(site.path, site.waypoints, candidate, site.in_flux))
- {
- return;
- }
- if regions.contains_node(candidate) {
- self.record_already_planned_selector_truth(candidate, site);
- return;
- }
- candidates.push(candidate);
- });
-
- let (rule, entry_id) = site.exact_entry.unwrap();
- let (program, entry) = self.programs.entry_location(entry_id);
- let sheet = self.program.rule_sheet(rule);
- let compiled = self.programs.get(program);
- if compiled.can_leave_its_scope()
- || !self
- .program
- .sheet_attachments(sheet)
- .iter()
- .any(|attachment| attachment.tree_scope == TreeScopeID::DOCUMENT)
- || compiled.entries().get(entry as usize).is_none()
- {
- for candidate in candidates {
- self.record_selector_truth_refresh(candidate, attributed_rule);
- regions.add(ImpactRegion::Node(candidate));
- }
-
- return true;
- }
-
- candidates.retain(|&candidate| {
- if self.tree.tree_scope(candidate) == TreeScopeID::DOCUMENT {
- true
- } else {
- self.record_selector_truth_refresh(candidate, attributed_rule);
- regions.add(ImpactRegion::Node(candidate));
- false
- }
- });
- if candidates.is_empty() {
- return true;
- }
-
- for candidate in candidates {
- if let Some(exact_tree_evaluation) = site.exact_tree_evaluation {
- let change = self.candidate_changes_exact_tree(candidate, program, entry, exact_tree_evaluation);
- if exact_entry_changed(change) {
- self.record_exact_selector_truth_change(candidate, site, change);
- regions.add(ImpactRegion::Node(candidate));
- }
- continue;
- }
-
- let change = self.candidate_changes_exact_entry(candidate, site);
- if exact_entry_changed(change) {
- self.record_exact_selector_truth_change(candidate, site, change);
- regions.add(ImpactRegion::Node(candidate));
- }
- }
-
- true
- }
-
- /// Narrow the union of all regions reached through one transpose route.
- ///
- /// Transaction impact is the union of every normalized input's route. Keeping that union
- /// grouped by route means a common subject posting is enumerated once, and a broad exact
- /// plan streams overlapping regions once, regardless of how many inputs reached the entry.
- pub(super) fn add_narrowed_regions_with_workspace(
- &mut self,
- routed_regions: &[ImpactRegion],
- site: &RoutingSite<'_>,
- regions: &mut ImpactRegions,
- workspace: &mut ImpactPlanningWorkspace,
- ) {
- if routed_regions.is_empty() {
- return;
- }
- if site.position.bound != u32::MAX {
- let mut expanded_children = false;
- let mut has_other_regions = false;
- for &region in routed_regions {
- match region {
- ImpactRegion::Children(_) => {
- self.add_position_bounded_region(region, site, regions);
- expanded_children = true;
- }
- _ => has_other_regions = true,
- }
- }
- if !has_other_regions {
- return;
- }
- if expanded_children {
- for region in routed_regions
- .iter()
- .filter(|region| !matches!(region, ImpactRegion::Children(_)))
- {
- self.add_narrowed_regions_with_workspace(std::slice::from_ref(region), site, regions, workspace);
- }
- return;
- }
- }
-
- let has_usable_subject = !site.subject.is_empty() && site.subject.iter().all(|key| key.has_selector_posting());
- if !self.selector_truth_changes_active
- && has_usable_subject
- && site
- .subject
- .iter()
- .all(|&key| !matches!(self.facts.postings().lookup(key), Lookup::Missing(_)))
- && routed_regions
- .iter()
- .all(|region| matches!(region, ImpactRegion::Node(_)))
- {
- self.add_narrowed_node_regions(routed_regions, site, regions);
- return;
- }
- let cardinality = if has_usable_subject {
- site.subject.iter().copied().try_fold(0_usize, |total, posting| {
- match self.facts.postings().lookup(posting) {
- Lookup::Known(posting) => Some(total.saturating_add(posting.len())),
- Lookup::KnownAbsent => Some(total),
- Lookup::Missing(_) => None,
- }
- })
- } else {
- None
- };
- // A tiny dense posting is already the cheaper side of the join. Prove each of its nodes
- // against the named regions directly instead of materializing every node in those regions
- // merely to discover that the posting was tiny. Larger sources still compile the union so
- // the selective-versus-batch choice has an exact region cardinality.
- let use_direct_region_membership = cardinality.is_some_and(|cardinality| cardinality <= SMALL_CANDIDATE_SOURCE);
- let compiled_regions = if use_direct_region_membership {
- None
- } else {
- let compiled_regions = self.compile_region_batch(routed_regions, regions, Some(workspace));
- let region_nodes = compiled_regions.node_count();
- match choose_plan(
- region_nodes,
- cardinality,
- self.exact_batch_is_available(routed_regions, site),
- ) {
- Plan::ExactBatch { .. } => {
- let executed = self.add_exact_batch_regions(
- routed_regions,
- site,
- regions,
- Some(workspace),
- Some(compiled_regions),
- );
- if executed {
- return;
- }
- unreachable!("an available exact batch plan must execute");
- }
- Plan::Conservative => {
- for &region in routed_regions {
- if let ImpactRegion::Node(node) = region {
- self.record_selector_truth_refresh(node, site.attribution());
- }
- self.add_region_for_site(region, site, regions);
- }
- return;
- }
- Plan::Selective { .. } => {}
- }
- Some(compiled_regions)
- };
-
- let mut candidates = Vec::new();
- let mut pruned_nodes = Vec::new();
- for &posting in site.subject {
- let Ok((reused, copied, inspected, _)) = workspace.extend_remaining_posting(
- posting,
- self.facts.postings(),
- regions,
- &mut candidates,
- self.selector_truth_changes_active.then_some(&mut pruned_nodes),
- ) else {
- unreachable!("the cardinality lookup proved every selective posting present")
- };
-
- self.counters.bump(match reused {
- true => Counter::RemainingPostingReuses,
- false => Counter::RemainingPostingBuilds,
- });
- self.counters.add(Counter::RemainingPostingRowsCopied, copied as u64);
- self.counters
- .add(Counter::RemainingPostingRowsInspected, inspected as u64);
- }
- let mut already_planned_moved_nodes = Vec::new();
- let moved_features = &self
- .transaction_fact_view
- .as_ref()
- .expect("routing requires a transaction fact view")
- .moved_features;
- for &key in site.subject {
- moved_features.all_nodes_with_key(key, |node| {
- match regions.contains_node(node) {
- true => already_planned_moved_nodes.push(node),
- false => candidates.push(node),
- }
- true
- });
- }
- already_planned_moved_nodes.sort_unstable();
- already_planned_moved_nodes.dedup();
- // A node the posting dropped as already planned, and a moved node already in the plan,
- // still need this route's contribution reflected in their retained-answer patch. When
- // the route names its exact rule, one attribution of its extent carries that for all of
- // them symbolically instead of materializing the (node, rule) product; the routes whose
- // input this is were measured pushing hundreds of thousands of such rows per flush.
- pruned_nodes.sort_unstable();
- pruned_nodes.dedup();
- let already_planned_candidates = (already_planned_moved_nodes.len() + pruned_nodes.len()) as u64;
- if already_planned_candidates > 0 && self.selector_truth_changes_active {
- match site.attribution() {
- Some(key) => {
- for &region in routed_regions {
- regions.attribute_extent(region, key);
- }
- }
- None => {
- for &node in &already_planned_moved_nodes {
- self.record_already_planned_selector_truth(node, site);
- }
- for &pruned in &pruned_nodes {
- self.record_already_planned_selector_truth(pruned, site);
- }
- }
- }
- }
- candidates.sort_unstable();
- candidates.dedup();
-
- for candidate in candidates {
- let candidate_is_in_routed_regions = compiled_regions.as_ref().map_or_else(
- || regions.union_contains_node(routed_regions, candidate, &self.tree),
- |compiled_regions| regions.batch_contains_node(compiled_regions, candidate),
- );
- if candidate_is_in_routed_regions
- && self.node_carries_all(site.subject_required, candidate, site.in_flux)
- && self.path_meets_waypoints(site.path, site.waypoints, candidate, site.in_flux)
- {
- let change = self.candidate_changes_exact_entry(candidate, site);
- if exact_entry_changed(change) {
- self.record_exact_selector_truth_change(candidate, site, change);
- regions.add(ImpactRegion::Node(candidate));
- }
- }
- }
- }
-
- /// Narrow a union of exact-node regions from the nodes themselves.
- ///
- /// A subject posting can contain many nodes while this route's region contains only one. The
- /// local fact rows answer membership directly, so walking and copying the whole posting merely
- /// to intersect it back down to those named nodes reverses the cheaper side of the join.
- fn add_narrowed_node_regions(
- &mut self,
- routed_regions: &[ImpactRegion],
- site: &RoutingSite<'_>,
- regions: &mut ImpactRegions,
- ) {
- let mut candidates: Vec<_> = routed_regions
- .iter()
- .filter_map(|region| match region {
- ImpactRegion::Node(node) => Some(*node),
- _ => None,
- })
- .collect();
- candidates.sort_unstable();
- candidates.dedup();
-
- let mut already_planned = Vec::new();
-
- for candidate in candidates {
- if !self.node_carries_any(site.subject, candidate, site.in_flux) {
- continue;
- }
- if regions.contains_node(candidate) {
- already_planned.push(candidate);
- continue;
- }
- if self.node_carries_all(site.subject_required, candidate, site.in_flux)
- && self.path_meets_waypoints(site.path, site.waypoints, candidate, site.in_flux)
- {
- let change = self.candidate_changes_exact_entry(candidate, site);
- if exact_entry_changed(change) {
- self.record_exact_selector_truth_change(candidate, site, change);
- regions.add(ImpactRegion::Node(candidate));
- }
- }
- }
-
- if already_planned.is_empty() || !self.selector_truth_changes_active {
- return;
- }
- match site.attribution() {
- Some(key) => {
- for &region in routed_regions {
- regions.attribute_extent(region, key);
- }
- }
- None => {
- for node in already_planned {
- self.record_already_planned_selector_truth(node, site);
- }
- }
- }
- }
-
- /// The prefix part of the transition this transaction is routing, which every caller below
- /// has already established.
- fn transaction_prefix(&self) -> &PrefixFactTransition {
- self.transaction_fact_view
- .as_ref()
- .and_then(|transition| transition.prefix.as_ref())
- .expect("a prefix transition must be present")
- }
-
- /// Finish local routes after all normalized inputs have contributed their regions.
- ///
- /// Ordinary selector chains over all four axes share one top-down automaton. When every
- /// pending route is answerable by that automaton, compare its old and new states once from
- /// every changed root. A node whose local matches differ is dirty; descendants need
- /// inspection only while the continuation inherited by children differs, and later siblings
- /// only while the rightward state entering them differs. Successfully compared routes are
- /// removed from the route-by-route planner below.
- #[must_use]
- pub(super) fn route_is_prefix_convergence_eligible(
- &self,
- routing: &RoutingRegistry,
- dispatch: &RuleDispatch,
- route: RouteID,
- ) -> bool {
- routing.entry_has_prefix_chain(route)
- && routing.entry_prefix_chain_has_only_local_facts(route)
- && self
- .program
- .sheet_origin(self.program.rule_sheet(routing.rule_of(route)))
- == CascadeOrigin::Author
- && dispatch.prefixes().contains_entry(routing.entry_of(route))
- }
-
- #[allow(clippy::too_many_arguments)]
- pub(super) fn add_prefix_convergence_regions(
- &mut self,
- pending: &mut PendingRoutes,
- regions: &mut ImpactRegions,
- retained_winners_are_current: bool,
- transaction: &StyleTransaction,
- sequences: &SequenceChanges,
- pending_prefix_producers: &[PendingPrefixProducer],
- ) -> PrefixConvergenceOutcome {
- let Some((root, tree_relations_changed)) = self.transaction_fact_view.as_ref().and_then(|transition| {
- transition
- .prefix
- .as_ref()
- .map(|prefix| (transition.root, prefix.tree_relations_changed))
- }) else {
- return PrefixConvergenceOutcome::default();
- };
- // Only the root set is edited below, so the departures and the sibling frontier stay
- // borrowed from the transition for as long as each use needs them.
- let mut pending_nodes = self.transaction_prefix().roots.clone();
- let routing = Arc::clone(&self.routing);
- let (scope_program, dispatch) = self.prepare_scope_program(TreeScopeID::DOCUMENT);
- if dispatch.prefixes().is_empty() {
- return PrefixConvergenceOutcome::default();
- }
- let retained_relation = match self.prefix_caches.borrow_mut().states.lookup_mut(scope_program) {
- Lookup::Known(states) => states.relation.take(),
- _ => None,
- };
- if let Some(mut relation) = retained_relation {
- let facts = self.facts.primary();
- let view = self.transaction_fact_view.as_ref().unwrap();
- let mut workspace = MatchScratch::default();
- let mut old_workspace = MatchScratch::default();
- let mut evaluator = MatchEvaluator::new(&self.tree, facts)
- .with_transaction_fact_view(view, TransactionFactSide::After)
- .with_match_workspace(&mut workspace, MatchEvaluationSide::Current);
- let mut old_evaluator = MatchEvaluator::new(&self.tree, facts)
- .with_transaction_fact_view(view, TransactionFactSide::Before)
- .with_match_workspace(&mut old_workspace, MatchEvaluationSide::OldTree);
- let mut evaluation = PrefixEvaluation::new(
- dispatch.prefixes(),
- &self.tree,
- facts,
- &self.programs,
- &mut evaluator,
- None,
- None,
- );
- let mut old_evaluation = PrefixEvaluation::new(
- dispatch.prefixes(),
- &self.tree,
- facts,
- &self.programs,
- &mut old_evaluator,
- None,
- None,
- );
- {
- // A retained relation answers the whole pass, so the root set is free to carry
- // the geometry arrivals it collects here.
- let changed = &mut pending_nodes;
- if tree_relations_changed {
- let mut geometry_nodes: Vec<_> = transaction
- .inputs
- .iter()
- .filter_map(|input| {
- if let InputKey::TreeRelations(node) = input.key {
- Some(node)
- } else {
- None
- }
- })
- .collect();
- geometry_nodes.extend_from_slice(&self.transaction_prefix().sibling_frontier);
- geometry_nodes.sort_unstable();
- geometry_nodes.dedup();
- changed.extend(relation.update_geometry(
- dispatch.prefixes(),
- &mut evaluation,
- &geometry_nodes,
- &self.counters,
- ));
- }
- changed.sort_unstable();
- changed.dedup();
- relation.update(
- dispatch.prefixes(),
- &mut evaluation,
- &mut old_evaluation,
- changed,
- &self.counters,
- );
- }
- let mut eligible: Vec<_> = pending
- .keys()
- .filter(|key| self.route_is_prefix_convergence_eligible(&routing, &dispatch, key.route))
- .collect();
- eligible.sort_unstable();
- let mut changed_routing_keys = Vec::new();
- if retained_winners_are_current && !relation.changed_answers.is_empty() {
- for input in &transaction.inputs {
- changed_routing_keys.extend(routing_keys_for_input(input));
- if let InputKey::LocalFeature(_, LocalFeatureKey::Attribute(name)) = input.key {
- changed_routing_keys
- .extend(self.facts.attribute_name_keys(name).map(RoutingKey::AttributeName));
- }
- }
- changed_routing_keys.sort_unstable();
- changed_routing_keys.dedup();
- }
- let mut cascade_relevance: HashMap<EntryID, Option<bool>> = HashMap::default();
-
- let mut cascade_stops = 0;
- for (node, old, new) in &relation.changed_answers {
- let mut has_active_change = false;
- let mut may_change_cascade = false;
- for difference in merge_sorted_by(old, new, Ord::cmp) {
- let entry = match difference {
- SortedMergeEntry::Left(&entry) | SortedMergeEntry::Right(&entry) => entry,
- SortedMergeEntry::Both(_, _) => continue,
- };
-
- let relevance = *cascade_relevance.entry(entry).or_insert_with(|| {
- let mut active = false;
- for candidate in dispatch.entries_for_identity(entry) {
- if !self.program.rule_can_decide(candidate.rule) {
- continue;
- }
- active = true;
- if !retained_winners_are_current
- || !self.prefix_route_cannot_change_any_retained_winner(
- candidate.rule,
- candidate.program,
- candidate.entry,
- &changed_routing_keys,
- )
- {
- return Some(true);
- }
- }
- if active {
- cascade_stops += 1;
- Some(false)
- } else {
- None
- }
- });
-
- has_active_change |= relevance.is_some();
- may_change_cascade |= relevance == Some(true);
- if may_change_cascade {
- break;
- }
- }
- if !has_active_change {
- continue;
- }
- // A record rolled back below a substituted revert keyword holds a declaration its
- // winners do not name, which a losing rule may be.
- may_change_cascade |= self.record_rolls_back_substitution(*node);
- record_match_set_difference(
- &mut self.selector_truth_changes,
- self.selector_truth_changes_active,
- *node,
- old,
- new,
- &dispatch,
- &self.program,
- );
- if may_change_cascade {
- regions.add(ImpactRegion::Node(*node));
- } else if self.selector_truth_changes_active {
- // Keep prefix truth current even when its rule cannot win. Retire an
- // unplanned node's exact answer, or repair it if another route plans it.
- self.selector_truth_changes.refreshes.push(SelectorTruthRefresh {
- node: *node,
- rule: None,
- });
- }
- }
- self.counters.add(Counter::PrefixRelationCascadeStops, cascade_stops);
-
- let mut caches = self.prefix_caches.borrow_mut();
- let states = caches.states.prepare_program(scope_program);
- relation.install_answers(states);
- for &node in &self.transaction_prefix().departures {
- states.forget_transition(node);
- }
- states.relation = Some(relation);
- self.counters.bump(Counter::PrefixConvergencePasses);
- caches.states.mark_full();
- caches.states.mark_current();
-
- // The relation answers for the document tree alone. A route reaching into another tree
- // scope keeps those regions for its own program to route.
- let mut released_route_bytes = 0;
- pending.retain(|key, routed_regions| {
- if eligible.binary_search(&key).is_err() {
- return true;
- }
- routed_regions.retain(|region| region.lies_outside_document_scope(&self.tree));
- if !routed_regions.is_empty() {
- return true;
- }
- released_route_bytes += (routed_regions.capacity() * size_of::<ImpactRegion>()) as u64;
- false
- });
-
- return PrefixConvergenceOutcome {
- sibling_routes_are_covered: pending.is_empty()
- && tree_relations_changed
- && dispatch.prefixes().has_sibling_steps(),
- positional_routes_are_covered: pending.is_empty()
- && tree_relations_changed
- && !dispatch.prefixes().positional_tests().is_empty(),
- };
- }
- let mut local_fact_changes = pending_nodes.clone();
- local_fact_changes.sort_unstable();
- local_fact_changes.dedup();
- let automaton_has_sibling_steps = dispatch.prefixes().has_sibling_steps();
- // A tree delta moves the rightward context entering the nodes that follow it, so a
- // sibling-bearing automaton walks the frontier those deltas name: the retained walk
- // compares each frontier node's cached transition against one computed from the current
- // topology and propagates right and down until both outputs converge.
- if automaton_has_sibling_steps && tree_relations_changed {
- pending_nodes.extend_from_slice(&self.transaction_prefix().sibling_frontier);
- pending_nodes.sort_unstable();
- pending_nodes.dedup();
- }
- // Structural truth is per index or per child list, not per fact cohort: one tree
- // mutation moves the an+b answers of untouched siblings on both sides of the mutation
- // point and its parent's emptiness, with no local fact change and no rightward state
- // to carry the flip. When the automaton holds structural tests, the walk therefore
- // re-compares every remaining child of every parent a tree delta touched, plus that
- // parent itself for emptiness. An of-type answer additionally reads sibling tag facts,
- // so a tag change re-compares the changed node's whole sequence too.
- let positional_tests = dispatch.prefixes().positional_tests();
- // The parents whose child sequences this flush touched: only their children can have
- // moved positional truth, so every other node's retained positional bits still hold.
- let mut positional_touched_parents: Vec<StyleNodeID> = Vec::new();
- if !positional_tests.is_empty() {
- let has_of_type_tests = positional_tests
- .iter()
- .any(|&(_, test)| matches!(test, selector::PrefixStructuralTest::Nth(nth) if nth.of_type));
- let automaton_has_empty_tests = positional_tests
- .iter()
- .any(|&(_, test)| test == selector::PrefixStructuralTest::Empty);
- let mut touched_parents: Vec<StyleNodeID> = Vec::new();
- let mut touch = |tree: &StyleNodeTree, parent: Option<StyleNodeID>| {
- if let Some(parent) = parent
- && tree.is_live(parent)
- && tree.tree_scope(parent) == TreeScopeID::DOCUMENT
- {
- touched_parents.push(parent);
- }
- };
- for input in &transaction.inputs {
- match input.key {
- InputKey::TreeRelations(_) => {
- for value in [input.old, input.new] {
- let InputValue::TreeRelations(Some(relations)) = value else {
- continue;
- };
- touch(&self.tree, relations.parent);
- }
- }
- InputKey::LocalFeature(node, LocalFeatureKey::TagName | LocalFeatureKey::FoldedTagName)
- if has_of_type_tests =>
- {
- touch(&self.tree, self.tree.parent(node));
- }
- _ => {}
- }
- }
- touched_parents.sort_unstable();
- touched_parents.dedup();
- if !touched_parents.is_empty() {
- if automaton_has_empty_tests {
- pending_nodes.extend(touched_parents.iter().copied());
- }
- for &parent in &touched_parents {
- let child_count = self.tree.children(parent).count();
- let before_geometry = self
- .transaction_fact_view
- .as_ref()
- .filter(|view| view.before_sibling_relations_available);
- let sequence_change = sequences.get(parent);
- let can_narrow = before_geometry.is_some() && sequence_change.is_some();
- for (index, child) in self.tree.children(parent).enumerate() {
- let plain_truth_changed = can_narrow
- && positional_tests.iter().any(|&(_, test)| {
- let selector::PrefixStructuralTest::Nth(nth) = test else {
- return false;
- };
- if nth.of_type {
- return false;
- }
- let new_count = match nth.from_end {
- true => child_count - index,
- false => index + 1,
- } as i64;
- let new_matches = nth.matches_count(new_count);
- let old_matches = before_geometry
- .and_then(|view| view.before_sibling_geometry.sibling_positions(child))
- .is_some_and(|old| {
- let old_count = match nth.from_end {
- true => old.from_end,
- false => old.from_start,
- };
- nth.matches_count(i64::from(old_count))
- });
- old_matches != new_matches
- });
- let of_type_may_have_changed = can_narrow
- && has_of_type_tests
- && sequence_change.is_some_and(|change| {
- if change.has_unidentified_type {
- return true;
- }
- let tag = self.facts.tag_of_node(child);
- tag.is_none() || change.changed_types.contains(&(tag, self.facts.namespace_of(child)))
- });
- if !can_narrow || plain_truth_changed || of_type_may_have_changed {
- pending_nodes.push(child);
- }
- }
- }
- pending_nodes.sort_unstable();
- pending_nodes.dedup();
- }
- positional_touched_parents = touched_parents;
- }
-
- // No fact root moved: the cache's own book-keeping is the whole maintenance. Departed
- // transitions are forgotten, an arrival simply has no transition until something asks,
- // and cross-parent moves already refused the transition above. Pure tree flushes used to
- // discard the cache here, which re-cooled every later plan into coarse arrivals.
- if pending_nodes.is_empty() {
- // Currency can only be claimed for inputs the prefix book-keeping accounts for. A
- // change in another tree scope contributes no roots here yet still ages the caches
- // serving that scope, and a non-node input reshapes the program itself.
- let all_inputs_accounted = transaction.inputs.iter().all(|input| {
- input
- .key
- .style_node()
- .is_some_and(|node| self.tree.tree_scope(node) == TreeScopeID::DOCUMENT)
- });
- if !all_inputs_accounted {
- return PrefixConvergenceOutcome::default();
- }
- let prefix_caches = std::sync::Arc::clone(&self.prefix_caches);
- let mut caches = prefix_caches.borrow_mut();
- if !caches.states.is_retained() {
- return PrefixConvergenceOutcome::default();
- }
- for &node in &self.transaction_prefix().departures {
- caches.states.forget_transition(scope_program, node);
- }
- // With positional tests registered, an empty pending set on a tree flush means
- // every touched sequence lost its last member, so there is no positional truth
- // left to move and coverage holds vacuously.
- return PrefixConvergenceOutcome {
- sibling_routes_are_covered: false,
- positional_routes_are_covered: tree_relations_changed
- && !dispatch.prefixes().positional_tests().is_empty(),
- };
- }
- if !pending_nodes
- .iter()
- .all(|&node| regions.region_contains_node(ImpactRegion::Subtree(root), node, &self.tree))
- {
- return PrefixConvergenceOutcome::default();
- }
-
- if retained_winners_are_current {
- let mut changed_routing_keys = Vec::new();
- for input in &transaction.inputs {
- changed_routing_keys.extend(routing_keys_for_input(input));
- if let InputKey::LocalFeature(_, LocalFeatureKey::Attribute(name)) = input.key {
- changed_routing_keys.extend(self.facts.attribute_name_keys(name).map(RoutingKey::AttributeName));
- }
- }
- changed_routing_keys.sort_unstable();
- changed_routing_keys.dedup();
-
- let before = pending.len();
- let mut released_route_bytes = 0;
- let mut inexact_answer_regions = Vec::new();
- pending.retain(|key, routed_regions| {
- let route = routing.route(key.route);
- let (program, entry) = self.programs.entry_location(route.entry);
- let keep = !self.prefix_route_cannot_change_any_retained_winner(
- routing.rule_of(key.route),
- program,
- entry,
- &changed_routing_keys,
- );
- if !keep {
- released_route_bytes += (routed_regions.capacity() * size_of::<ImpactRegion>()) as u64;
- inexact_answer_regions.extend(routed_regions.iter().copied());
- }
- keep
- });
-
- if self.selector_truth_changes_active {
- let refreshes = &mut self.selector_truth_changes.refreshes;
- regions.for_each_union(&inexact_answer_regions, &self.tree, Some(root), |node| {
- refreshes.push(SelectorTruthRefresh { node, rule: None });
- });
- }
-
- self.counters.add(
- Counter::SelectorRoutesRejectedByCascade,
- before.saturating_sub(pending.len()) as u64,
- );
- if pending.is_empty() {
- return PrefixConvergenceOutcome::default();
- }
- }
-
- // The pass consumes the routes the automaton can answer and leaves the rest pending: a
- // mixed transaction no longer forfeits the retained cache, it just narrows its other
- // routes the ordinary way.
- let mut eligible_keys: Vec<PendingRoute> = pending
- .keys()
- .filter(|key| self.route_is_prefix_convergence_eligible(&routing, &dispatch, key.route))
- .collect();
- eligible_keys.sort_unstable();
- self.counters.add(Counter::PendingSelectorRoutes, pending.len() as u64);
- self.counters
- .add(Counter::PrefixEligibleRoutes, eligible_keys.len() as u64);
- // Consumption still asks for the whole pending set: at current transition unit cost a
- // maintenance walk on a mixed flush loses to the generic narrowing it would subsidize.
- // Partial consumption was measured again after positional admission and lost about a
- // fifth of the whole bench, spread across every suite, so widening admission until
- // whole flushes qualify is the lever, not walking to subsidize a subset.
- let consuming = eligible_keys.len() == pending.len();
- if !consuming {
- return PrefixConvergenceOutcome::default();
- }
-
- // A retained prefix pass is a top-down walk until its continuation converges. When every
- // route has a small indexed subject set, exact selective routing can ask that union directly
- // instead of visiting an otherwise unchanged document to reach it. A warm retained cache
- // changes that arithmetic: its maintenance walk is bounded by the change and keeping it
- // current is what keeps every later plan narrow, so it is never bypassed away.
- const PREFIX_CONVERGENCE_SELECTIVE_MINIMUM_DOCUMENT: u32 = 1024;
- const PREFIX_CONVERGENCE_SELECTIVE_RATIO: usize = 16;
- let mut subject_candidates = HashSet::default();
- let mut subjects_are_indexed = true;
- for key in pending.keys() {
- let subject = routing.subject_dispatch_of(key.route);
- if subject.is_empty() {
- subjects_are_indexed = false;
- break;
- }
- for dispatch in subject {
- if !dispatch.has_selector_posting() {
- subjects_are_indexed = false;
- break;
- }
- let candidates = match self.facts.postings().lookup(*dispatch) {
- Lookup::Known(posting) => posting.candidates(),
- Lookup::KnownAbsent => continue,
- Lookup::Missing(_) => {
- subjects_are_indexed = false;
- break;
- }
- };
- for candidate in candidates {
- subject_candidates.insert(candidate);
- if subject_candidates.len() > SMALL_CANDIDATE_SOURCE {
- break;
- }
- }
- if !subjects_are_indexed || subject_candidates.len() > SMALL_CANDIDATE_SOURCE {
- break;
- }
- }
- if !subjects_are_indexed || subject_candidates.len() > SMALL_CANDIDATE_SOURCE {
- break;
- }
- }
- if !self.prefix_caches.borrow().states.is_retained()
- && self.tree.connected_element_count() >= PREFIX_CONVERGENCE_SELECTIVE_MINIMUM_DOCUMENT
- && subjects_are_indexed
- && subject_candidates.len() <= SMALL_CANDIDATE_SOURCE
- && subject_candidates
- .len()
- .saturating_mul(PREFIX_CONVERGENCE_SELECTIVE_RATIO)
- < self.tree.connected_element_count() as usize
- {
- self.counters.bump(Counter::PrefixConvergenceBypasses);
- return PrefixConvergenceOutcome::default();
- }
-
- let selection = dispatch.prefixes().select_entries(
- eligible_keys.iter().map(|key| {
- let route = routing.route(key.route);
- route.entry
- }),
- self.programs.entry_capacity(),
- );
- let had_retained_prefix_states = self.prefix_caches.borrow().states.is_retained();
- let mut local_prefix_producers: HashMap<StyleNodeID, Vec<PrefixProducer>> = HashMap::default();
- if had_retained_prefix_states {
- for producer in pending_prefix_producers {
- local_prefix_producers
- .entry(producer.node)
- .or_default()
- .push(producer.producer);
- }
- for producers in local_prefix_producers.values_mut() {
- producers.sort_unstable_by_key(|producer| producer.step);
- producers.dedup_by_key(|producer| producer.step);
- }
- }
-
- if had_retained_prefix_states {
- let prefix_caches = std::sync::Arc::clone(&self.prefix_caches);
- let mut caches = prefix_caches.borrow_mut();
- let PrefixCaches {
- states: retained,
- answers,
- } = &mut *caches;
- let cache_is_batch_sparse = retained.is_sparse();
- retained.make_scratch();
- retained.prepare_to_mutate();
- // NB: An incomplete cache under departures used to refuse reuse outright, which
- // released the cache and stranded every later flush on the from-scratch compare
- // loop, since nothing reseeds the retained states between full batches. The walk
- // already forgets departed transitions and routes every unprovable comparison
- // through its gap and abandon exits, so reuse is safe and keeps the automaton
- // warm across departure-bearing flushes.
- let can_reuse = retained.lookup_mut(scope_program).sparse().is_ok();
- if can_reuse {
- let view = self
- .transaction_fact_view
- .as_ref()
- .expect("prefix planning has a transaction fact view");
- let resident_facts = self.facts.primary();
- let mut prefix_context = PrefixTransitionContext::new_composite(
- retained
- .lookup_mut(scope_program)
- .sparse()
- .expect("prepared prefix program"),
- resident_facts,
- &local_fact_changes,
- );
- self.counters.bump(Counter::PrefixTransitionCacheHits);
- let nodes_in_preorder = regions.sort_nodes_for_top_down_walk(&mut pending_nodes, &self.tree);
- if automaton_has_sibling_steps && !nodes_in_preorder {
- retained.release();
- answers.release(&mut self.match_answers);
- return PrefixConvergenceOutcome::default();
- }
- let mut visited = Vec::new();
- let mut changed_nodes = Vec::new();
- let mut prefix_delta_arena = PrefixDeltaArena::default();
- let mut positional_workspace = MatchScratch::default();
- let mut old_positional_workspace = MatchScratch::default();
- let mut old_evaluator = MatchEvaluator::new(&self.tree, resident_facts)
- .with_transaction_fact_view(view, TransactionFactSide::Before)
- .with_match_workspace(&mut old_positional_workspace, MatchEvaluationSide::OldTree);
- let mut old_evaluation = PrefixEvaluation::new(
- dispatch.prefixes(),
- &self.tree,
- resident_facts,
- &self.programs,
- &mut old_evaluator,
- None,
- None,
- );
- let mut new_evaluator = MatchEvaluator::new(&self.tree, resident_facts)
- .with_transaction_fact_view(view, TransactionFactSide::After)
- .with_match_workspace(&mut positional_workspace, MatchEvaluationSide::Current);
- let mut new_evaluation = PrefixEvaluation::new(
- dispatch.prefixes(),
- &self.tree,
- resident_facts,
- &self.programs,
- &mut new_evaluator,
- None,
- None,
- );
-
- let mut complete = true;
- let mut prefix_completion_budget = PREFIX_TRANSITION_CACHE_COMPLETION_BUDGET;
- let mut sibling_walk_abandoned = false;
- {
- let states = match retained.lookup_mut(scope_program) {
- Lookup::Known(states) => states,
- Lookup::KnownAbsent | Lookup::Missing(_) => {
- unreachable!("prefix cache reuse proved the program present")
- }
- };
- // A batch-warmed sparse cache holds transitions only for the spines that
- // were asked. A root without one has no old truth to diff, and turning it
- // into an upquery would trade its route's exact delta for a cold rematch,
- // so leave such roots to their routes and walk only where the cache
- // compares.
- if cache_is_batch_sparse {
- pending_nodes.retain(|&node| states.has_transition(node));
- }
- let mut pending_prefix_nodes: Vec<_> = pending_nodes
- .drain(..)
- .map(|node| PendingPrefixNode {
- node,
- entering_deltas: PrefixEnteringDeltas::default(),
- })
- .collect();
- while let Some(pending_node) = pending_prefix_nodes.pop() {
- let node = pending_node.node;
- if !automaton_has_sibling_steps
- && regions.is_covered_by_subtree(ImpactRegion::Node(node), &self.tree)
- {
- // NB: The transaction needs no narrower answer below an existing
- // subtree. A sibling-bearing automaton processes the node anyway:
- // its rightward output can reach later siblings outside the
- // covering subtree.
- // A covering subtree that is only attributed narrows the node's
- // patch to the covering rules, so the undiffed node must then
- // poison its patch to a full re-derivation.
- if self.selector_truth_changes_active
- && !regions.is_covered_by_full_subtree(ImpactRegion::Node(node), &self.tree)
- {
- self.selector_truth_changes
- .refreshes
- .push(SelectorTruthRefresh { node, rule: None });
- }
- // The skipped subtree's resident transitions describe pre-flush facts.
- // In a down-only automaton the subtree is exactly the set of states
- // that depend on the skipped node, so forget those transitions and
- // keep the rest of the cache warm instead of surrendering all of it.
- for stale in self.elements_under(node) {
- states.forget_transition(stale);
- }
- continue;
- }
- if !mark_element_visited(&mut visited, node) {
- continue;
- }
- // A topology flush disables the routed selection for difference
- // detection: a tree change can move matches no route named.
- let difference_selection = match tree_relations_changed {
- true => None,
- false => Some(&selection),
- };
- let local_facts_changed = local_fact_changes.binary_search(&node).is_ok();
- let local_prefix_candidates = local_facts_changed
- .then(|| local_prefix_producers.get(&node))
- .flatten()
- .map(Vec::as_slice)
- .filter(|steps| !steps.is_empty());
- // A node's positional bits move when its own sequence moved; its emptiness
- // moves when its children did.
- let positional_truth_stable = positional_tests.is_empty()
- || (positional_touched_parents.binary_search(&node).is_err()
- && self
- .tree
- .parent(node)
- .is_none_or(|parent| positional_touched_parents.binary_search(&parent).is_err()));
- let difference = match states.compare_and_update(
- &mut prefix_context.scratch,
- &mut prefix_context.effects,
- &mut new_evaluation,
- &mut old_evaluation,
- difference_selection,
- node,
- local_facts_changed,
- local_prefix_candidates,
- pending_node.entering_deltas,
- positional_truth_stable,
- &mut prefix_delta_arena,
- &self.counters,
- ) {
- PrefixTransitionLookup::Known(difference) => difference,
- PrefixTransitionLookup::Missing(_) => {
- complete = false;
- sibling_walk_abandoned = automaton_has_sibling_steps;
- break;
- }
- };
- self.counters.bump(Counter::PrefixConvergenceNodes);
- if difference.arrived {
- self.counters.bump(Counter::PrefixConvergenceUpqueries);
- // NB: An arrival has no old state to diff against, so the retained
- // answer must be re-derived cold. An exact node region alone does
- // not force that once attributed regions cover the node, so poison
- // its patch explicitly.
- if self.selector_truth_changes_active
- && !regions.is_covered_by_full_subtree(ImpactRegion::Node(node), &self.tree)
- {
- self.selector_truth_changes
- .refreshes
- .push(SelectorTruthRefresh { node, rule: None });
- }
- regions.add(ImpactRegion::Node(node));
- } else if difference.matches_changed {
- changed_nodes.push((node, difference.old_matches, difference.new_matches));
- }
- if automaton_has_sibling_steps
- && difference.right_changed
- && let Some(next) = self.tree.next_element_sibling(node)
- {
- // The next sibling pops after this node's whole changed subtree: it is
- // pushed first, and children go on top of it in document order.
- if states.has_transition(next) {
- pending_prefix_nodes.push(PendingPrefixNode {
- node: next,
- entering_deltas: PrefixEnteringDeltas {
- parent: pending_node.entering_deltas.parent,
- previous: difference.right_delta,
- parent_endpoints: pending_node.entering_deltas.parent_endpoints,
- },
- });
- } else if prefix_completion_budget != 0 {
- prefix_completion_budget -= 1;
- pending_prefix_nodes.push(PendingPrefixNode {
- node: next,
- entering_deltas: PrefixEnteringDeltas {
- parent: pending_node.entering_deltas.parent,
- previous: difference.right_delta,
- parent_endpoints: pending_node.entering_deltas.parent_endpoints,
- },
- });
- } else {
- complete = false;
- sibling_walk_abandoned = true;
- break;
- }
- }
- if difference.continuation_changed {
- let first_new_child = pending_prefix_nodes.len();
- for child in self.tree.children(node) {
- if states.has_transition(child) {
- pending_prefix_nodes.push(PendingPrefixNode {
- node: child,
- entering_deltas: PrefixEnteringDeltas {
- parent: difference.continuation_delta,
- previous: None,
- parent_endpoints: difference.continuation_endpoints,
- },
- });
- } else if prefix_completion_budget != 0 {
- prefix_completion_budget -= 1;
- pending_prefix_nodes.push(PendingPrefixNode {
- node: child,
- entering_deltas: PrefixEnteringDeltas {
- parent: difference.continuation_delta,
- previous: None,
- parent_endpoints: difference.continuation_endpoints,
- },
- });
- } else {
- regions.add(ImpactRegion::Subtree(child));
- }
- }
- // Pops must see siblings in document order, or a later sibling would
- // read its predecessor's rightward state before it is recomputed.
- pending_prefix_nodes[first_new_child..].reverse();
- } else {
- self.counters.bump(Counter::PrefixConvergenceStops);
- }
- }
- }
- if complete && let Lookup::Known(states) = retained.lookup_mut(scope_program) {
- states.install_prefix_effects(&mut prefix_context.effects);
- }
-
- if complete {
- {
- let states = match retained.lookup_mut(scope_program) {
- Lookup::Known(states) => states,
- Lookup::KnownAbsent | Lookup::Missing(_) => {
- unreachable!("prefix cache reuse proved the program present")
- }
- };
- for &node in &self.transaction_prefix().departures {
- states.forget_transition(node);
- }
- }
- {
- let states = match retained.lookup_mut(scope_program) {
- Lookup::Known(states) => states,
- Lookup::KnownAbsent | Lookup::Missing(_) => {
- unreachable!("prefix cache reuse proved the program present")
- }
- };
- for &(node, old_matches, new_matches) in &changed_nodes {
- // The interned sets name exactly which entries moved: those rules
- // join the node's attribution, so its patch stays that narrow.
- record_match_set_difference(
- &mut self.selector_truth_changes,
- self.selector_truth_changes_active,
- node,
- states.matches_in(old_matches),
- states.matches_in(new_matches),
- &dispatch,
- &self.program,
- );
- }
- }
- for (node, _, _) in changed_nodes {
- regions.add(ImpactRegion::Node(node));
- }
- // Subsumption speaks for a route's whole candidate space, so a walk over a
- // batch-warmed sparse cache keeps every route; the warmth still cut the
- // spine re-derivation. The walk has now refreshed the cache, so the sparse
- // origin clears either way.
- if !cache_is_batch_sparse {
- let mut released_route_bytes = 0;
- pending.retain(|key, routed_regions| {
- let keep = eligible_keys.binary_search(&key).is_err();
- if !keep {
- released_route_bytes += (routed_regions.capacity() * size_of::<ImpactRegion>()) as u64;
- }
- keep
- });
- }
- self.counters.bump(Counter::PrefixConvergencePasses);
-
- // The walk refreshed only the nodes it visited, so a batch-sparse cache
- // stays sparse until a completing full-batch retention says otherwise.
- retained.mark_current();
- return PrefixConvergenceOutcome {
- sibling_routes_are_covered: !cache_is_batch_sparse
- && automaton_has_sibling_steps
- && tree_relations_changed,
- positional_routes_are_covered: !cache_is_batch_sparse
- && !dispatch.prefixes().positional_tests().is_empty()
- && tree_relations_changed,
- };
- }
-
- retained.release();
- if sibling_walk_abandoned {
- // The abandoned walk already drained part of the pending stack, so the
- // transaction pass below would under-visit; leave the whole flush to the
- // conservative planner instead.
- answers.release(&mut self.match_answers);
- return PrefixConvergenceOutcome::default();
- }
- } else {
- retained.release();
- }
- }
- // NB: Prefix answers are keyed by identities minted by the transition cache. They are one
- // coherent cache and cannot outlive a transition cache that failed to become current.
- if had_retained_prefix_states {
- self.prefix_caches.borrow_mut().answers.release(&mut self.match_answers);
- }
-
- PrefixConvergenceOutcome::default()
- }
- #[must_use]
- pub(super) fn rule_has_complete_element_winners(&self, rule: RuleID, entry: &SelectorEntry) -> bool {
- entry.pseudo_element.is_none()
- && entry.scope_root.is_none()
- && !self.program.rule_is_gated_by_container_query(rule)
- && self.program.declarations_are_complete_for(rule)
- && self.program.sheet_origin(self.program.rule_sheet(rule)) == CascadeOrigin::Author
- }
-
- /// Whether a prefix route changes no retained winner in any resident cascade class.
- #[must_use]
- pub(super) fn prefix_route_cannot_change_any_retained_winner(
- &self,
- rule: RuleID,
- program: SelectorProgramID,
- entry_index: u32,
- changed_routing_keys: &[RoutingKey],
- ) -> bool {
- let winner_program_version = self.program.version();
- if !matches!(
- self.winner_groups
- .coverage_at_least(winner_program_version, self.tree.connected_element_count() as usize),
- Lookup::Known(())
- ) {
- return false;
- }
- let compiled = self.programs.get(program);
- let Some(entry) = compiled.entries().get(entry_index as usize) else {
- return false;
- };
- if !self.rule_has_complete_element_winners(rule, entry) {
- return false;
- }
- let dispatch_key = compiled.dispatch_key(entry);
- if !dispatch_key.has_selector_posting() {
- return false;
- }
- // The proof has a cheap half and an expensive half. The cheap half compares the changed
- // rule against the exact retained priority; only when it can not win is the expensive half
- // needed, which walks the winner's transpose sites to prove the transaction does not touch
- // that winner. Ask the cheap question first.
- let retained_winner_program = |previous: PropertyWinner, property| {
- let WinnerSource::Rule(winner_rule) = previous.source else {
- return None;
- };
- if !self
- .program
- .declared_properties_of(winner_rule)
- .iter()
- .any(|declaration| declaration.property == property)
- {
- return None;
- }
- let program = self.program.rule_version(winner_rule).selector_program?;
- let compiled = self.programs.get(program);
- if compiled.can_leave_its_scope() || compiled.entries().iter().any(|entry| entry.scope_root.is_some()) {
- return None;
- }
-
- Some(program)
- };
- let retained_winner_ignores_transaction = |program: SelectorProgramID| {
- let compiled = self.programs.get(program);
- for (entry_index, entry) in compiled.entries().iter().enumerate() {
- if entry.pseudo_element.is_some() {
- continue;
- }
- let mut reads_changed_input = false;
- compiled.collect_transpose_entry_points(entry_index, |site| {
- reads_changed_input |= changed_routing_keys.binary_search(&site.key).is_ok();
- });
- if reads_changed_input {
- return false;
- }
- }
- true
- };
- let state_is_unaffected = |state| {
- self.program.declared_properties_of(rule).iter().all(|declaration| {
- let Some(previous) = self.winner_groups.winner_in_state(state, declaration.property) else {
- return false;
- };
- let changed_priority = self.own_scope_cascade_priority_of(
- rule,
- TreeScopeID::DOCUMENT,
- entry.specificity,
- u32::MAX,
- declaration.important,
- );
- let Some(previous_program) = retained_winner_program(previous, declaration.property) else {
- return false;
- };
- changed_priority <= previous.priority && retained_winner_ignores_transaction(previous_program)
- })
- };
-
- // A single affected candidate disproves the route-wide claim. Ask before collecting
- // every distinct winner state, since a failed proof needs none of that collection.
- if let Lookup::Known(posting) = self.facts.postings().lookup(dispatch_key)
- && let Some(node) = posting.candidates().next()
- {
- let Lookup::Known(&(state, _)) = self
- .winner_groups
- .lookup(WinnerGroupKey::current(node, winner_program_version))
- else {
- return false;
- };
- if !state_is_unaffected(state) {
- return false;
- }
- }
- // Rules dispatched under one key all walk the same posting, and the winner column is
- // stable for the routing pass, so the distinct-state collection is shared through a
- // generation-keyed cache: the first asker pays the posting walk, and every further rule
- // under the key pays only the distinct-state count.
- let winner_generation = self.winner_groups.generation();
- let cached = self
- .route_pruning_states
- .lock()
- .expect("the route-pruning memo is never held across a panic")
- .get(&(dispatch_key, winner_generation))
- .cloned();
- let posting_states = match cached {
- Some(Some(states)) => states,
- Some(None) => return false,
- None => {
- let mut collected: Vec<CascadeStateID> = Vec::new();
- let complete = match self.facts.postings().lookup(dispatch_key) {
- Lookup::Known(posting) => posting.candidates().all(|node| {
- self.winner_groups
- .lookup(WinnerGroupKey::current(node, winner_program_version))
- .sparse()
- .is_ok_and(|&(state, _)| {
- if let Err(index) = collected.binary_search(&state) {
- collected.insert(index, state);
- }
- true
- })
- }),
- Lookup::KnownAbsent => true,
- Lookup::Missing(_) => false,
- };
- let entry_value = complete.then(|| Arc::new(collected));
- self.route_pruning_states
- .lock()
- .expect("the route-pruning memo is never held across a panic")
- .insert((dispatch_key, winner_generation), entry_value.clone());
- match entry_value {
- Some(states) => states,
- None => return false,
- }
- }
- };
- let mut states_with_moved_features: Option<Vec<CascadeStateID>> = None;
- let moved_features_are_complete = self
- .transaction_fact_view
- .as_ref()
- .expect("routing requires a transaction fact view")
- .moved_features
- .all_nodes_with_key(dispatch_key, |node| {
- let Some(&(state, _)) = self
- .winner_groups
- .lookup(WinnerGroupKey::current(node, winner_program_version))
- .sparse()
- .ok()
- else {
- return false;
- };
- let states = states_with_moved_features.get_or_insert_with(|| posting_states.as_ref().clone());
- if let Err(index) = states.binary_search(&state) {
- states.insert(index, state);
- }
- true
- });
- if !moved_features_are_complete {
- return false;
- }
- let states = states_with_moved_features.as_deref().unwrap_or(posting_states.as_ref());
-
- states.iter().copied().all(state_is_unaffected)
- }
-
- /// Finish local routes after all normalized inputs have contributed their regions.
- #[allow(clippy::too_many_arguments)]
- pub(super) fn flush_pending_routes(
- &mut self,
- pending: &mut PendingRoutes,
- regions: &mut ImpactRegions,
- workspace: &mut ImpactPlanningWorkspace,
- retained_winners_are_current: bool,
- transaction: &StyleTransaction,
- sequences: &SequenceChanges,
- pending_prefix_producers: &[PendingPrefixProducer],
- ) -> PrefixConvergenceOutcome {
- let prefix_convergence = self.add_prefix_convergence_regions(
- pending,
- regions,
- retained_winners_are_current,
- transaction,
- sequences,
- pending_prefix_producers,
- );
- let routing = Arc::clone(&self.routing);
- // Several changed facts can reach different transpose points of the same selector entry.
- // Once both exact fact sides and the retained answer are complete, their region union can
- // be compared by evaluating that entry once per candidate. This replaces repeated partial
- // path walks with the exact question the planner ultimately needs to answer. Keep initial
- // and incomplete state on the original route-order path.
- let can_group_exact_entries = retained_winners_are_current
- && transaction.inputs.iter().all(|input| {
- let (InputKey::LocalFeature(node, _) | InputKey::State(node, _)) = input.key else {
- return false;
- };
- matches!(
- self.winner_groups
- .lookup(WinnerGroupKey::current(node, self.program.version())),
- Lookup::Known(_)
- ) && matches!(self.retained_match_answer(node), Lookup::Known(_))
- })
- && transaction
- .inputs
- .iter()
- .all(|input| !matches!(input.key, InputKey::LocalFeature(_, LocalFeatureKey::ArrivingFacts)))
- && self.selector_incidence_is_current
- && self
- .transaction_fact_view
- .as_ref()
- .is_some_and(|view| view.retained_truth_available)
- && matches!(
- self.winner_groups
- .coverage_at_least(self.program.version(), self.tree.connected_element_count() as usize),
- Lookup::Known(())
- );
- if !can_group_exact_entries {
- for (key, routed_regions) in pending.iter_mut() {
- let route = key.route;
- routed_regions.sort_unstable();
- routed_regions.dedup();
- let rule = routing.rule_of(route);
- let point = routing.route(route);
- let site = RoutingSite {
- subject: routing.subject_dispatch_of(route),
- subject_required: routing.subject_required_of(route),
- position: routing.subject_position_of(route),
- path: routing.path_of(route),
- waypoints: routing.waypoints_of(route),
- in_flux: None,
- exact_entry: Some((rule, point.entry)),
- exact_tree_evaluation: key.exact_tree_evaluation,
- refresh_rule: Some((rule, point.entry)),
- };
- self.discard_regions_covered_by_subtree(routed_regions, &site, regions);
- self.add_narrowed_regions_with_workspace(routed_regions, &site, regions, workspace);
- }
- return prefix_convergence;
- }
- pending.entries.sort_unstable_by_key(|entry| {
- let point = routing.route(entry.key.route);
- (
- routing.rule_of(entry.key.route),
- point.entry,
- entry.key.exact_tree_evaluation,
- )
- });
- let mut first = 0;
- while first < pending.entries.len() {
- let key = pending.entries[first].key;
- let point = routing.route(key.route);
- let exact_entry = (routing.rule_of(key.route), point.entry);
- let mut end = first + 1;
- while end < pending.entries.len() {
- let next = pending.entries[end].key;
- let next_point = routing.route(next.route);
- if (routing.rule_of(next.route), next_point.entry) != exact_entry
- || next.exact_tree_evaluation != key.exact_tree_evaluation
- {
- break;
- }
- debug_assert_eq!(
- routing.subject_dispatch_of(next.route),
- routing.subject_dispatch_of(key.route)
- );
- debug_assert_eq!(
- routing.subject_required_of(next.route),
- routing.subject_required_of(key.route)
- );
- debug_assert_eq!(
- routing.subject_position_of(next.route),
- routing.subject_position_of(key.route)
- );
- end += 1;
- }
- self.counters.add(
- Counter::GroupedExactSelectorRoutes,
- end.saturating_sub(first + 1) as u64,
- );
- let mut merged_regions = std::mem::take(&mut pending.entries[first].regions);
- for entry in &mut pending.entries[first + 1..end] {
- merged_regions.extend(std::mem::take(&mut entry.regions));
- }
-
- let routed_regions = &mut merged_regions;
- let route = key.route;
- routed_regions.sort_unstable();
- routed_regions.dedup();
- let rule = routing.rule_of(route);
- let point = routing.route(route);
- let site = RoutingSite {
- subject: routing.subject_dispatch_of(route),
- subject_required: routing.subject_required_of(route),
- position: routing.subject_position_of(route),
- path: if end - first == 1 { routing.path_of(route) } else { &[] },
- waypoints: if end - first == 1 {
- routing.waypoints_of(route)
- } else {
- &[]
- },
- in_flux: None,
- exact_entry: Some((rule, point.entry)),
- exact_tree_evaluation: key.exact_tree_evaluation,
- refresh_rule: Some((rule, point.entry)),
- };
- self.discard_regions_covered_by_subtree(routed_regions, &site, regions);
- self.add_narrowed_regions_with_workspace(routed_regions, &site, regions, workspace);
-
- first = end;
- }
- prefix_convergence
- }
-
- pub(super) fn flush_pending_sibling_routes(
- &mut self,
- pending: &mut PendingSiblingRoutes,
- entries: &[SiblingEntry],
- regions: &mut ImpactRegions,
- workspace: &mut ImpactPlanningWorkspace,
- prefix_convergence_covers_sibling_routes: bool,
- ) {
- if prefix_convergence_covers_sibling_routes {
- let (_, dispatch) = self.prepare_scope_program(TreeScopeID::DOCUMENT);
- let routing = Arc::clone(&self.routing);
- let mut released_route_bytes = 0;
- pending.retain(|key, routed_regions| {
- let keep = !self.route_is_prefix_convergence_eligible(&routing, &dispatch, key.route);
- if !keep {
- released_route_bytes += (routed_regions.capacity() * size_of::<ImpactRegion>()) as u64;
- }
- keep
- });
- }
- let routing = Arc::clone(&self.routing);
- for (key, routed_regions) in pending.iter_mut() {
- let Ok(index) = entries.binary_search_by_key(&key.route, |entry| entry.route) else {
- continue;
- };
- let entry = &entries[index];
- routed_regions.sort_unstable();
- routed_regions.dedup();
- let site = match key.kind {
- SiblingRouteKind::Full => entry.site(&routing, key.exact_tree_evaluation),
- SiblingRouteKind::BeyondSibling => {
- entry.site_beyond_the_sibling_step(&routing, key.exact_tree_evaluation)
- }
- SiblingRouteKind::Departure | SiblingRouteKind::ExactUnion => {
- let point = routing.route(entry.route);
- let exact_entry = (key.kind == SiblingRouteKind::ExactUnion || key.exact_tree_evaluation.is_some())
- .then_some((routing.rule_of(entry.route), point.entry));
- RoutingSite {
- subject: routing.subject_dispatch_of(entry.route),
- subject_required: routing.subject_required_of(entry.route),
- position: routing.subject_position_of(entry.route),
- path: if key.kind == SiblingRouteKind::ExactUnion {
- &[]
- } else {
- routing.path_of(entry.route)
- },
- waypoints: &[],
- in_flux: None,
- exact_entry,
- exact_tree_evaluation: key.exact_tree_evaluation,
- refresh_rule: Some((routing.rule_of(entry.route), point.entry)),
- }
- }
- };
- self.discard_regions_covered_by_subtree(routed_regions, &site, regions);
- self.add_narrowed_regions_with_workspace(routed_regions, &site, regions, workspace);
- }
- }
-
- /// Add a region, replacing it with the subject's candidates inside it where that is cheaper.
- /// Add a planned region, carrying the site's exact rule as attribution when it names one, so
- /// retained answers covered only by such regions can patch against the covering rules
- /// instead of fully re-deriving.
- pub(super) fn add_region_for_site(
- &mut self,
- region: ImpactRegion,
- site: &RoutingSite<'_>,
- regions: &mut ImpactRegions,
- ) {
- match site.attribution() {
- Some(key) => regions.add_attributed(region, key),
- None => regions.add(region),
- }
- }
-
- /// Preserve a route's contribution to the retained-answer patch when its region is discarded
- /// because an already planned subtree covers it. Coverage alone stopped being a sound reason
- /// to forget the route once patch narrowing existed: the covering subtree may itself be
- /// attributed to another route's rule, in which case a covered node's patch narrows to the
- /// covering attributions and would silently lose this route's rule. A site that names a rule
- /// records its extent symbolically over the dropped region; a site with no rule poisons the
- /// region to the full re-derivation cover, per the `refresh_rule` contract.
- pub(super) fn attribute_region_covered_by_subtree(
- &mut self,
- region: ImpactRegion,
- site: &RoutingSite<'_>,
- regions: &mut ImpactRegions,
- ) {
- if !self.selector_truth_changes_active || regions.is_covered_by_full_subtree(region, &self.tree) {
- return;
- }
- match site.attribution() {
- Some(key) => regions.attribute_extent(region, key),
- None => match region {
- ImpactRegion::Node(node) => self.record_selector_truth_refresh(node, None),
- _ => regions.add(region),
- },
- }
- }
-
- /// Drop the routed regions an already planned subtree covers, carrying each dropped region's
- /// contribution into the patch cover first.
- pub(super) fn discard_regions_covered_by_subtree(
- &mut self,
- routed_regions: &mut Vec<ImpactRegion>,
- site: &RoutingSite<'_>,
- regions: &mut ImpactRegions,
- ) {
- let mut kept = 0;
- for index in 0..routed_regions.len() {
- let region = routed_regions[index];
- if !regions.is_covered_by_subtree(region, &self.tree) {
- routed_regions[kept] = region;
- kept += 1;
- continue;
- }
- self.attribute_region_covered_by_subtree(region, site, regions);
- }
- routed_regions.truncate(kept);
- }
-
- pub(super) fn add_narrowed_region(
- &mut self,
- region: ImpactRegion,
- site: &RoutingSite<'_>,
- regions: &mut ImpactRegions,
- ) {
- let mut workspace = ImpactPlanningWorkspace::default();
- self.add_narrowed_regions_with_workspace(std::slice::from_ref(&region), site, regions, &mut workspace);
- }
-
- pub(super) fn add_position_bounded_region(
- &mut self,
- region: ImpactRegion,
- site: &RoutingSite<'_>,
- regions: &mut ImpactRegions,
- ) {
- if regions.is_covered_by_subtree(region, &self.tree) {
- self.attribute_region_covered_by_subtree(region, site, regions);
- return;
- }
- if let ImpactRegion::Node(node) = region
- && regions.contains_node(node)
- {
- match site.attribution() {
- Some(key) if self.selector_truth_changes_active => {
- regions.attribute_extent(region, key);
- }
- _ => self.record_already_planned_selector_truth(node, site),
- }
- return;
- }
-
- // A subject with no feature to enumerate by can still be bounded by where in a sequence it
- // is allowed to be: `:first-child` names one element of a sequence however long it is.
- if let ImpactRegion::Children(parent) = region
- && site.position.bound != u32::MAX
- {
- let unbounded = RoutingSite {
- position: SubjectPosition::UNBOUNDED,
- ..*site
- };
- let bound = site.position.bound as usize;
- if bound == 0 {
- return;
- }
- if site.position.from_end {
- let mut named = VecDeque::new();
- for child in self.tree.children(parent) {
- if named.len() == bound {
- named.pop_front();
- }
- named.push_back(child);
- }
-
- for child in named {
- self.add_narrowed_region(ImpactRegion::Node(child), &unbounded, regions);
- }
- } else {
- let mut next = self.tree.first_element_child(parent);
- for _ in 0..bound {
- let Some(child) = next else {
- break;
- };
- next = self.tree.next_element_sibling(child);
- self.add_narrowed_region(ImpactRegion::Node(child), &unbounded, regions);
- }
- }
- return;
- }
- unreachable!("position-bounded routing only expands child regions");
- }
-
- /// Route a custom-property registration to the elements whose cascade declares its name and
- /// those whose substitution dependencies could not be named precisely.
- pub(super) fn custom_property_registration_consumers(
- &self,
- name: StyleAtomID,
- ) -> Result<Vec<StyleNodeID>, PostingKey> {
- let mut nodes = self.facts.custom_property_candidates(name)?;
- match self.facts.postings().lookup(DependencyPostingKey::AnyCustomProperty) {
- Lookup::Known(posting) => posting.append_candidates_to(&mut nodes),
- Lookup::KnownAbsent => {}
- Lookup::Missing(gap) => return Err(gap),
- }
- Ok(nodes)
- }
-
- fn route_custom_property_registration(
- &mut self,
- name: StyleAtomID,
- scopes: Option<&[TreeScopeID]>,
- regions: &mut ImpactRegions,
- ) {
- let Ok(mut consumers) = self.custom_property_registration_consumers(name) else {
- if let Some(scopes) = scopes
- && let Some(reachable) = self.regions_reachable_for_named_consumers(scopes)
- {
- for region in reachable {
- regions.add_if_not_covered(region, &self.tree);
- }
- return;
- }
- regions.widen_to_document(&self.counters);
- return;
- };
- consumers.sort_unstable();
- consumers.dedup();
- if let Some(scopes) = scopes
- && let Some(reachable) = self.regions_reachable_for_named_consumers(scopes)
- {
- consumers.retain(|&node| reachable.iter().any(|region| region.contains_node(node, &self.tree)));
- }
- for node in consumers {
- regions.add_if_not_covered(ImpactRegion::Node(node), &self.tree);
- }
- }
-
- /// Whether a node is near enough to either end of its sibling sequence to be a bounded subject
- /// on one side of the transaction.
- ///
- /// The bound is how far in the sequence the subject can be, so the walk is at most that many
- /// steps: `:first-child` asks whether anything precedes the node, and stops there. The old side
- /// is where the transaction captured it: a sequence it did not capture did not change, and a
- /// transaction that captured nothing leaves every node possibly anywhere.
- #[must_use]
- pub(super) fn node_is_within_subject_position(
- &self,
- node: StyleNodeID,
- position: SubjectPosition,
- side: TransactionFactSide,
- ) -> bool {
- if position.bound == u32::MAX {
- return true;
- }
- if side == TransactionFactSide::Before {
- let Some(view) = self
- .transaction_fact_view
- .as_ref()
- .filter(|view| view.before_sibling_relations_available)
- else {
- return true;
- };
- if let Some(old) = view.before_sibling_geometry.sibling_positions(node) {
- return match position.from_end {
- true => old.from_end,
- false => old.from_start,
- } <= position.bound;
- }
- }
- let mut remaining = position.bound;
- let mut cursor = Some(node);
- while let Some(current) = cursor {
- if remaining == 0 {
- return false;
- }
- remaining -= 1;
- cursor = match position.from_end {
- true => self.tree.next_element_sibling(current),
- false => self.tree.previous_element_sibling(current),
- };
- }
- true
- }
-}
-
-impl StyleEngine {
- /// Lower one normalized program input into rows of the active-rule-match join.
- pub(super) fn append_program_join_deltas(&self, input: &NormalizedInput, output: &mut Vec<ProgramJoinDelta>) {
- let (rules, kind) = match input.key {
- InputKey::RuleField(rule, field) => {
- let kind = match field {
- RuleField::Existence | RuleField::Selector | RuleField::Activation | RuleField::Scope => {
- ProgramJoinDeltaKind::ActiveRuleMatch
- }
- RuleField::Declarations => ProgramJoinDeltaKind::Declarations,
- RuleField::Layer => ProgramJoinDeltaKind::Priority,
- };
- (vec![rule], kind)
- }
- InputKey::SheetAttachment(sheet, _) | InputKey::SheetActivation(sheet) => (
- self.retained.program.rules_in_sheet(sheet),
- ProgramJoinDeltaKind::ActiveRuleMatch,
- ),
- InputKey::CascadeTopology(TopologyAxis::SheetOrder(tree_scope)) => {
- let sheets = self
- .host
- .program_staging
- .sheets_in_scope
- .pairs()
- .find(|(scope, _, _)| *scope == tree_scope)
- .map_or_else(
- || self.retained.program.sheets_in_scope(tree_scope).to_vec(),
- |(_, before, after)| {
- let mut positions_by_origin = HashMap::default();
- let before_positions: HashMap<_, _> = before
- .iter()
- .map(|&sheet| {
- let position = positions_by_origin
- .entry(self.retained.program.sheet_origin(sheet) as u8)
- .or_insert(0u64);
- let entry = (sheet, *position);
- *position += 1;
- entry
- })
- .collect();
- positions_by_origin.clear();
- after
- .iter()
- .filter_map(|&sheet| {
- let position = positions_by_origin
- .entry(self.retained.program.sheet_origin(sheet) as u8)
- .or_insert(0u64);
- let changed = before_positions
- .get(&sheet)
- .is_some_and(|previous| previous != position);
- *position += 1;
- changed.then_some(sheet)
- })
- .collect()
- },
- );
- (
- sheets
- .into_iter()
- .flat_map(|sheet| self.retained.program.rules_in_sheet(sheet))
- .collect(),
- ProgramJoinDeltaKind::Priority,
- )
- }
- InputKey::CascadeTopology(TopologyAxis::LayerOrder(tree_scope)) => {
- let layer_order = self
- .host
- .program_staging
- .layer_orders
- .pairs()
- .find(|(scope, _, _)| *scope == tree_scope);
- (
- self.retained
- .program
- .rules_in_a_layer_in_scope(tree_scope)
- .into_iter()
- .filter(|&rule| {
- let layer = self.retained.program.rule_version(rule).layer;
- layer_order.is_none_or(|(_, before, after)| before.get(&layer) != after.get(&layer))
- })
- .collect(),
- ProgramJoinDeltaKind::Priority,
- )
- }
- _ => return,
- };
-
- output.extend(rules.into_iter().map(|rule| {
- let current_program = self.retained.program.rule_version(rule).selector_program;
- let (before_program, after_program, before_contributes, after_contributes) = match input.key {
- InputKey::RuleField(_, RuleField::Selector) => {
- let before = match input.old {
- InputValue::SelectorProgram(program) => program,
- _ => current_program,
- };
- let after = match input.new {
- InputValue::SelectorProgram(program) => program,
- _ => current_program,
- };
- (before, after, before.is_some(), after.is_some())
- }
- InputKey::RuleField(_, RuleField::Existence | RuleField::Activation)
- | InputKey::SheetAttachment(..)
- | InputKey::SheetActivation(_) => {
- let before = match input.old {
- InputValue::Flag(value) => value,
- _ => true,
- };
- let after = match input.new {
- InputValue::Flag(value) => value,
- _ => true,
- };
- (current_program, current_program, before, after)
- }
- InputKey::RuleField(_, RuleField::Scope | RuleField::Declarations | RuleField::Layer)
- | InputKey::CascadeTopology(_) => (current_program, current_program, true, true),
- _ => unreachable!("program join lowering accepted a non-program input"),
- };
- ProgramJoinDelta {
- input: input.key,
- rule,
- before_program,
- after_program,
- before_contributes,
- after_contributes,
- kind,
- }
- }));
- }
-
- /// Whether the retained cascade answers prove that a program change cannot change a winner.
- ///
- /// The winner column is the answer from the last completed cascade, not a prediction. Adding a
- /// declaration below every retained winner leaves that answer unchanged. Editing a winner to
- /// the same canonical specified value does too, provided its priority does not fall and expose
- /// a contender that the winner column deliberately does not retain.
- #[must_use]
- pub(super) fn program_change_cannot_change_retained_winners(
- &self,
- input: &NormalizedInput,
- rule: RuleID,
- entry: &SelectorEntry,
- winner_program_version: Option<ProgramVersion>,
- probe: RetainedWinnerProbe,
- ) -> bool {
- if !self.rule_has_complete_element_winners(rule, entry) {
- return false;
- }
- // The completeness the gate above reads is the new side's. A declarations edit is judged
- // against the old winners, and a block that was incomplete before the edit can have
- // declared custom properties, which the winner columns never hold - so the proof cannot
- // see what the rule used to contribute, and pruning would strand its old declarations.
- if matches!(input.key, InputKey::RuleField(changed, RuleField::Declarations) if changed == rule)
- && self
- .host
- .program_staging
- .rules_with_incomplete_old_declarations
- .contains(&rule)
- {
- return false;
- }
- let Some(winner_program_version) = winner_program_version else {
- return false;
- };
- let node_state = match probe {
- RetainedWinnerProbe::Node(node) => {
- // Shadow-scope winner rows do not describe the complete cascade.
- if self.retained.tree.tree_scope(node) != TreeScopeID::DOCUMENT {
- return false;
- }
- let retained_winner_key = WinnerGroupKey::retained(node, winner_program_version);
- if !matches!(
- self.retained.winner_groups.lookup(retained_winner_key),
- Lookup::Known(_)
- ) {
- return false;
- }
- if matches!(
- input.key,
- InputKey::CascadeTopology(TopologyAxis::SheetOrder(_) | TopologyAxis::LayerOrder(_))
- ) {
- return self.retained.program.declared_properties_of(rule).iter().all(|current| {
- matches!(
- self.retained.winner_groups.winner(retained_winner_key, current.property),
- Lookup::Known(previous) if previous.key == RetainedState::retained_rule_winner_key(*current)
- )
- });
- }
- let current_winner_key = WinnerGroupKey::current(node, winner_program_version);
- let state = match self.retained.winner_groups.lookup(current_winner_key) {
- Lookup::Known(&(state, _)) => state,
- Lookup::KnownAbsent | Lookup::Missing(_) => return false,
- };
- if matches!(
- input.key,
- InputKey::RuleField(changed, RuleField::Declarations) if changed == rule
- ) {
- let declared = self.retained.program.declared_properties_of(rule);
-
- // A property this rule used to win but no longer declares exposes a runner-up
- // that this compact column intentionally does not retain.
- if self.retained.winner_groups.winners_in_state(state).any(|previous| {
- previous.source == WinnerSource::Rule(rule)
- && !declared.iter().any(|current| current.property == previous.property)
- }) {
- return false;
- }
-
- return declared.iter().all(|current| {
- let Some(previous) = self.retained.winner_groups.winner_in_state(state, current.property)
- else {
- return false;
- };
- let key = RetainedState::retained_rule_winner_key(*current);
-
- if previous.source == WinnerSource::Rule(rule) {
- // Raising the same winner cannot expose anything below it. Lowering it
- // can, even when its own value is unchanged.
- (!previous.important || current.important) && key == previous.key
- } else {
- // A declaration that remains below the retained winner is inert. One
- // that reaches or passes it is inert only for the same semantic value.
- key == previous.key
- }
- });
- }
- Some((state, self.retained.tree.tree_scope(node)))
- }
- RetainedWinnerProbe::AllResident { resident_count } => {
- if !matches!(
- self.retained
- .winner_groups
- .coverage_at_least(winner_program_version, resident_count),
- Lookup::Known(())
- ) {
- return false;
- }
- None
- }
- };
- if matches!(
- (input.key, input.old, input.new),
- (
- InputKey::RuleField(changed, RuleField::Activation),
- InputValue::Flag(true),
- InputValue::Flag(false)
- ) if changed == rule
- ) {
- let Some((state, _)) = node_state else {
- return false;
- };
- return self
- .retained
- .program
- .declared_properties_of(rule)
- .iter()
- .all(|declared| {
- !matches!(
- self.retained.winner_groups.winner_in_state(state, declared.property),
- Some(previous) if previous.source == WinnerSource::Rule(rule)
- )
- });
- }
- match (input.key, input.old, input.new) {
- (
- InputKey::SheetAttachment(..)
- | InputKey::SheetActivation(_)
- | InputKey::RuleField(_, RuleField::Existence | RuleField::Activation),
- InputValue::Flag(false),
- InputValue::Flag(true),
- ) => {}
- _ => return false,
- }
-
- let declarations_are_inert = |state, tree_scope| {
- self.retained
- .program
- .declared_properties_of(rule)
- .iter()
- .all(|declared| {
- let Some(previous) = self.retained.winner_groups.winner_in_state(state, declared.property) else {
- return false;
- };
- let WinnerSource::Rule(previous_rule) = previous.source else {
- return false;
- };
- let Some(previous_program) = self.retained.program.rule_version(previous_rule).selector_program
- else {
- return false;
- };
- if self.retained.programs.get(previous_program).can_leave_its_scope() {
- return false;
- }
- let priority = self.own_scope_cascade_priority_of(
- rule,
- tree_scope,
- entry.specificity,
- u32::MAX,
- declared.important,
- );
- priority <= previous.priority
- })
- };
- match node_state {
- Some((state, tree_scope)) => declarations_are_inert(state, tree_scope),
- None => self
- .winner_groups
- .active_states()
- .all(|state| declarations_are_inert(state, TreeScopeID::DOCUMENT)),
- }
- }
-}
-
-impl StyleEngine {
- /// Route a program change to the elements the affected rules could match.
- ///
- /// Inserting a sheet invalidates no existing selector truth, so the region is not the document:
- /// it is the candidates of the rules that arrived or left. A sheet of `@font-face` rules
- /// contributes no style rule and therefore reaches nothing at all, and a sheet whose rules all
- /// name a class reaches only the elements carrying it. An entry with no selective rightmost
- /// feature has no posting to drive from, and only then does the region widen.
- #[allow(clippy::too_many_arguments)]
- pub(super) fn route_program_input(
- &mut self,
- input: &NormalizedInput,
- program_joins: &[ProgramJoinDelta],
- arriving_rules: &[RuleID],
- departed_sheet_scopes: &[(SheetID, TreeScopeID)],
- context: ProgramRoutingContext<'_>,
- regions: &mut ImpactRegions,
- ) {
- let ProgramRoutingContext {
- resident_nodes,
- winner_program_version,
- document_root,
- attachment_scopes,
- removed_rules_requiring_refresh,
- } = context;
- let key = input.key;
- if let InputKey::CustomPropertyRegistration(name) = key {
- self.route_custom_property_registration(name, None, regions);
- return;
- }
- if program_joins.is_empty() {
- return;
- }
-
- // A rule that is retargeted stops matching what it matched. Both sides of the change have
- // to be reached, or the declarations the old selector was winning are never taken back.
- // A sheet decides only in the scopes it is attached to. Its rules' features are indexed
- // across the whole document, so a sheet adopted by one shadow root would otherwise reach
- // every element anywhere carrying the same class. A program using `:host`, `::slotted()` or
- // `::part()` does reach out of its scope, and only that program skips the check.
- let mut scopes = match key {
- // An attachment change names the scope it happened in, which is the only place it can
- // reach - and the only answer that still holds once the sheet has left, since by routing
- // time the attachment it is about is gone.
- InputKey::SheetAttachment(_, tree_scope) => {
- attachment_scopes.map_or_else(|| vec![tree_scope], |scopes| scopes.to_vec())
- }
- InputKey::SheetActivation(sheet) => self.scopes_of_sheet(sheet, departed_sheet_scopes),
- InputKey::RuleField(rule, _) => {
- self.scopes_of_sheet(self.retained.program.rule_sheet(rule), departed_sheet_scopes)
- }
- InputKey::CascadeTopology(TopologyAxis::SheetOrder(tree_scope) | TopologyAxis::LayerOrder(tree_scope)) => {
- vec![tree_scope]
- }
- _ => Vec::new(),
- };
- scopes.sort_unstable();
- scopes.dedup();
-
- // A sheet attached nowhere decides nothing, so neither do its rules. Re-inserting a `<style>`
- // element builds a new sheet and drops the old one, and the dropped one's rules are still
- // recorded as having arrived - answering for them with the whole document would make every
- // detach and reattach of a subtree holding a sheet a full restyle.
- if matches!(key, InputKey::SheetActivation(_) | InputKey::RuleField(..)) && scopes.is_empty() {
- return;
- }
-
- let resident_count = resident_nodes.map_or(self.retained.tree.connected_element_count() as usize, |nodes| {
- nodes.len()
- });
-
- let mut programs: Vec<(RuleID, SelectorProgramID)> = program_joins
- .iter()
- .filter(|delta| delta.before_program != delta.after_program)
- .flat_map(|delta| {
- [delta.before_program, delta.after_program]
- .into_iter()
- .flatten()
- .map(|program| (delta.rule, program))
- })
- .collect();
- let changes_selector_truth = program_joins
- .iter()
- .any(|delta| delta.kind == ProgramJoinDeltaKind::ActiveRuleMatch);
- let removes_contribution = matches!(
- (key, input.old, input.new),
- (
- InputKey::SheetAttachment(..)
- | InputKey::SheetActivation(_)
- | InputKey::RuleField(_, RuleField::Existence | RuleField::Activation),
- InputValue::Flag(true),
- InputValue::Flag(false)
- )
- );
-
- for delta in program_joins {
- let rule = delta.rule;
- // Liveness is not asked about, because a rule being deleted is the change: it is no
- // longer live, and what it was winning still has to be repaired.
- //
- // Its activation is asked about: a rule behind a group whose condition does not hold
- // decides nothing, so a sheet arriving, leaving, being enabled or being reordered moves
- // nothing it could have won. A rule whose own activation is the change is the one case
- // where the answer has to come from the other side of it, and that is decided below.
- if !matches!(key, InputKey::RuleField(..)) && !self.retained.program.rule_conditions_hold(rule) {
- continue;
- }
- let version = self.retained.program.rule_version(rule);
- // A rule that reaches its consumers by name matches nothing, so what finds them is the
- // index of who uses that name: the elements running an animation for `@keyframes`, the
- // elements declaring or referencing a custom property for `@property`.
- if let Some(name) = version.declared_name {
- if version.kind == RuleKind::Property {
- self.route_custom_property_registration(name, Some(&scopes), regions);
- continue;
- }
- let consumers = match version.kind {
- RuleKind::Keyframes => {
- match self
- .retained
- .facts
- .postings()
- .lookup(DependencyPostingKey::AnimationName(name))
- {
- Lookup::Known(posting) => Ok(posting.candidates().collect()),
- Lookup::KnownAbsent => Ok(Vec::new()),
- Lookup::Missing(gap) => Err(gap),
- }
- }
- _ => continue,
- };
- let Ok(mut consumers) = consumers else {
- match self.regions_reachable_for_named_consumers(&scopes) {
- Some(reachable) => {
- for region in reachable {
- regions.add_if_not_covered(region, &self.retained.tree);
- }
- continue;
- }
- None => {
- regions.widen_to_document(&self.retained.counters);
- return;
- }
- }
- };
- consumers.sort_unstable();
- consumers.dedup();
- // The index is document-wide, but a scope-local sheet decides only in the tree it is
- // attached to, its host, and the nodes slotted into it. An element elsewhere running
- // an animation of the same name is not this sheet's business.
- // A named rule reaches consumers, not selector subjects. Consumers can be inside
- // the attached tree or outside it through `:host` and `::slotted()` declarations.
- if let Some(reachable) = self.regions_reachable_for_named_consumers(&scopes) {
- consumers.retain(|&node| {
- reachable
- .iter()
- .any(|region| region.contains_node(node, &self.retained.tree))
- });
- }
- for node in consumers {
- regions.add_if_not_covered(ImpactRegion::Node(node), &self.retained.tree);
- }
- continue;
- }
- // A property rule without a declared name registers nothing.
- if version.kind == RuleKind::Property {
- continue;
- }
- // A custom function reaches the elements that called one. Which function they called is
- // not reported by the substitution machinery, so it is all of them - bounded by having
- // called a function at all, rather than by the document.
- if version.kind == RuleKind::Function {
- let consumers: Vec<StyleNodeID> = match self
- .retained
- .facts
- .postings()
- .lookup(DependencyPostingKey::AnyCustomFunction)
- {
- Lookup::Known(posting) => posting.candidates().collect(),
- Lookup::KnownAbsent => Vec::new(),
- Lookup::Missing(_) => match self.regions_reachable_for_named_consumers(&scopes) {
- Some(reachable) => {
- for region in reachable {
- regions.add_if_not_covered(region, &self.retained.tree);
- }
- continue;
- }
- None => {
- regions.widen_to_document(&self.retained.counters);
- return;
- }
- },
- };
- for node in consumers {
- regions.add_if_not_covered(ImpactRegion::Node(node), &self.retained.tree);
- }
- continue;
- }
- // `@font-feature-values` changes how a font feature name resolves for every element that
- // uses one, and nothing indexes which elements those are: the names are resolved deep in
- // value computation, not by selector matching. So it reaches everything the sheet decides
- // for, the same shape as a registration that carries an initial value.
- if version.kind == RuleKind::FontFeatureValues {
- regions.widen_to_document(&self.retained.counters);
- return;
- }
- // A counter style can be referenced through list markers and generated content. Those
- // consumers are resolved while computing values and are not indexed by rule name.
- if version.kind == RuleKind::CounterStyle {
- regions.widen_to_document(&self.retained.counters);
- return;
- }
- // A rule that does not contribute declarations through selector matching reaches no
- // element: an @font-face rule arrives at its own consumers instead.
- if !version.kind.matches_elements() {
- continue;
- }
- if let Some(selector_program) = version.selector_program {
- let compiled = self.retained.programs.get(selector_program);
- let winner_inventory_is_complete = removes_contribution
- // Container conditions are evaluated by the style consumer, so its
- // winning declarations are not proven by the native winner inventory.
- && !self.retained.program.rule_is_gated_by_container_query(rule)
- && self.retained.program.declarations_are_complete_for(rule)
- && compiled.entries().iter().all(|entry| entry.pseudo_element.is_none())
- && winner_program_version.is_some_and(|version| {
- matches!(
- self.retained.winner_groups.coverage_at_least(version, resident_count),
- Lookup::Known(())
- )
- });
- if winner_inventory_is_complete {
- if !self.retained.winner_groups.rule_is_a_winner(rule) {
- if self.retained.selector_truth_changes_active {
- removed_rules_requiring_refresh.push(rule);
- }
- self.retained.counters.bump(Counter::ProgramCandidatesRejectedByCascade);
- continue;
- }
- let winning_nodes = (!compiled.subject_can_leave_its_scope()
- && compiled
- .entries()
- .iter()
- .all(|entry| compiled.dispatch_key(entry).has_selector_posting()))
- .then(|| {
- self.retained.winner_groups.winning_nodes(rule).map(|nodes| {
- nodes.filter(|&node| scopes.binary_search(&self.retained.tree.tree_scope(node)).is_ok())
- })
- })
- .flatten();
- if let Some(nodes) = winning_nodes {
- if self.retained.selector_truth_changes_active {
- removed_rules_requiring_refresh.push(rule);
- }
- for node in nodes {
- regions.add_if_not_covered(ImpactRegion::Node(node), &self.retained.tree);
- }
- continue;
- }
- }
- programs.push((rule, selector_program));
- }
- }
- programs.sort_unstable_by_key(|(rule, program)| (program.0, rule.0));
- programs.dedup();
-
- // A rule behind a group whose condition does not hold decides nothing, so a rule arriving
- // inside one reaches nothing. Its activation is normally exempt from that - a condition
- // turning off is precisely what has to reach the rule's matches to take its declarations
- // back - but not when the rule arrived in this same transaction, because then there is
- // nothing to take back.
- if let InputKey::RuleField(rule, field) = key
- && !self.retained.program.rule_conditions_hold(rule)
- && (field != RuleField::Activation || arriving_rules.contains(&rule))
- {
- return;
- }
-
- // The old side's tree is the one the transaction captured, and a transaction too wide for
- // exact tree routing captures none, so there the old side cannot be read at all.
- let old_side_is_readable = self
- .transaction_fact_view
- .as_ref()
- .is_some_and(|view| view.before_sibling_relations_available);
- let mut first_program_rule = 0;
- while first_program_rule < programs.len() {
- let selector_program = programs[first_program_rule].1;
- let end_program_rule = programs[first_program_rule..]
- .partition_point(|&(_, program)| program == selector_program)
- + first_program_rule;
- let program_rules = &programs[first_program_rule..end_program_rule];
- let can_leave_scope = self.retained.programs.get(selector_program).can_leave_its_scope();
- let subject_can_leave_scope = self
- .retained
- .programs
- .get(selector_program)
- .subject_can_leave_its_scope();
- let bounded_by_scope = !scopes.is_empty() && !subject_can_leave_scope;
- // Activation is one input of an active rule match; selector truth is the other. The
- // dispatch posting is only a candidate source, so test the complete selector before
- // admitting one of its nodes. Turning a rule off reads the old side and turning it on
- // reads the new side. If that side cannot be reconstructed, keep the candidate.
- // A sheet attaching, detaching, or toggling activation is the same shape sheet-wide:
- // on the side where the sheet contributed nothing it decided nothing, so only the side
- // where it contributes has to be read, and a candidate its selector does not match
- // there is not a subject of the change.
- let can_filter_exactly = matches!(
- key,
- InputKey::RuleField(_, RuleField::Activation)
- | InputKey::SheetAttachment(..)
- | InputKey::SheetActivation(_)
- ) && scopes.as_slice() == [TreeScopeID::DOCUMENT]
- && !can_leave_scope;
- let retained_incidence = if can_filter_exactly
- && self.retained.selector_incidence_is_current
- && matches!(key, InputKey::RuleField(_, RuleField::Activation))
- {
- self.retained
- .retained_selector_incidences
- .lookup(selector_program)
- .cloned()
- .or_else(|| {
- program_joins
- .iter()
- .any(|delta| delta.before_contributes && delta.before_program == Some(selector_program))
- .then(|| self.retained_selector_incidence(selector_program, document_root))
- .flatten()
- })
- .or_else(|| self.materialize_current_selector_incidence(selector_program))
- } else {
- None
- };
- if let Some(incidences) = retained_incidence {
- // Selector incidence is invariant under activation. The retained relation was
- // materialized while this program contributed, so route its exact subjects and
- // leave liveness to the active-rule join downstream. In particular, an empty
- // relation is a complete answer and performs no selector work.
- let change = match (input.old, input.new) {
- (InputValue::Flag(false), InputValue::Flag(true)) => SetChange::Added,
- (InputValue::Flag(true), InputValue::Flag(false)) => SetChange::Removed,
- _ => unreachable!("an activation input must flip its boolean value"),
- };
- for incidence in incidences.iter().copied() {
- let node = incidence.node;
- if resident_nodes.is_some_and(|resident| resident.binary_search(&node).is_err()) {
- continue;
- }
- if bounded_by_scope && scopes.binary_search(&self.retained.tree.tree_scope(node)).is_err() {
- continue;
- }
- let entry = &self.retained.programs.get(selector_program).entries()[incidence.entry as usize];
- if program_rules.iter().all(|&(rule, _)| {
- self.program_change_cannot_change_retained_winners(
- input,
- rule,
- entry,
- winner_program_version,
- RetainedWinnerProbe::Node(node),
- )
- }) {
- self.record_selector_truth_refresh(node, None);
- self.retained
- .counters
- .add(Counter::ProgramCandidatesRejectedByCascade, program_rules.len() as u64);
- continue;
- }
- if self.retained.selector_truth_changes_active && changes_selector_truth {
- for &(rule, _) in program_rules {
- self.retained.selector_truth_changes.deltas.push(SelectorTruthDelta {
- node,
- rule,
- entry: self.retained.programs.entry_id(selector_program, incidence.entry),
- change,
- selector_truth_changed: false,
- });
- }
- }
- regions.add_if_not_covered(ImpactRegion::Node(node), &self.retained.tree);
- }
- first_program_rule = end_program_rule;
- continue;
- }
- let activation_fact_sides = can_filter_exactly
- .then_some(match (input.old, input.new) {
- (InputValue::Flag(false), InputValue::Flag(true)) => (None, Some(TransactionFactSide::After)),
- (InputValue::Flag(true), InputValue::Flag(false)) => (Some(TransactionFactSide::Before), None),
- _ => (Some(TransactionFactSide::Before), Some(TransactionFactSide::After)),
- })
- .filter(|(old_side, _)| old_side.is_none() || old_side_is_readable);
- // A program that stops deciding - a rule turned off or deleted, a sheet detached, the old
- // selector of a retargeted rule - matched its subjects where they stood before the
- // change, and tree routing reaches none that has moved since: its routes are gone.
- let subject_side = match removes_contribution
- || matches!(input.new, InputValue::SelectorProgram(after) if after != Some(selector_program))
- {
- true => TransactionFactSide::Before,
- false => TransactionFactSide::After,
- };
- let compiled = self.retained.programs.get(selector_program);
- for (entry_index, entry) in compiled.entries().iter().enumerate() {
- if scopes.as_slice() == [TreeScopeID::DOCUMENT]
- && !can_leave_scope
- && program_rules.iter().all(|&(rule, _)| {
- self.program_change_cannot_change_retained_winners(
- input,
- rule,
- entry,
- winner_program_version,
- RetainedWinnerProbe::AllResident { resident_count },
- )
- })
- {
- let dispatch = compiled.dispatch_key(entry);
- let rejected = match dispatch
- .has_selector_posting()
- .then(|| self.retained.facts.postings().lookup(dispatch))
- {
- Some(Lookup::Known(posting)) => {
- if self.retained.selector_truth_changes_active {
- let refreshes = &mut self.retained.selector_truth_changes.refreshes;
- for node in posting.candidates() {
- refreshes.push(SelectorTruthRefresh { node, rule: None });
- }
- }
- posting.len()
- }
- Some(Lookup::KnownAbsent) => 0,
- Some(Lookup::Missing(_)) | None => {
- if self.retained.selector_truth_changes_active {
- let refreshes = &mut self.retained.selector_truth_changes.refreshes;
- self.retained.retained_match_answers.for_each_answer_node(|node| {
- refreshes.push(SelectorTruthRefresh { node, rule: None });
- });
- }
- 1
- }
- };
- self.retained.counters.add(
- Counter::ProgramCandidatesRejectedByCascade,
- rejected as u64 * program_rules.len() as u64,
- );
- continue;
- }
- let dispatch = compiled.dispatch_key(entry);
- let posting = dispatch
- .has_selector_posting()
- .then(|| self.retained.facts.postings().lookup(dispatch));
- match posting {
- Some(Lookup::Known(posting)) => {
- // A subject bounded to a prefix or suffix of its sibling sequence is not
- // every element carrying its feature: `.row:first-child` names one row of a
- // table however many rows carry the class.
- let position = compiled.subject_position(entry_index);
- let posting_cardinality = posting.len();
- // An arriving subtree is already in the plan. When most of a posting belongs
- // to one, probe the smaller set of resident nodes instead of enumerating all
- // of the new nodes once for every arriving selector.
- let candidates: Vec<StyleNodeID> = match resident_nodes {
- Some(residents) => {
- let candidates: Vec<StyleNodeID> = if residents.len() < posting_cardinality {
- residents
- .iter()
- .copied()
- .filter(|&node| posting.contains(node))
- .collect()
- } else {
- posting
- .candidates()
- .filter(|node| residents.binary_search(node).is_ok())
- .collect()
- };
- candidates
- }
- None => posting.candidates().collect(),
- };
- for node in candidates {
- if bounded_by_scope && scopes.binary_search(&self.retained.tree.tree_scope(node)).is_err() {
- continue;
- }
- if !self.node_is_within_subject_position(node, position, subject_side) {
- continue;
- }
- if let Some((old_side, new_side)) = activation_fact_sides {
- let mut may_match = false;
- for side in [old_side, new_side].into_iter().flatten() {
- let view = self
- .transaction_fact_view
- .as_ref()
- .expect("exact activation filtering has a transaction fact view");
- match MatchEvaluator::new(&self.retained.tree, self.retained.facts.primary())
- .with_transaction_fact_view(view, side)
- .matches_entry(compiled, entry, node, &self.retained.counters)
- {
- Ok(false) => {}
- Ok(true) | Err(_) => {
- may_match = true;
- break;
- }
- }
- }
- if !may_match {
- if !matches!(key, InputKey::RuleField(..)) {
- self.retained.counters.bump(Counter::SheetChangeCandidatesRejected);
- }
- continue;
- }
- }
- if program_rules.iter().all(|&(rule, _)| {
- self.program_change_cannot_change_retained_winners(
- input,
- rule,
- entry,
- winner_program_version,
- RetainedWinnerProbe::Node(node),
- )
- }) {
- if self.retained.selector_truth_changes_active {
- self.retained
- .selector_truth_changes
- .refreshes
- .push(SelectorTruthRefresh { node, rule: None });
- }
- self.retained
- .counters
- .add(Counter::ProgramCandidatesRejectedByCascade, program_rules.len() as u64);
- continue;
- }
- // Program routing and DOM routing share one union of impact regions. If
- // another route already covered this node, its narrower attribution must
- // not hide the program rule from the retained-answer patch.
- if self.retained.selector_truth_changes_active && changes_selector_truth {
- for &(rule, _) in program_rules {
- self.retained
- .selector_truth_changes
- .refreshes
- .push(SelectorTruthRefresh {
- node,
- rule: Some((
- rule,
- self.retained.programs.entry_id(
- selector_program,
- u32::try_from(entry_index)
- .expect("selector program entry space exhausted"),
- ),
- )),
- });
- }
- }
- regions.add_if_not_covered(ImpactRegion::Node(node), &self.retained.tree);
- }
- }
- // Nothing to enumerate the subject by. It may still say where its subjects are:
- // `:root` names one element, and a child combinator names a parent that does
- // have a posting. Only when neither holds is the scope the answer, and a sheet
- // in a shadow root is bounded by the tree it decides in where the document's own
- // scope has no bound but the document.
- Some(Lookup::KnownAbsent) => continue,
- Some(Lookup::Missing(_)) | None => {
- if let Some(narrowed) = self.regions_from_subject_position(
- compiled,
- entry_index,
- document_root,
- bounded_by_scope.then_some(scopes.as_slice()),
- ) {
- for region in narrowed {
- regions.add_if_not_covered(region, &self.retained.tree);
- }
- continue;
- }
- match self.regions_reachable_from_scopes(
- &scopes,
- compiled.subject_can_leave_its_scope(),
- compiled.host_is_a_subject(),
- ) {
- Some(reachable) => {
- for region in reachable {
- regions.add_if_not_covered(region, &self.retained.tree);
- }
- }
- None => {
- regions.widen_to_document(&self.retained.counters);
- return;
- }
- }
- }
- }
- }
- first_program_rule = end_program_rule;
- }
- }
-}
diff --git a/Libraries/LibWeb/Rust/src/css/style/shared_vector.rs b/Libraries/LibWeb/Rust/src/css/style/shared_vector.rs
deleted file mode 100644
index b89c483bc79..00000000000
--- a/Libraries/LibWeb/Rust/src/css/style/shared_vector.rs
+++ /dev/null
@@ -1,276 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-use super::fast_hash::fast_hasher;
-use super::weak_pool::WeakPool;
-use std::hash::{Hash, Hasher};
-use std::ops::Deref;
-use std::sync::Arc;
-
-/// A pool of shared vector contents of one element type.
-pub(super) struct SharedVectorPool<T: 'static> {
- pool: WeakPool<SharedVectorData<T>>,
-}
-
-impl<T> Default for SharedVectorPool<T> {
- fn default() -> Self {
- Self {
- pool: WeakPool::default(),
- }
- }
-}
-
-struct SharedVectorData<T: 'static> {
- values: Vec<T>,
- hash: u64,
-}
-
-enum Storage<T: 'static> {
- Owned(Vec<T>),
- Shared(Arc<SharedVectorData<T>>),
-}
-
-/// A flat vector that can share equal contents between documents. Its allocation is charged
-/// once while shared; nested payloads, if any, remain their owners' accounting responsibility.
-pub(super) struct SharedVector<T: 'static> {
- storage: Storage<T>,
-}
-
-impl<T> Default for SharedVector<T> {
- fn default() -> Self {
- Self {
- storage: Storage::Owned(Vec::new()),
- }
- }
-}
-
-impl<T: std::fmt::Debug> std::fmt::Debug for SharedVector<T> {
- fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
- std::fmt::Debug::fmt(self.as_slice(), formatter)
- }
-}
-
-impl<T: Clone> Clone for SharedVector<T> {
- fn clone(&self) -> Self {
- Self {
- storage: match &self.storage {
- Storage::Owned(values) => Storage::Owned(values.clone()),
- Storage::Shared(data) => Storage::Shared(Arc::clone(data)),
- },
- }
- }
-}
-
-impl<T: PartialEq> PartialEq for SharedVector<T> {
- fn eq(&self, other: &Self) -> bool {
- if let (Storage::Shared(first), Storage::Shared(second)) = (&self.storage, &other.storage)
- && Arc::ptr_eq(first, second)
- {
- return true;
- }
- self.as_slice() == other.as_slice()
- }
-}
-
-impl<T: Eq> Eq for SharedVector<T> {}
-
-impl<T: Hash> Hash for SharedVector<T> {
- fn hash<H: Hasher>(&self, state: &mut H) {
- // Frozen vectors already computed this content hash when entering their pool.
- // Hash owned vectors the same way so equal storage forms always hash alike.
- let hash = match &self.storage {
- Storage::Shared(data) => data.hash,
- Storage::Owned(values) => {
- let mut hasher = fast_hasher();
- values.hash(&mut hasher);
- hasher.finish()
- }
- };
- hash.hash(state);
- }
-}
-
-impl<T> FromIterator<T> for SharedVector<T> {
- fn from_iter<I: IntoIterator<Item = T>>(iter: I) -> Self {
- Self {
- storage: Storage::Owned(iter.into_iter().collect()),
- }
- }
-}
-
-impl<T> Deref for SharedVector<T> {
- type Target = Vec<T>;
-
- fn deref(&self) -> &Self::Target {
- match &self.storage {
- Storage::Owned(values) => values,
- Storage::Shared(data) => &data.values,
- }
- }
-}
-
-impl<T: Clone> SharedVector<T> {
- pub(super) fn make_mut(&mut self) -> &mut Vec<T> {
- if matches!(self.storage, Storage::Shared(_)) {
- let Storage::Shared(data) = std::mem::replace(&mut self.storage, Storage::Owned(Vec::new())) else {
- unreachable!()
- };
- let values = match Arc::try_unwrap(data) {
- Ok(mut data) => std::mem::take(&mut data.values),
- Err(data) => data.values.clone(),
- };
- self.storage = Storage::Owned(values);
- }
- let Storage::Owned(values) = &mut self.storage else {
- unreachable!()
- };
- values
- }
-
- pub(super) fn clear(&mut self) {
- match &mut self.storage {
- Storage::Owned(values) => values.clear(),
- Storage::Shared(_) => self.storage = Storage::Owned(Vec::new()),
- }
- }
-}
-
-impl<T: Clone + Eq + Hash> SharedVector<T> {
- pub(super) fn share(&mut self, pool: &mut SharedVectorPool<T>) {
- let Storage::Owned(values) = &self.storage else { return };
- if values.is_empty() {
- return;
- }
- let mut hasher = fast_hasher();
- values.hash(&mut hasher);
- let hash = hasher.finish();
- let Storage::Owned(values) = std::mem::replace(&mut self.storage, Storage::Owned(Vec::new())) else {
- unreachable!()
- };
- let shared = match pool.pool.find(hash, |data| data.values == values) {
- Some(found) => found,
- None => {
- let shared = Arc::new(SharedVectorData { values, hash });
- pool.pool.insert(hash, &shared);
- shared
- }
- };
- self.storage = Storage::Shared(shared);
- }
-}
-
-const SHARED_VECTOR_PAGE_SIZE: usize = 128;
-
-/// An append-only column whose equal immutable pages can be shared between snapshots.
-#[derive(Clone)]
-pub(super) struct PagedSharedVector<T: 'static> {
- pages: Vec<SharedVector<T>>,
- len: usize,
-}
-
-impl<T> Default for PagedSharedVector<T> {
- fn default() -> Self {
- Self {
- pages: Vec::new(),
- len: 0,
- }
- }
-}
-
-impl<T> PagedSharedVector<T> {
- pub(super) fn len(&self) -> usize {
- self.len
- }
-
- pub(super) fn iter(&self) -> impl Iterator<Item = &T> {
- self.pages.iter().flat_map(|page| page.iter())
- }
-
- pub(super) fn range(&self, range: std::ops::Range<usize>) -> impl Iterator<Item = &T> {
- assert!(range.start <= range.end && range.end <= self.len);
- range.map(|index| &self[index])
- }
-
- pub(super) fn shrink_to_fit(&mut self) {
- self.pages.shrink_to_fit();
- for page in &mut self.pages {
- if let Storage::Owned(values) = &mut page.storage {
- values.shrink_to_fit();
- }
- }
- }
-}
-
-impl<T: Clone> PagedSharedVector<T> {
- pub(super) fn push(&mut self, value: T) {
- let next_len = self.len.checked_add(1).expect("shared column identity space exhausted");
- if self.len.is_multiple_of(SHARED_VECTOR_PAGE_SIZE) {
- self.pages.push(SharedVector {
- storage: Storage::Owned(Vec::with_capacity(SHARED_VECTOR_PAGE_SIZE)),
- });
- }
- let values = self.pages.last_mut().unwrap().make_mut();
- values.reserve_exact(SHARED_VECTOR_PAGE_SIZE - values.len());
- values.push(value);
- self.len = next_len;
- }
-}
-
-impl<T: Clone> Extend<T> for PagedSharedVector<T> {
- fn extend<I: IntoIterator<Item = T>>(&mut self, iter: I) {
- for value in iter {
- self.push(value);
- }
- }
-}
-
-impl<T> std::ops::Index<usize> for PagedSharedVector<T> {
- type Output = T;
-
- fn index(&self, index: usize) -> &T {
- &self.pages[index / SHARED_VECTOR_PAGE_SIZE][index % SHARED_VECTOR_PAGE_SIZE]
- }
-}
-
-impl<T: Clone + Eq + Hash> PagedSharedVector<T> {
- pub(super) fn share(&mut self, pool: &mut SharedVectorPool<T>) {
- for page in &mut self.pages {
- page.share(pool);
- }
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::*;
-
- #[test]
- fn equal_vectors_share_and_mutation_detaches_without_changing_other_owners() {
- let mut pool = SharedVectorPool::default();
- let mut make_vector = || {
- let mut vector = SharedVector::default();
- vector.make_mut().extend([1, 2, 3]);
- vector.share(&mut pool);
- vector
- };
- let first = make_vector();
- let mut second = make_vector();
- let (Storage::Shared(left), Storage::Shared(right)) = (&first.storage, &second.storage) else {
- panic!("equal vectors should be shared");
- };
- assert!(Arc::ptr_eq(left, right));
- second.make_mut()[0] = 9;
- assert_eq!(first.as_slice(), &[1, 2, 3]);
- assert_eq!(second.as_slice(), &[9, 2, 3]);
- second.share(&mut pool);
- let previous_buffer = second.as_ptr();
- // The pool owns only a weak reference: the last document can recover its buffer.
- assert_eq!(second.make_mut().as_ptr(), previous_buffer);
- second.clear();
- assert!(second.is_empty());
- assert_eq!(first.as_slice(), &[1, 2, 3]);
- }
-}
diff --git a/Libraries/LibWeb/Rust/src/css/style/transaction.rs b/Libraries/LibWeb/Rust/src/css/style/transaction.rs
deleted file mode 100644
index 02905454b3e..00000000000
--- a/Libraries/LibWeb/Rust/src/css/style/transaction.rs
+++ /dev/null
@@ -1,1207 +0,0 @@
-/*
- * Copyright (c) 2026-present, the Ladybird developers.
- *
- * SPDX-License-Identifier: BSD-2-Clause
- */
-
-//! Typed semantic inputs and the normalization journal that collapses them. Typing matters:
-//! treating every change as a generic version bump would move work from mutation time into an
-//! unnecessarily broad lazy validation later, which is exactly the amplification this engine
-//! exists to avoid.
-
-use super::fast_hash::FastMap as HashMap;
-
-use super::index::FeatureValue;
-use super::index::LocalFeatureKey;
-use super::index::StyleAtomID;
-use super::index::StyleNodeFacts;
-use super::instrumentation::Counter;
-use super::instrumentation::Counters;
-use super::program::ActivationPredicateID;
-use super::program::CascadeLayerID;
-use super::program::DeclarationBlockID;
-use super::program::RuleID;
-use super::program::SelectorProgramID;
-use super::program::SheetID;
-use super::program::StyleScopeID;
-use super::tree::StyleNodeID;
-use super::tree::TreeScopeID;
-
-/// Version of the attached stylesheet program: compiled selectors, declarations, conditions, and
-/// their attachment to style scopes.
-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, PartialOrd, Ord)]
-pub struct ProgramVersion(pub u64);
-
-/// Monotonic identity of one normalized style transaction published by a document.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]
-pub struct StyleTransactionVersion(pub u64);
-
-// -- Typed semantic inputs -------------------------------------------------------------------
-
-// An element or document state fact.
-//
-// States are semantic facts rather than bespoke invalidation entry points, so a transition
-// publishes an old and a new value and only operators depending on that state receive it.
-//
-// Every boolean pseudo-class the parser can produce has an entry here. That exhaustiveness is the
-// point: a pseudo-class with no fact would compile to something the engine cannot route, and a
-// selector that cannot be routed cannot be invalidated. Facts whose value is a parameter rather
-// than a boolean - `:dir()`, `:lang()`, `:state()`, `:heading()` - are operators instead, because
-// a bitset cannot carry their argument.
-include!(concat!(env!("OUT_DIR"), "/style_state_fact_generated.rs"));
-
-impl StateFact {
- /// Whether the elements in this state are enumerated by a feature posting.
- ///
- /// A state a user interaction puts an element in holds on a handful of elements at a time: the
- /// focused element and the ancestors focus is within, the hovered chain, the activated chain,
- /// the top layer. A subject compound carrying nothing but such a state names its subjects as
- /// well as an ID does, so a change elsewhere in the selector reaches those subjects rather than
- /// every element its combinators could lead to. A state an element's nature decides, such as
- /// being a link or enabled, holds on most of a document and is left to the compound's names.
- #[must_use]
- pub fn has_selector_posting(self) -> bool {
- matches!(
- self,
- Self::Active
- | Self::Focus
- | Self::FocusVisible
- | Self::FocusWithin
- | Self::Fullscreen
- | Self::Hover
- | Self::Modal
- | Self::PictureInPicture
- | Self::PopoverOpen
- | Self::Target
- )
- }
-}
-
-/// Declarations sourced from one style node rather than a stylesheet rule. Each kind keeps its
-/// language-defined cascade placement: presentational hints do not masquerade as inline style, and
-/// none of them enter the selector program merely because their source syntax is an attribute.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
-#[repr(u8)]
-pub enum ElementDeclarationKind {
- /// The `style` attribute.
- InlineStyle,
- /// An HTML presentational-hint attribute.
- PresentationalHint,
- /// An SVG presentation attribute such as `fill` or `stroke`.
- SvgPresentationAttribute,
-}
-
-impl ElementDeclarationKind {
- pub const COUNT: usize = Self::SvgPresentationAttribute as usize + 1;
- pub const ALL: [Self; Self::COUNT] = [
- Self::InlineStyle,
- Self::PresentationalHint,
- Self::SvgPresentationAttribute,
- ];
-
- #[must_use]
- pub const fn index(self) -> usize {
- self as usize
- }
-}
-
-/// Which field of a rule an edit touched. Splitting the fields is what lets a declaration edit
-/// reuse selector truth, a condition edit reuse both selector truth and declarations, and a layer
-/// move reuse everything except cascade priority.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
-pub enum RuleField {
- /// Whether the rule is attached to its sheet at all.
- Existence,
- Selector,
- Declarations,
- Activation,
- Layer,
- Scope,
-}
-
-/// A cascade topology axis. A change here alters priority comparisons for declarations that
-/// already matched; it never invalidates selector truth.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
-pub enum TopologyAxis {
- /// Layer order within one style scope. A layer name belongs to the tree scope its sheet is
- /// attached to, so declaring one in a shadow root reorders nothing outside it.
- LayerOrder(TreeScopeID),
- /// Sheet order within one style scope. Reordering sheets changes cascade priority for
- /// declarations that already matched; it never changes which elements they match.
- SheetOrder(TreeScopeID),
-}
-
-/// The tree relations of one style node, as of one side of a mutation.
-///
-/// This is the minimum old-side information the applicable transpose rules need. It is not a
-/// traversable old DOM and does not copy unchanged descendant fields: old-side facts exist to
-/// establish a complete impact region, not to reconstruct history.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub struct TreeRelations {
- pub parent: Option<StyleNodeID>,
- pub previous_element_sibling: Option<StyleNodeID>,
- pub next_element_sibling: Option<StyleNodeID>,
- pub tree_scope: TreeScopeID,
- pub assigned_slot: Option<StyleNodeID>,
-}
-
-impl TreeRelations {
- /// Relations of a node with no parent, slot, or host: the shape a node has before insertion and
- /// after removal.
- #[must_use]
- #[cfg(test)]
- pub fn detached(tree_scope: TreeScopeID) -> Self {
- Self {
- parent: None,
- previous_element_sibling: None,
- next_element_sibling: None,
- tree_scope,
- assigned_slot: None,
- }
- }
-}
-
-macro_rules! define_input_kinds {
- ($($variant:ident => $counter:expr,)+) => {
- /// The typed kind of a semantic input. Coarsening and routing are per kind, so a child-list
- /// mutation never consults programs that depend only on an environment predicate.
- #[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
- #[repr(usize)]
- pub enum InputKind {
- $($variant,)+
- }
-
- pub const INPUT_KIND_COUNT: usize = 0 $(+ { let _ = InputKind::$variant; 1 })+;
-
- static INPUT_KIND_VALUES: [InputKind; INPUT_KIND_COUNT] = [$(InputKind::$variant,)+];
-
- impl InputKind {
- #[must_use]
- pub fn index(self) -> usize {
- self as usize
- }
-
- #[must_use]
- pub fn counter(self) -> Option<Counter> {
- match self {
- $(Self::$variant => $counter,)+
- }
- }
- }
- };
-}
-
-define_input_kinds! {
- TreeRelations => Some(Counter::TreeDeltas),
- LocalFeature => Some(Counter::LocalFeatureDeltas),
- State => Some(Counter::StateDeltas),
- ElementDeclaration => Some(Counter::ElementDeclarationDeltas),
- ElementStyleInput => None,
- Program => Some(Counter::ProgramDeltas),
- CascadeTopology => Some(Counter::CascadeTopologyDeltas),
- Environment => Some(Counter::EnvironmentDeltas),
-}
-
-/// A journal key: a style-node identity plus the typed fact or relation it describes.
-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
-pub enum InputKey {
- TreeRelations(StyleNodeID),
- LocalFeature(StyleNodeID, LocalFeatureKey),
- State(StyleNodeID, StateFact),
- ElementDeclaration(StyleNodeID, ElementDeclarationKind),
- /// A non-selector style input owned by the element changed. This is an edge-triggered action,
- /// not retained fact state; its journal value says only whether the action is pending.
- ElementStyleInput(StyleNodeID),
- /// One sheet's attachment to one style scope.
- SheetAttachment(SheetID, TreeScopeID),
- /// Whether a sheet's rules are active at all.
- SheetActivation(SheetID),
- RuleField(RuleID, RuleField),
- /// A registration made through `CSS.registerProperty()`, which has no stylesheet rule identity.
- CustomPropertyRegistration(StyleAtomID),
- CascadeTopology(TopologyAxis),
-}
-
-pub const STYLE_REACTION_PUBLISHED_STYLE: u8 = 1 << 0;
-pub const STYLE_REACTION_RECOMPUTE_STYLE: u8 = 1 << 1;
-pub const STYLE_REACTION_INHERITED_STYLE: u8 = 1 << 2;
-pub const STYLE_REACTION_INHERITED_CUSTOM_PROPERTIES: u8 = 1 << 3;
-pub const STYLE_REACTION_RECOMPUTE_DESCENDANT_STYLES: u8 = 1 << 4;
-pub const STYLE_REACTION_ANCESTOR_BECAME_VISIBLE: u8 = 1 << 5;
-pub const STYLE_REACTION_PSEUDO_INPUTS_MAY_HAVE_CHANGED: u8 = 1 << 6;
-/// The element's font environment moved: a face its font cascade names became available, failed
-/// or changed. The `@font-face` table that decides the cascade is published to the engine and
-/// versioned by the font-environment generation.
-pub const STYLE_REACTION_FONT_INPUTS_CHANGED: u8 = 1 << 7;
-
-impl InputKey {
- #[must_use]
- pub fn kind(self) -> InputKind {
- match self {
- Self::TreeRelations(..) => InputKind::TreeRelations,
- Self::LocalFeature(..) => InputKind::LocalFeature,
- Self::State(..) => InputKind::State,
- Self::ElementDeclaration(..) => InputKind::ElementDeclaration,
- Self::ElementStyleInput(..) => InputKind::ElementStyleInput,
- Self::SheetAttachment(..)
- | Self::SheetActivation(..)
- | Self::RuleField(..)
- | Self::CustomPropertyRegistration(..) => InputKind::Program,
- Self::CascadeTopology(..) => InputKind::CascadeTopology,
- }
- }
-
- /// The style node this key is about, for keys that name one.
- #[must_use]
- pub fn style_node(self) -> Option<StyleNodeID> {
- match self {
- Self::TreeRelations(node)
- | Self::LocalFeature(node, _)
- | Self::State(node, _)
- | Self::ElementDeclaration(node, _)
- | Self::ElementStyleInput(node) => Some(node),
- Self::SheetAttachment(..)
- | Self::SheetActivation(..)
- | Self::RuleField(..)
- | Self::CustomPropertyRegistration(..)
- | Self::CascadeTopology(..) => None,
- }
- }
-
- /// The tree scope whose program this key changes, for keys that name one.
- #[must_use]
- pub fn program_tree_scope(self) -> Option<TreeScopeID> {
- match self {
- Self::SheetAttachment(_, tree_scope)
- | Self::CascadeTopology(TopologyAxis::SheetOrder(tree_scope) | TopologyAxis::LayerOrder(tree_scope)) => {
- Some(tree_scope)
- }
- _ => None,
- }
- }
-}
-
-/// The value of a journal key on one side of a mutation.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub enum InputValue {
- /// `None` means the node is not participating in the tree on that side.
- TreeRelations(Option<TreeRelations>),
- Feature(FeatureValue),
- State(bool),
- /// `None` means no declaration block of that kind exists on that side.
- ElementDeclaration(Option<DeclarationBlockID>),
- ElementStyleInput {
- reaction: u8,
- inherited_style_groups: u8,
- },
- /// Whether a sheet is attached to a scope, whether it is enabled, or whether a rule is
- /// attached to its sheet. Position within a scope is not encoded here: an order token is an
- /// identity whose numeric label is deliberately meaningless, and a position index is not stable
- /// against other sheets moving. Reordering publishes a cascade topology change instead.
- Flag(bool),
- SelectorProgram(Option<SelectorProgramID>),
- RuleDeclarations(Option<DeclarationBlockID>),
- ActivationPredicate(Option<ActivationPredicateID>),
- Layer(CascadeLayerID),
- Scope(StyleScopeID),
- /// The version of one topology axis.
- Topology(u64),
-}
-
-impl InputValue {
- #[must_use]
- fn kind(self) -> InputKind {
- match self {
- Self::TreeRelations(_) => InputKind::TreeRelations,
- Self::Feature(_) => InputKind::LocalFeature,
- Self::State(_) => InputKind::State,
- Self::ElementDeclaration(_) => InputKind::ElementDeclaration,
- Self::ElementStyleInput { .. } => InputKind::ElementStyleInput,
- Self::Flag(_)
- | Self::SelectorProgram(_)
- | Self::RuleDeclarations(_)
- | Self::ActivationPredicate(_)
- | Self::Layer(_)
- | Self::Scope(_) => InputKind::Program,
- Self::Topology(_) => InputKind::CascadeTopology,
- }
- }
-}
-
-/// Asks exact matching to read final authoritative facts for one input kind throughout a complete
-/// scope and compare them against last committed outputs. This is still an exact path that
-/// emits only actual semantic changes - not a conservative restyle. A marker can represent an input
-/// that is inherently scope-wide, or replace fine-grained entries which exceeded their scratch
-/// journal capacity.
-///
-/// The marker currently covers the whole document for its input kind. Narrowing it to a proven
-/// common ancestor of the coarsened keys is an optimization, not a correctness requirement: a
-/// larger region is always safe, an unknown one never is.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub struct CompleteScopeMarker {
- pub kind: InputKind,
-}
-
-/// One normalized input change: the pre-transaction value and the final pending value.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub struct NormalizedInput {
- pub key: InputKey,
- pub old: InputValue,
- pub new: InputValue,
-}
-
-/// One rule-side row produced by changing an input of the active-rule-match join.
-///
-/// Selector, attachment, and activation changes alter which selector truth joins the rule.
-/// Declaration and priority changes retain that truth but alter its downstream cascade row.
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub struct ProgramJoinDelta {
- pub input: InputKey,
- pub rule: RuleID,
- pub before_program: Option<SelectorProgramID>,
- pub after_program: Option<SelectorProgramID>,
- pub before_contributes: bool,
- pub after_contributes: bool,
- pub kind: ProgramJoinDeltaKind,
-}
-
-#[derive(Clone, Copy, Debug, PartialEq, Eq)]
-pub enum ProgramJoinDeltaKind {
- ActiveRuleMatch,
- Declarations,
- Priority,
-}
-
-/// The original and final declaration inventories of one edited rule.
-///
-/// Declaration block identities normalize the semantic input, while these property rows retain
-/// the exact key range needed by incremental cascade maintenance.
-#[derive(Debug)]
-pub struct RuleDeclarationChange {
- pub rule: RuleID,
- pub old_properties: Vec<u16>,
- pub new_properties: Vec<u16>,
- /// Whether the custom properties the rule declares moved, which no winner shows.
- pub custom_declarations_changed: bool,
-}
-
-/// The normalized result of one transaction boundary, in deterministic key order.
-#[derive(Default)]
-#[must_use]
-pub struct StyleTransaction {
- pub inputs: Vec<NormalizedInput>,
- pub markers: Vec<CompleteScopeMarker>,
- pub program_joins: Vec<ProgramJoinDelta>,
- pub rule_declaration_changes: Vec<RuleDeclarationChange>,
- pub program_base_version: Option<ProgramVersion>,
- pub(crate) before_facts: Option<StyleNodeFacts>,
-}
-
-impl StyleTransaction {
- #[must_use]
- pub fn is_empty(&self) -> bool {
- self.inputs.is_empty() && self.markers.is_empty()
- }
-
- /// Whether any marker replaced fine-grained inputs whose exact identities are unavailable.
- #[must_use]
- pub fn has_coarsened_markers(&self) -> bool {
- self.markers.iter().any(|marker| marker.kind != InputKind::Environment)
- }
-
- pub fn install_program_joins(&mut self, joins: Vec<ProgramJoinDelta>) {
- debug_assert!(self.program_joins.is_empty());
-
- self.program_joins = joins;
- }
-
- pub fn install_rule_declaration_changes(&mut self, changes: Vec<RuleDeclarationChange>) {
- debug_assert!(self.rule_declaration_changes.is_empty());
-
- self.rule_declaration_changes = changes;
- }
-
- pub fn install_before_facts(&mut self, before_facts: StyleNodeFacts) {
- debug_assert!(self.before_facts.is_none());
-
- self.before_facts = Some(before_facts);
- }
-
- pub fn take_before_facts(&mut self) -> Option<StyleNodeFacts> {
- self.before_facts.take()
- }
-
- #[must_use]
- pub fn program_joins_for(&self, input: InputKey) -> &[ProgramJoinDelta] {
- let first = self.program_joins.partition_point(|delta| delta.input < input);
- let count = self.program_joins[first..].partition_point(|delta| delta.input == input);
- &self.program_joins[first..first + count]
- }
-
- /// Release the transaction's scratch charge. Called once the transaction has been consumed.
- pub fn release(self) {}
-}
-
-/// Accumulates pending input changes and normalizes them at a transaction boundary.
-///
-/// Script performs many mutations before style is observed, so the raw mutation count is not the
-/// default work multiplier. Adding then removing the same class produces no final delta; changing a
-/// declaration three times retains only the old and final blocks; moving a subtree twice retains
-/// only its original and final relationships.
-///
-/// Normalization never combines changes across a required observation boundary. An operation whose
-/// Web-platform semantics force synchronous observation drains the journal first.
-#[derive(Clone, Default)]
-pub struct NormalizationJournal {
- entries: HashMap<InputKey, (InputValue, InputValue)>,
- markers: Vec<CompleteScopeMarker>,
- covered: [bool; INPUT_KIND_COUNT],
- document_entry_limit: usize,
- #[cfg(test)]
- entry_limit_override: Option<usize>,
-}
-
-const JOURNAL_ENTRIES_PER_CONNECTED_ELEMENT: usize = 4;
-const MIN_JOURNAL_ENTRY_LIMIT: usize = 64 * 1024;
-const MAX_JOURNAL_ENTRY_LIMIT: usize = 512 * 1024;
-/// Fold a newer value for a key into its pending `(old, new)` entry, and return whether the
-/// pending change now cancels out against the pre-transaction value. An element style input
-/// accumulates every reaction requested for it instead.
-fn fold_into_pending(entry: &mut (InputValue, InputValue), new: InputValue) -> bool {
- if let (
- InputValue::ElementStyleInput {
- reaction: pending_reaction,
- inherited_style_groups: pending_inherited_style_groups,
- },
- InputValue::ElementStyleInput {
- reaction: new_reaction,
- inherited_style_groups: new_inherited_style_groups,
- },
- ) = (&mut entry.1, new)
- {
- *pending_reaction |= new_reaction;
- *pending_inherited_style_groups |= new_inherited_style_groups;
- return false;
- }
- if entry.0 == new {
- return true;
- }
- entry.1 = new;
- false
-}
-
-impl NormalizationJournal {
- #[must_use]
- pub fn new() -> Self {
- Self::default()
- }
-
- /// Fine-grained keys currently pending. Kinds replaced by a complete-scope marker are not
- /// counted here, because their individual keys no longer exist.
- #[must_use]
- #[cfg(test)]
- pub fn len(&self) -> usize {
- self.entries.len()
- }
-
- #[must_use]
- pub fn is_empty(&self) -> bool {
- self.entries.is_empty() && self.markers.is_empty()
- }
-
- #[must_use]
- pub fn markers(&self) -> &[CompleteScopeMarker] {
- &self.markers
- }
-
- /// The normalized view of the fine-grained inputs which are still pending.
- pub(super) fn inputs(&self) -> impl Iterator<Item = NormalizedInput> + '_ {
- self.entries
- .iter()
- .map(|(&key, &(old, new))| NormalizedInput { key, old, new })
- }
-
- /// Fold a newer journal into this one without counting its already-recorded inputs a second
- /// time. This retains the original value before either journal and the final value after both.
- /// A complete-scope marker of either journal covers the entries of its kind from both.
- pub(super) fn absorb_newer(&mut self, newer: &mut Self, counters: &Counters) {
- for marker in std::mem::take(&mut newer.markers) {
- self.install_marker(marker.kind);
- }
- let newer_entries = std::mem::take(&mut newer.entries);
-
- newer.covered = [false; INPUT_KIND_COUNT];
-
- for (key, (old, new)) in newer_entries {
- if self.covered[key.kind().index()] {
- continue;
- }
- if let Some(entry) = self.entries.get_mut(&key) {
- if fold_into_pending(entry, new) {
- self.entries.remove(&key);
- counters.bump(Counter::JournalCancellations);
- }
- continue;
- }
- if old == new || !self.make_room_for_one(key.kind(), counters) {
- continue;
- }
- self.entries.insert(key, (old, new));
- }
- }
-
- #[must_use]
- pub fn contains_only_element_style_inputs(&self) -> bool {
- self.markers.is_empty()
- && !self.entries.is_empty()
- && self
- .entries
- .keys()
- .all(|key| matches!(key, InputKey::ElementStyleInput(..)))
- }
-
- #[inline(never)]
- fn entry_limit(&self) -> usize {
- #[cfg(test)]
- if let Some(limit) = self.entry_limit_override {
- return limit;
- }
- self.document_entry_limit.max(MIN_JOURNAL_ENTRY_LIMIT)
- }
-
- pub(super) fn set_document_entry_limit(&mut self, connected_element_count: u32) {
- self.document_entry_limit = JOURNAL_ENTRIES_PER_CONNECTED_ELEMENT
- .saturating_mul(connected_element_count as usize)
- .clamp(MIN_JOURNAL_ENTRY_LIMIT, MAX_JOURNAL_ENTRY_LIMIT);
- }
-
- /// The pre-transaction value already journalled for `key`, if anything has been recorded for it.
- ///
- /// A caller that needs to know whether its own record will cancel has to ask before making it:
- /// cancellation means the input is back where the transaction found it, which for some inputs is
- /// not the same as nothing having happened.
- #[must_use]
- pub fn pending_old(&self, key: InputKey) -> Option<InputValue> {
- self.entries.get(&key).map(|entry| entry.0)
- }
-
- /// A demand for one node's record has answered that node's inputs. Every other entry stays
- /// for the next transaction, including entries of the same input kind.
- pub(super) fn acknowledge_node(&mut self, node: StyleNodeID) {
- self.entries.retain(|key, _| key.style_node() != Some(node));
- }
-
- /// Record one input change. `old` is the value before this mutation and is kept only if this is
- /// the first record for `key`; `new` replaces any previously pending value.
- #[inline]
- pub fn record(&mut self, key: InputKey, old: InputValue, new: InputValue, counters: &Counters) {
- let kind = key.kind();
- assert_eq!(old.kind(), kind, "journal value does not match its key");
- assert_eq!(new.kind(), kind, "journal value does not match its key");
-
- counters.bump(Counter::RawMutationRecords);
- if let Some(counter) = kind.counter() {
- counters.bump(counter);
- }
-
- // Once a kind has been coarsened, its individual keys carry no further information: the
- // marker's region already contains them. This is what bounds journal memory against a
- // pathological script, which can force broad discovery but not unbounded retention.
- if self.covered[kind.index()] {
- return;
- }
-
- if let Some(entry) = self.entries.get_mut(&key) {
- if fold_into_pending(entry, new) {
- self.entries.remove(&key);
- counters.bump(Counter::JournalCancellations);
- }
- return;
- }
-
- if old == new {
- return;
- }
- if !self.make_room_for_one(kind, counters) {
- return;
- }
- self.entries.insert(key, (old, new));
- }
-
- /// Record one input action whose semantic scope is already the complete document.
- pub fn record_complete_scope_action(&mut self, kind: InputKind, counters: &Counters) {
- counters.bump(Counter::RawMutationRecords);
- if let Some(counter) = kind.counter() {
- counters.bump(counter);
- }
- self.install_marker(kind);
- }
-
- /// Normalize and drain. The result is sorted by key so that downstream planning is
- /// deterministic regardless of mutation arrival order.
- pub fn take_transaction(&mut self, counters: &Counters) -> StyleTransaction {
- let mut inputs: Vec<NormalizedInput> = self
- .entries
- .drain()
- .map(|(key, (old, new))| NormalizedInput { key, old, new })
- .collect();
- inputs.sort_unstable_by_key(|input| input.key);
-
- // Facts are normally folded as they are recorded after an element's tree arrival. The DOM
- // publishes an element's immutable tag before connecting it, though, and other producers
- // are allowed to announce facts in either order. Once the complete transaction is visible,
- // fold both orders to the same arriving-facts key: the tree delta already puts the subtree
- // in the plan, while that one key routes the final facts to relational and sibling
- // selectors outside it.
- // Tree-relation keys are unique and already sorted by node in the normalized inputs.
- let arriving_nodes: Vec<StyleNodeID> = inputs
- .iter()
- .filter_map(|input| match (input.key, input.old, input.new) {
- (
- InputKey::TreeRelations(node),
- InputValue::TreeRelations(None),
- InputValue::TreeRelations(Some(_)),
- ) => Some(node),
- _ => None,
- })
- .collect();
- if !arriving_nodes.is_empty() {
- inputs.retain(|input| {
- let (InputKey::LocalFeature(node, _) | InputKey::State(node, _)) = input.key else {
- return true;
- };
- if arriving_nodes.binary_search(&node).is_err() {
- return true;
- }
- if !matches!(input.key, InputKey::LocalFeature(_, LocalFeatureKey::ArrivingFacts)) {
- counters.bump(Counter::ArrivingNodeFactsFolded);
- }
- false
- });
- inputs.extend(arriving_nodes.into_iter().map(|node| NormalizedInput {
- key: InputKey::LocalFeature(node, LocalFeatureKey::ArrivingFacts),
- old: InputValue::Feature(FeatureValue::Absent),
- new: InputValue::Feature(FeatureValue::Present),
- }));
- inputs.sort_unstable_by_key(|input| input.key);
- }
-
- counters.add(Counter::NormalizedUniqueKeys, inputs.len() as u64);
-
- let markers = std::mem::take(&mut self.markers);
- self.covered = [false; INPUT_KIND_COUNT];
- self.entries.shrink_to_fit();
-
- StyleTransaction {
- inputs,
- markers,
- program_joins: Vec::new(),
- rule_declaration_changes: Vec::new(),
- program_base_version: None,
- before_facts: None,
- }
- }
-
- /// Ensure one more fine-grained entry may be inserted, coarsening until it fits. Returns false
- /// when the entry must not be journalled at all, in which case its kind has been marked.
- fn make_room_for_one(&mut self, kind: InputKind, counters: &Counters) -> bool {
- if self.entries.len() < self.entries.capacity() {
- return true;
- }
- self.make_room_for_one_slow(kind, counters)
- }
-
- #[cold]
- #[inline(never)]
- fn make_room_for_one_slow(&mut self, kind: InputKind, counters: &Counters) -> bool {
- while self.entries.len() >= self.entries.capacity() {
- let grown_capacity = self.entries.capacity() + self.entries.capacity().max(4);
- if grown_capacity <= self.entry_limit() {
- return true;
- }
- if !self.coarsen_largest_kind(counters) {
- if kind == InputKind::ElementStyleInput {
- return true;
- }
- // Nothing left to coarsen: mark this kind's scope rather than journalling it.
- if self.install_marker(kind) {
- counters.bump(Counter::CoarsenedScopeMarkers);
- }
- return false;
- }
- if self.covered[kind.index()] {
- return false;
- }
- }
- true
- }
-
- /// Replace every fine-grained entry of the most numerous remaining kind with one typed
- /// complete-scope marker. Coarsening the largest kind first keeps a burst of class mutations
- /// from also coarsening unrelated tree relations.
- fn coarsen_largest_kind(&mut self, counters: &Counters) -> bool {
- let mut counts = [0_usize; INPUT_KIND_COUNT];
- for key in self.entries.keys() {
- counts[key.kind().index()] += 1;
- }
- let Some((index, _)) = counts
- .iter()
- .enumerate()
- .filter(|&(index, &count)| {
- count > 0 && !self.covered[index] && INPUT_KIND_VALUES[index] != InputKind::ElementStyleInput
- })
- .max_by_key(|&(_, &count)| count)
- else {
- return false;
- };
- if self.install_marker(INPUT_KIND_VALUES[index]) {
- counters.bump(Counter::CoarsenedScopeMarkers);
- }
- true
- }
-
- fn install_marker(&mut self, kind: InputKind) -> bool {
- if self.covered[kind.index()] {
- return false;
- }
- self.covered[kind.index()] = true;
- self.entries.retain(|key, _| key.kind() != kind);
- self.entries.shrink_to_fit();
- self.markers.push(CompleteScopeMarker { kind });
- true
- }
-}
-
-#[cfg(test)]
-mod tests {
- use super::super::index::StyleAtomID;
- use super::*;
-
- // -- Normalization journal ---------------------------------------------------------------
-
- struct JournalFixture {
- counters: Counters,
- journal: NormalizationJournal,
- }
-
- impl JournalFixture {
- fn new() -> Self {
- Self {
- counters: Counters::new(),
- journal: NormalizationJournal::new(),
- }
- }
-
- fn with_journal_entry_limit(entries: usize) -> Self {
- let mut fixture = Self::new();
- fixture.journal.entry_limit_override = Some(entries);
- fixture
- }
-
- fn record(&mut self, key: InputKey, old: InputValue, new: InputValue) {
- self.journal.record(key, old, new, &self.counters);
- }
-
- fn class(&mut self, node: u32, class: u32, old: bool, new: bool) {
- let value = |present: bool| {
- InputValue::Feature(if present {
- FeatureValue::Present
- } else {
- FeatureValue::Absent
- })
- };
- self.record(
- InputKey::LocalFeature(StyleNodeID::element(node), LocalFeatureKey::Class(StyleAtomID(class))),
- value(old),
- value(new),
- );
- }
-
- fn element_style_input(&mut self, node: u32) {
- self.record(
- InputKey::ElementStyleInput(StyleNodeID::element(node)),
- InputValue::ElementStyleInput {
- reaction: 0,
- inherited_style_groups: 0,
- },
- InputValue::ElementStyleInput {
- reaction: STYLE_REACTION_RECOMPUTE_STYLE,
- inherited_style_groups: 0,
- },
- );
- }
-
- fn take(&mut self) -> StyleTransaction {
- self.journal.take_transaction(&self.counters)
- }
- }
-
- fn relations(parent: u32) -> InputValue {
- InputValue::TreeRelations(Some(TreeRelations {
- parent: Some(StyleNodeID::element(parent)),
- ..TreeRelations::detached(TreeScopeID::DOCUMENT)
- }))
- }
-
- #[test]
- fn adding_then_removing_the_same_class_produces_no_final_delta() {
- let mut fixture = JournalFixture::new();
- fixture.class(1, 10, false, true);
- assert_eq!(fixture.journal.len(), 1);
-
- fixture.class(1, 10, true, false);
- assert!(fixture.journal.is_empty());
- assert_eq!(fixture.counters.get(Counter::JournalCancellations), 1);
- assert_eq!(fixture.counters.get(Counter::RawMutationRecords), 2);
-
- let transaction = fixture.take();
- assert!(transaction.is_empty());
- assert_eq!(fixture.counters.get(Counter::NormalizedUniqueKeys), 0);
- transaction.release();
- }
-
- #[test]
- fn repeated_element_style_actions_merge_reactions_and_inherited_groups() {
- let mut fixture = JournalFixture::new();
- let key = InputKey::ElementStyleInput(StyleNodeID::element(1));
- let empty = InputValue::ElementStyleInput {
- reaction: 0,
- inherited_style_groups: 0,
- };
- fixture.record(
- key,
- empty,
- InputValue::ElementStyleInput {
- reaction: STYLE_REACTION_PUBLISHED_STYLE,
- inherited_style_groups: 0b001,
- },
- );
- fixture.record(
- key,
- empty,
- InputValue::ElementStyleInput {
- reaction: STYLE_REACTION_RECOMPUTE_STYLE,
- inherited_style_groups: 0b100,
- },
- );
-
- let transaction = fixture.take();
- assert_eq!(
- transaction.inputs,
- vec![NormalizedInput {
- key,
- old: empty,
- new: InputValue::ElementStyleInput {
- reaction: STYLE_REACTION_PUBLISHED_STYLE | STYLE_REACTION_RECOMPUTE_STYLE,
- inherited_style_groups: 0b101,
- },
- }]
- );
- transaction.release();
- }
-
- #[test]
- fn absorbing_a_newer_journal_keeps_its_complete_scope_markers() {
- let mut fixture = JournalFixture::new();
- fixture.class(1, 10, false, true);
-
- let mut newer = NormalizationJournal::new();
- newer.record_complete_scope_action(InputKind::LocalFeature, &fixture.counters);
-
- fixture.journal.absorb_newer(&mut newer, &fixture.counters);
- assert!(newer.is_empty());
-
- let transaction = fixture.take();
- assert!(transaction.inputs.is_empty());
- assert_eq!(
- transaction.markers,
- [CompleteScopeMarker {
- kind: InputKind::LocalFeature
- }]
- );
- transaction.release();
- }
-
- #[test]
- fn absorbing_a_newer_journal_keeps_the_reactions_of_both() {
- let mut fixture = JournalFixture::new();
- let key = InputKey::ElementStyleInput(StyleNodeID::element(1));
- let value = |reaction| InputValue::ElementStyleInput {
- reaction,
- inherited_style_groups: 0,
- };
- fixture.record(key, value(0), value(STYLE_REACTION_RECOMPUTE_STYLE));
-
- let mut newer = NormalizationJournal::new();
- newer.record(key, value(0), value(STYLE_REACTION_INHERITED_STYLE), &fixture.counters);
-
- fixture.journal.absorb_newer(&mut newer, &fixture.counters);
-
- let transaction = fixture.take();
- assert_eq!(
- transaction.inputs,
- [NormalizedInput {
- key,
- old: value(0),
- new: value(STYLE_REACTION_RECOMPUTE_STYLE | STYLE_REACTION_INHERITED_STYLE),
- }]
- );
- transaction.release();
- }
-
- #[test]
- fn absorbing_a_newer_journal_accepts_non_local_inputs() {
- let mut fixture = JournalFixture::new();
- fixture.class(1, 10, false, true);
-
- let mut newer = NormalizationJournal::new();
- newer.record(
- InputKey::ElementStyleInput(StyleNodeID::element(1)),
- InputValue::ElementStyleInput {
- reaction: 0,
- inherited_style_groups: 0,
- },
- InputValue::ElementStyleInput {
- reaction: STYLE_REACTION_RECOMPUTE_STYLE,
- inherited_style_groups: 0,
- },
- &fixture.counters,
- );
-
- fixture.journal.absorb_newer(&mut newer, &fixture.counters);
- assert!(newer.is_empty());
-
- let transaction = fixture.take();
- assert_eq!(transaction.inputs.len(), 2);
- assert!(
- transaction
- .inputs
- .iter()
- .any(|input| matches!(input.key, InputKey::LocalFeature(..)))
- );
- assert!(
- transaction
- .inputs
- .iter()
- .any(|input| matches!(input.key, InputKey::ElementStyleInput(..)))
- );
- transaction.release();
- }
-
- #[test]
- fn repeated_declaration_edits_retain_only_the_old_and_final_blocks() {
- let mut fixture = JournalFixture::new();
- let key = InputKey::ElementDeclaration(StyleNodeID::element(1), ElementDeclarationKind::InlineStyle);
- let block = |id: u32| InputValue::ElementDeclaration(Some(DeclarationBlockID(id)));
-
- fixture.record(key, block(1), block(2));
- fixture.record(key, block(2), block(3));
- fixture.record(key, block(3), block(4));
-
- assert_eq!(fixture.journal.len(), 1);
-
- let transaction = fixture.take();
- assert_eq!(
- transaction.inputs,
- vec![NormalizedInput {
- key,
- old: block(1),
- new: block(4),
- }]
- );
- transaction.release();
- }
-
- #[test]
- fn moving_a_subtree_twice_retains_only_its_original_and_final_relationships() {
- let mut fixture = JournalFixture::new();
- let key = InputKey::TreeRelations(StyleNodeID::element(5));
-
- fixture.record(key, relations(1), relations(2));
- fixture.record(key, relations(2), relations(3));
-
- let transaction = fixture.take();
- assert_eq!(transaction.inputs.len(), 1);
- assert_eq!(transaction.inputs[0].old, relations(1));
- assert_eq!(transaction.inputs[0].new, relations(3));
- transaction.release();
- }
-
- #[test]
- fn facts_published_before_and_after_an_arrival_fold_together() {
- let mut fixture = JournalFixture::new();
- let node = StyleNodeID::element(5);
- fixture.record(
- InputKey::LocalFeature(node, LocalFeatureKey::TagName),
- InputValue::Feature(FeatureValue::Absent),
- InputValue::Feature(FeatureValue::Atom(StyleAtomID(1))),
- );
- fixture.record(
- InputKey::TreeRelations(node),
- InputValue::TreeRelations(None),
- relations(1),
- );
- fixture.class(5, 10, false, true);
- fixture.record(
- InputKey::State(node, StateFact::Hover),
- InputValue::State(false),
- InputValue::State(true),
- );
-
- let transaction = fixture.take();
- assert_eq!(transaction.inputs.len(), 2);
- assert!(transaction.inputs.iter().any(|input| {
- input.key == InputKey::TreeRelations(node)
- && input.old == InputValue::TreeRelations(None)
- && input.new == relations(1)
- }));
- assert!(transaction.inputs.iter().any(|input| {
- input.key == InputKey::LocalFeature(node, LocalFeatureKey::ArrivingFacts)
- && input.old == InputValue::Feature(FeatureValue::Absent)
- && input.new == InputValue::Feature(FeatureValue::Present)
- }));
- assert_eq!(fixture.counters.get(Counter::ArrivingNodeFactsFolded), 3);
- transaction.release();
- }
-
- #[test]
- fn a_mutation_that_changes_nothing_is_counted_but_not_journalled() {
- let mut fixture = JournalFixture::new();
- fixture.class(1, 10, true, true);
- assert!(fixture.journal.is_empty());
- assert_eq!(fixture.counters.get(Counter::RawMutationRecords), 1);
- assert_eq!(fixture.counters.get(Counter::LocalFeatureDeltas), 1);
- }
-
- #[test]
- fn normalized_output_is_sorted_regardless_of_arrival_order() {
- let mut fixture = JournalFixture::new();
- for node in [7_u32, 2, 9, 4] {
- fixture.class(node, 1, false, true);
- }
- let transaction = fixture.take();
- let nodes: Vec<u32> = transaction
- .inputs
- .iter()
- .map(|input| input.key.style_node().unwrap().raw())
- .collect();
- assert_eq!(nodes, vec![2, 4, 7, 9]);
- transaction.release();
- }
-
- #[test]
- fn complete_scope_actions_are_not_counted_as_journal_coarsening() {
- let mut fixture = JournalFixture::new();
- fixture
- .journal
- .record_complete_scope_action(InputKind::Environment, &fixture.counters);
-
- assert_eq!(fixture.counters.get(Counter::RawMutationRecords), 1);
- assert_eq!(fixture.counters.get(Counter::EnvironmentDeltas), 1);
- assert_eq!(fixture.counters.get(Counter::CoarsenedScopeMarkers), 0);
- let transaction = fixture.take();
- assert!(!transaction.has_coarsened_markers());
- assert_eq!(
- transaction.markers,
- vec![CompleteScopeMarker {
- kind: InputKind::Environment
- }]
- );
- transaction.release();
- }
-
- #[test]
- fn journal_overflow_coarsens_the_largest_kind_into_a_typed_marker() {
- let mut fixture = JournalFixture::with_journal_entry_limit(64);
- fixture.record(
- InputKey::TreeRelations(StyleNodeID::element(1)),
- relations(1),
- relations(2),
- );
- fixture.record(
- InputKey::TreeRelations(StyleNodeID::element(2)),
- relations(1),
- relations(2),
- );
- for node in 10..200_u32 {
- fixture.class(node, 1, false, true);
- }
-
- assert!(
- fixture.counters.get(Counter::CoarsenedScopeMarkers) > 0,
- "a bounded scratch budget must force coarsening"
- );
- assert_eq!(
- fixture.journal.markers(),
- &[CompleteScopeMarker {
- kind: InputKind::LocalFeature
- }],
- "only the kind that overflowed is coarsened"
- );
-
- let transaction = fixture.take();
- assert!(transaction.has_coarsened_markers());
- // The tree relations keep their exact old and new values; only the class facts widened.
- assert!(
- transaction
- .inputs
- .iter()
- .all(|input| input.key.kind() == InputKind::TreeRelations)
- );
- assert_eq!(transaction.inputs.len(), 2);
- transaction.release();
- }
-
- #[test]
- fn element_style_actions_remain_exact_without_scratch_headroom() {
- let mut fixture = JournalFixture::with_journal_entry_limit(0);
- fixture.element_style_input(10);
- fixture.element_style_input(20);
-
- // Reconstructible facts may still coarsen around edge-triggered actions.
- for node in 30..200 {
- fixture.class(node, 1, false, true);
- }
- fixture.element_style_input(200);
-
- assert_eq!(
- fixture.journal.markers(),
- &[CompleteScopeMarker {
- kind: InputKind::LocalFeature
- }]
- );
- let transaction = fixture.take();
- assert_eq!(
- transaction
- .inputs
- .iter()
- .filter(|input| input.key.kind() == InputKind::ElementStyleInput)
- .map(|input| input.key)
- .collect::<Vec<_>>(),
- vec![
- InputKey::ElementStyleInput(StyleNodeID::element(10)),
- InputKey::ElementStyleInput(StyleNodeID::element(20)),
- InputKey::ElementStyleInput(StyleNodeID::element(200)),
- ]
- );
- transaction.release();
- }
-
- #[test]
- fn a_coarsened_kind_absorbs_further_records_without_growing() {
- let mut fixture = JournalFixture::with_journal_entry_limit(8);
- for node in 10..200_u32 {
- fixture.class(node, 1, false, true);
- }
-
- for node in 200..4000_u32 {
- fixture.class(node, 1, false, true);
- }
- assert_eq!(fixture.journal.len(), 0);
- assert_eq!(
- fixture.counters.get(Counter::RawMutationRecords),
- 3990,
- "every raw mutation is still counted"
- );
- }
-}
diff --git a/Libraries/LibWeb/Rust/src/css/style/transaction_view.rs b/Libraries/LibWeb/Rust/src/css/style/transaction_view.rs
index c99d658c1e0..f42ee4e9abf 100644
--- a/Libraries/LibWeb/Rust/src/css/style/transaction_view.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/transaction_view.rs
@@ -4,260 +4,10 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-//! Physical views used while evaluating one normalized transaction.
-
-use super::index::DispatchKey;
-use super::index::StyleNodeFacts;
-use super::selector::SiblingSequenceGeometry;
-use super::tree::StyleNodeID;
-
-const FEATURE_FLUX_PAGE_BITS: usize = u64::BITS as usize;
-
-/// Transaction-local feature changes indexed by dense style-node identity.
-///
-/// The occupancy words retain the fast dense negative gate. A hit selects one flat node span
-/// through a parallel page start and bit rank, so neither nodes nor their keys need a hash table or
-/// per-page allocations.
-#[derive(Clone, Copy)]
-struct FeatureFluxNode {
- key_offset: u32,
- key_count: u32,
-}
-
-#[derive(Clone, Default)]
-pub(super) struct FeatureFluxColumn {
- occupied: Vec<u64>,
- node_starts: Vec<u32>,
- nodes: Vec<FeatureFluxNode>,
- keys: Vec<DispatchKey>,
- nodes_by_key: Vec<(DispatchKey, StyleNodeID)>,
-}
-
-impl FeatureFluxColumn {
- pub(super) fn from_entries(mut entries: Vec<(StyleNodeID, DispatchKey)>) -> Self {
- entries.sort_unstable();
- entries.dedup();
- let mut features = Self::default();
- for entries in entries.chunk_by(|left, right| left.0 == right.0) {
- features.push_node(entries[0].0, entries.iter().map(|&(_, key)| key));
- }
- features.nodes_by_key = entries.into_iter().map(|(node, key)| (key, node)).collect();
- features.nodes_by_key.sort_unstable();
- features
- }
-
- fn push_node(&mut self, node: StyleNodeID, keys: impl IntoIterator<Item = DispatchKey>) {
- self.push(node.element_index().unwrap() as usize, keys);
- }
-
- fn push(&mut self, index: usize, keys: impl IntoIterator<Item = DispatchKey>) {
- let page_index = index / FEATURE_FLUX_PAGE_BITS;
- if self.occupied.len() <= page_index {
- self.occupied.resize(page_index + 1, 0);
- self.node_starts.resize(page_index + 1, 0);
- }
- let slot = index % FEATURE_FLUX_PAGE_BITS;
- let mask = 1_u64 << slot;
- let occupied = &mut self.occupied[page_index];
- assert_eq!(*occupied & mask, 0, "feature flux node inserted twice");
- assert!(
- *occupied < mask,
- "feature flux nodes must be inserted in identity order"
- );
- if *occupied == 0 {
- self.node_starts[page_index] = u32::try_from(self.nodes.len()).expect("feature flux node space exhausted");
- }
- *occupied |= mask;
- let key_offset = u32::try_from(self.keys.len()).expect("feature flux key space exhausted");
- self.keys.extend(keys);
- let key_end = u32::try_from(self.keys.len()).expect("feature flux key space exhausted");
- self.nodes.push(FeatureFluxNode {
- key_offset,
- key_count: key_end - key_offset,
- });
- }
-
- fn keys_of(&self, index: usize) -> &[DispatchKey] {
- let page_index = index / FEATURE_FLUX_PAGE_BITS;
- let Some(&occupied) = self.occupied.get(page_index) else {
- return &[];
- };
- let slot = index % FEATURE_FLUX_PAGE_BITS;
- let mask = 1_u64 << slot;
- if occupied & mask == 0 {
- return &[];
- }
- let rank = (occupied & mask.wrapping_sub(1)).count_ones() as usize;
- let node = self.nodes[self.node_starts[page_index] as usize + rank];
- let start = node.key_offset as usize;
- let end = start + node.key_count as usize;
- &self.keys[start..end]
- }
-
- pub(super) fn keys_of_node(&self, node: StyleNodeID) -> &[DispatchKey] {
- self.keys_of(node.element_index().unwrap() as usize)
- }
-
- #[cfg(test)]
- pub(super) fn all_nodes(&self, mut predicate: impl FnMut(StyleNodeID, &[DispatchKey]) -> bool) -> bool {
- for (page_index, &occupied) in self.occupied.iter().enumerate() {
- let mut remaining = occupied;
- let node_start = self.node_starts[page_index] as usize;
- for rank in 0..occupied.count_ones() as usize {
- let slot = remaining.trailing_zeros() as usize;
- remaining &= remaining - 1;
- let node = self.nodes[node_start + rank];
- let key_start = node.key_offset as usize;
- let key_end = key_start + node.key_count as usize;
- let index = page_index * FEATURE_FLUX_PAGE_BITS + slot;
- if !predicate(
- StyleNodeID::element(u32::try_from(index).expect("element identity space exhausted")),
- &self.keys[key_start..key_end],
- ) {
- return false;
- }
- }
- }
- true
- }
-
- pub(super) fn all_nodes_with_key(&self, key: DispatchKey, mut predicate: impl FnMut(StyleNodeID) -> bool) -> bool {
- let start = self.nodes_by_key.partition_point(|&(candidate, _)| candidate < key);
- self.nodes_by_key[start..]
- .iter()
- .take_while(|&&(candidate, _)| candidate == key)
- .all(|&(_, node)| predicate(node))
- }
-}
+//! The sides of a transaction that its readers compare.
#[derive(Clone, Copy, PartialEq, Eq)]
pub(super) enum TransactionFactSide {
Before,
After,
}
-
-/// The local facts and tree relations available while planning one transaction.
-///
-/// The after side lives in the resident arrangement. Changed local facts retain sparse before rows;
-/// unchanged nodes fall back to the resident arrangement on both sides.
-#[derive(Clone)]
-pub(super) struct TransactionFactView {
- pub(super) root: StyleNodeID,
- /// Every (node, key) local feature moved by this transaction, including all attribute name
- /// forms. Routing consults this delta beside the resident after-side facts so that neither a
- /// removed nor an added conjunct can reject the invalidation that will settle it.
- pub(super) moved_features: FeatureFluxColumn,
- pub(super) before_sibling_geometry: SiblingSequenceGeometry,
- pub(super) before_sibling_sequence_by_parent: Vec<(StyleNodeID, u32)>,
- pub(super) before_sibling_parents_by_sequence: Vec<StyleNodeID>,
- pub(super) before_absent_nodes: Vec<StyleNodeID>,
- pub(super) before_sibling_relations_available: bool,
- pub(super) prefix: Option<PrefixFactTransition>,
- pub(super) retained_truth_available: bool,
- /// Sparse before-side rows for the local facts changed by this transaction.
- pub(super) before: Option<StyleNodeFacts>,
-}
-
-impl TransactionFactView {
- #[must_use]
- pub(super) fn row_of<'a>(
- &'a self,
- side: TransactionFactSide,
- resident: &'a StyleNodeFacts,
- node: StyleNodeID,
- ) -> Option<(&'a StyleNodeFacts, u32)> {
- if side == TransactionFactSide::Before
- && let Some(facts) = self.before.as_ref()
- && let Some(row) = facts.row_of(node)
- {
- return Some((facts, row));
- }
- resident.row_of(node).map(|row| (resident, row))
- }
-}
-
-#[derive(Clone)]
-
-pub(super) struct PrefixFactTransition {
- pub(super) roots: Vec<StyleNodeID>,
- pub(super) departures: Vec<StyleNodeID>,
- pub(super) tree_relations_changed: bool,
- /// Live nodes whose rightward context a tree delta moved: reordered nodes, arrivals, and the
- /// nodes that followed an arrival, departure, or reorder in its old and new sequences. A
- /// sibling-bearing automaton walks these to convergence; a sibling-free one ignores them.
- pub(super) sibling_frontier: Vec<StyleNodeID>,
-}
-
-impl PrefixFactTransition {}
-
-#[cfg(test)]
-mod tests {
- use super::super::index::StateSet;
- use super::super::index::StyleAtomID;
- use super::*;
-
- #[test]
- fn feature_flux_packs_element_pages() {
- let first_class = DispatchKey::Class(StyleAtomID(200));
- let second_class = DispatchKey::Class(StyleAtomID(201));
- let features = FeatureFluxColumn::from_entries(vec![
- (StyleNodeID::element(70), second_class),
- (StyleNodeID::element(1), first_class),
- (StyleNodeID::element(70), first_class),
- (StyleNodeID::element(70), first_class),
- ]);
-
- assert_eq!(features.keys_of_node(StyleNodeID::element(1)), &[first_class]);
- assert_eq!(
- features.keys_of_node(StyleNodeID::element(70)),
- &[first_class, second_class]
- );
- assert!(features.keys_of_node(StyleNodeID::element(69)).is_empty());
- let mut visited = Vec::new();
- assert!(features.all_nodes(|node, _| {
- visited.push(node);
- true
- }));
- assert_eq!(visited, [StyleNodeID::element(1), StyleNodeID::element(70)]);
- assert_eq!(features.nodes.len(), 2);
- assert_eq!(features.occupied, [2, 64]);
- assert_eq!(features.node_starts, [0, 1]);
- let mut first_class_nodes = Vec::new();
- assert!(features.all_nodes_with_key(first_class, |node| {
- first_class_nodes.push(node);
- true
- }));
- assert_eq!(first_class_nodes, [StyleNodeID::element(1), StyleNodeID::element(70)]);
- let mut second_class_nodes = Vec::new();
- assert!(features.all_nodes_with_key(second_class, |node| {
- second_class_nodes.push(node);
- true
- }));
- assert_eq!(second_class_nodes, [StyleNodeID::element(70)]);
- }
-
- #[test]
- fn an_unchanged_local_fact_arrangement_serves_both_semantic_sides() {
- let node = StyleNodeID::element(1);
- let mut resident = StyleNodeFacts::new();
- resident.push_row(node, StyleAtomID(100), StyleAtomID::NONE, StateSet::default(), &[], &[]);
- let view = TransactionFactView {
- root: node,
- moved_features: FeatureFluxColumn::default(),
- before_sibling_geometry: SiblingSequenceGeometry::default(),
- before_sibling_sequence_by_parent: Vec::new(),
- before_sibling_parents_by_sequence: Vec::new(),
- before_absent_nodes: Vec::new(),
- before_sibling_relations_available: false,
- prefix: None,
- retained_truth_available: false,
- before: None,
- };
-
- for side in [TransactionFactSide::Before, TransactionFactSide::After] {
- let (facts, row) = view.row_of(side, &resident, node).unwrap();
- assert!(std::ptr::eq(facts, &raw const resident));
- assert_eq!(facts.tag_of(row), StyleAtomID(100));
- }
- }
-}
diff --git a/Libraries/LibWeb/Rust/src/css/style/tree.rs b/Libraries/LibWeb/Rust/src/css/style/tree.rs
index 1b87817d4fe..fac28ba94e5 100644
--- a/Libraries/LibWeb/Rust/src/css/style/tree.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/tree.rs
@@ -24,24 +24,24 @@
use super::fast_hash::FastMap as HashMap;
use super::fast_hash::FastSet as HashSet;
use smallvec::SmallVec;
-use std::cmp::Ordering;
use std::num::NonZeroU32;
-use std::sync::Arc;
-use std::sync::atomic::AtomicU32;
use super::column::BitColumn;
use super::column::PagedColumn;
use super::column::PagedColumnPage;
use super::column::RemovablePagedColumnPage;
use super::index::StyleAtomID;
-use super::transaction::TreeRelations;
-
-/// What an element's published style record says about whether, and as what, it is a query
-/// container. Kept apart from the selector facts, since it moves only when a record is published.
-#[derive(Clone, Default)]
-pub(super) struct ContainerQueryInputRow {
+use super::pipeline::projection::Projection;
+use crate::cow_column::CowColumn;
+
+/// What a record says of its element as a query container, read from the record's box group and
+/// the element's box kind: nothing of it is kept beside the record. Fly strings are interned, so
+/// inputs naming equal names hold equal raws.
+#[derive(Clone, Copy, PartialEq)]
+pub(super) struct ContainerQueryInputs<'a> {
pub(super) style_record: u64,
- pub(super) names: Vec<Vec<u16>>,
+ /// The record's `container-name` idents, as the raw fly strings its box group holds.
+ pub(super) names: &'a [usize],
pub(super) is_size_container: bool,
pub(super) size_queries_available: bool,
pub(super) is_inline_size_container: bool,
@@ -50,30 +50,25 @@ pub(super) struct ContainerQueryInputRow {
pub(super) direction: u8,
}
-#[derive(Clone, Default)]
-pub(super) struct ContainerQueryInputColumns {
- rows: Vec<Option<ContainerQueryInputRow>>,
-}
-
-impl ContainerQueryInputColumns {
- pub(super) fn set(&mut self, node: StyleNodeID, row: ContainerQueryInputRow) {
- let Some(index) = node.element_index().map(|index| index as usize) else {
- return;
- };
- if self.rows.len() <= index {
- self.rows.resize_with(index + 1, || None);
- }
- self.rows[index] = Some(row);
- }
+const _: () = assert!(size_of::<ContainerQueryInputs<'static>>() <= 32);
- pub(super) fn clear(&mut self, node: StyleNodeID) {
- if let Some(row) = node.element_index().and_then(|index| self.rows.get_mut(index as usize)) {
- *row = None;
- }
+impl ContainerQueryInputs<'_> {
+ /// Whether one of the container's names is `name`.
+ pub(super) fn is_named(&self, name: &[u16]) -> bool {
+ self.names.iter().any(|raw| {
+ // SAFETY: The record's box group holds a reference to each of its names.
+ match unsafe { ak::utf16_string_units(raw) } {
+ ak::Utf16StringUnits::Ascii(units) | ak::Utf16StringUnits::Latin1(units) => {
+ units.iter().copied().map(u16::from).eq(name.iter().copied())
+ }
+ ak::Utf16StringUnits::Utf16(units) => units == name,
+ }
+ })
}
- pub(super) fn get(&self, node: StyleNodeID) -> Option<&ContainerQueryInputRow> {
- self.rows.get(node.element_index()? as usize).and_then(Option::as_ref)
+ /// Whether the container answers size queries.
+ pub(super) fn supports_size_queries(&self) -> bool {
+ self.size_queries_available && (self.is_size_container || self.is_inline_size_container)
}
}
@@ -146,15 +141,18 @@ impl TreeScopeID {
}
/// A pseudo-element kind, holding the generated CSS pseudo-element enum value.
+#[cfg(test)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct PseudoElementKind(pub u16);
/// Which pseudo-element a selector entry targets.
+#[cfg(test)]
#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]
pub struct PseudoElementTarget {
pub kind: PseudoElementKind,
}
+#[cfg(test)]
impl PseudoElementTarget {
#[must_use]
pub fn new(kind: PseudoElementKind) -> Self {
@@ -166,7 +164,6 @@ const SEGMENTED_NODE_COLUMN_PAGE_SHIFT: usize = 6;
const SEGMENTED_NODE_COLUMN_PAGE_SIZE: usize = 1 << SEGMENTED_NODE_COLUMN_PAGE_SHIFT;
#[derive(Clone)]
-
struct SegmentedNodePage<T: Copy> {
values: [Option<T>; SEGMENTED_NODE_COLUMN_PAGE_SIZE],
}
@@ -213,6 +210,10 @@ impl<T: Copy> Default for SegmentedNodeColumn<T> {
}
impl<T: Copy> SegmentedNodeColumn<T> {
+ pub(super) fn heap_size(&self) -> usize {
+ self.0.heap_size()
+ }
+
pub(super) fn get(&self, node: StyleNodeID) -> Option<T> {
let index = node.element_index()? as usize;
self.0.get(index)
@@ -231,294 +232,6 @@ impl<T: Copy> SegmentedNodeColumn<T> {
}
}
-#[derive(Clone, Copy)]
-struct StagedTreeValue<T: Copy> {
- before: T,
- after: T,
- dirty: bool,
-}
-
-/// Transaction-local before/after rows for the tree relation family.
-///
-/// Pages are addressed by dense element identity. The touched lists exist only to drain populated
-/// rows without scanning the document-wide page directory at the commit barrier.
-#[derive(Clone, Default)]
-pub(super) struct TreeRelationStaging {
- rows: SegmentedNodeColumn<StagedTreeValue<Option<TreeRelations>>>,
- touched_rows: Vec<StyleNodeID>,
- dirty_rows: Vec<StyleNodeID>,
- first_children: SegmentedNodeColumn<StagedTreeValue<Option<StyleNodeID>>>,
- touched_first_children: Vec<StyleNodeID>,
- dirty_first_children: Vec<StyleNodeID>,
- applied: bool,
- /// How many rows are staged, which the document's host reads: each may deepen the tree by a level once settled.
- staged_rows: Arc<AtomicU32>,
-}
-
-type StagedTreeRows = Vec<(StyleNodeID, Option<TreeRelations>, Option<TreeRelations>)>;
-
-fn radix_sort_style_node_ids(mut nodes: Vec<StyleNodeID>) -> Vec<StyleNodeID> {
- if nodes.is_sorted() {
- return nodes;
- }
- let mut scratch = vec![nodes[0]; nodes.len()];
- let significant_bits = u32::BITS - nodes.iter().map(|node| node.raw()).max().unwrap().leading_zeros();
- for shift in (0..significant_bits).step_by(u8::BITS as usize) {
- let mut offsets = [0_usize; 1 << u8::BITS];
- for node in &nodes {
- offsets[((node.raw() >> shift) & u8::MAX as u32) as usize] += 1;
- }
- let mut offset = 0;
- for count in &mut offsets {
- let next_offset = offset + *count;
- *count = offset;
- offset = next_offset;
- }
- for &node in &nodes {
- let bucket = ((node.raw() >> shift) & u8::MAX as u32) as usize;
- scratch[offsets[bucket]] = node;
- offsets[bucket] += 1;
- }
- std::mem::swap(&mut nodes, &mut scratch);
- }
- nodes
-}
-
-impl TreeRelationStaging {
- pub(super) fn is_empty(&self) -> bool {
- self.touched_rows.is_empty() && self.touched_first_children.is_empty()
- }
-
- pub(super) fn is_applied(&self) -> bool {
- self.applied
- }
-
- pub(super) fn current_row(&self, node: StyleNodeID, unstaged: Option<TreeRelations>) -> Option<TreeRelations> {
- self.rows.get(node).map_or(unstaged, |pair| pair.after)
- }
-
- pub(super) fn stage_row(&mut self, node: StyleNodeID, before: Option<TreeRelations>, after: Option<TreeRelations>) {
- self.applied = false;
- match self.rows.get(node) {
- Some(mut pair) => {
- pair.after = after;
- if !pair.dirty {
- pair.dirty = true;
- self.dirty_rows.push(node);
- }
- self.rows.insert(node, pair);
- }
- None => {
- self.rows.insert(
- node,
- StagedTreeValue {
- before,
- after,
- dirty: true,
- },
- );
- self.touched_rows.push(node);
- self.dirty_rows.push(node);
- self.staged_rows.store(
- u32::try_from(self.touched_rows.len()).unwrap_or(u32::MAX),
- std::sync::atomic::Ordering::Relaxed,
- );
- }
- }
- }
-
- /// Gives a fork a count of staged rows of its own in place of the one it shares with the host.
- pub(super) fn detach_staged_rows_for_fork(&mut self) {
- let staged = self.staged_rows.load(std::sync::atomic::Ordering::Relaxed);
- self.staged_rows = Arc::new(AtomicU32::new(staged));
- }
-
- /// Keeps `staged_rows`, which the document's host reads, at how many rows are staged, rather than a count of the
- /// staging's own. Nothing is staged yet.
- pub(super) fn share_staged_rows(&mut self, staged_rows: Arc<AtomicU32>) {
- debug_assert!(self.touched_rows.is_empty());
- self.staged_rows = staged_rows;
- }
-
- pub(super) fn stage_first_child(
- &mut self,
- parent: StyleNodeID,
- before: Option<StyleNodeID>,
- after: Option<StyleNodeID>,
- ) {
- self.applied = false;
- match self.first_children.get(parent) {
- Some(mut pair) => {
- pair.after = after;
- if !pair.dirty {
- pair.dirty = true;
- self.dirty_first_children.push(parent);
- }
- self.first_children.insert(parent, pair);
- }
- None => {
- self.first_children.insert(
- parent,
- StagedTreeValue {
- before,
- after,
- dirty: true,
- },
- );
- self.touched_first_children.push(parent);
- self.dirty_first_children.push(parent);
- }
- }
- }
-
- pub(super) fn rows(
- &self,
- ) -> impl Iterator<Item = (StyleNodeID, Option<TreeRelations>, Option<TreeRelations>)> + '_ {
- self.touched_rows.iter().copied().map(|node| {
- let pair = self.rows.get(node).expect("touched tree row must be staged");
- (node, pair.before, pair.after)
- })
- }
-
- pub(super) fn first_children(
- &self,
- ) -> impl Iterator<Item = (StyleNodeID, Option<StyleNodeID>, Option<StyleNodeID>)> + '_ {
- self.touched_first_children.iter().copied().map(|parent| {
- let pair = self
- .first_children
- .get(parent)
- .expect("touched first-child row must be staged");
- (parent, pair.before, pair.after)
- })
- }
-
- pub(super) fn dirty_rows(&self) -> StagedTreeRows {
- radix_sort_style_node_ids(self.dirty_rows.clone())
- .into_iter()
- .map(|node| {
- let pair = self.rows.get(node).expect("dirty tree row must be staged");
- (node, pair.before, pair.after)
- })
- .collect()
- }
-
- pub(super) fn dirty_first_children(
- &self,
- ) -> impl Iterator<Item = (StyleNodeID, Option<StyleNodeID>, Option<StyleNodeID>)> + '_ {
- self.dirty_first_children.iter().copied().map(|parent| {
- let pair = self
- .first_children
- .get(parent)
- .expect("dirty first-child row must be staged");
- (parent, pair.before, pair.after)
- })
- }
-
- pub(super) fn before_relations(&self, node: StyleNodeID, resident: Option<TreeRelations>) -> Option<TreeRelations> {
- self.rows.get(node).map_or(resident, |pair| pair.before)
- }
-
- pub(super) fn before_first_child(&self, parent: StyleNodeID, resident: Option<StyleNodeID>) -> Option<StyleNodeID> {
- self.first_children.get(parent).map_or(resident, |pair| pair.before)
- }
-
- pub(super) fn mark_applied(&mut self) {
- for &node in &self.dirty_rows {
- let mut pair = self.rows.get(node).expect("touched tree row must be staged");
- pair.dirty = false;
- self.rows.insert(node, pair);
- }
- for &parent in &self.dirty_first_children {
- let mut pair = self
- .first_children
- .get(parent)
- .expect("touched first-child row must be staged");
- pair.dirty = false;
- self.first_children.insert(parent, pair);
- }
- self.dirty_rows.clear();
- self.dirty_first_children.clear();
- self.applied = true;
- }
-
- pub(super) fn clear(&mut self) {
- let staged_rows = std::mem::take(&mut self.staged_rows);
- staged_rows.store(0, std::sync::atomic::Ordering::Relaxed);
- *self = Self {
- staged_rows,
- ..Self::default()
- };
- }
-}
-
-/// Sparse shadow relations, allocated only for documents that have shadow trees.
-///
-/// These are the facts the flat tree is derived from rather than a second child list. Storing
-/// flat-tree children directly would cost two more words per node and duplicate information the
-/// slot and host relations already carry; deriving costs one lookup at the two places the flat tree
-/// actually diverges from the DOM tree.
-#[derive(Clone, Default)]
-struct ShadowRelations {
- /// A slotted element's slot.
- assigned_slot: SegmentedNodeColumn<StyleNodeID>,
- /// A slotted text node's slot. Text identities have no relation columns of their own, and a
- /// slotted text node is rare enough that a map costs less than a second column would.
- text_assigned_slot: HashMap<StyleNodeID, StyleNodeID>,
- /// A slot's assigned nodes, text nodes included, in the order the DOM assigned them.
- assigned_nodes: HashMap<StyleNodeID, Vec<StyleNodeID>>,
- /// A shadow host's shadow root.
- shadow_root: SegmentedNodeColumn<StyleNodeID>,
- /// A shadow root's host.
- host: SegmentedNodeColumn<StyleNodeID>,
- /// Every name an element is addressable by paired with the host of the level that name reaches.
- ///
- /// `exportparts` forwards a name outwards under a name of the host's choosing, so a name and a
- /// host only answer a `::part()` rule together: the flattened name set says an element answers
- /// to some name somewhere, which is what candidate discovery needs, while a rule matches only
- /// when one level exposes the name it writes and the host of that same level is the element its
- /// outer compound describes.
- part_hosts: HashMap<StyleNodeID, Vec<(StyleAtomID, StyleNodeID)>>,
- /// The element-backed pseudo-element kind an element of a shadow tree stands for on its host.
- backing_pseudo_kinds: HashMap<StyleNodeID, u16>,
-}
-
-impl ShadowRelations {
- fn retire_node(&mut self, node: StyleNodeID) {
- if let Some(slot) = self.assigned_slot.remove(node)
- && let Some(nodes) = self.assigned_nodes.get_mut(&slot)
- {
- nodes.retain(|&assigned| assigned != node);
- }
- if let Some(nodes) = self.assigned_nodes.remove(&node) {
- for assigned in nodes {
- if assigned.text_index().is_some() {
- if self.text_assigned_slot.get(&assigned) == Some(&node) {
- self.text_assigned_slot.remove(&assigned);
- }
- } else if self.assigned_slot.get(assigned) == Some(node) {
- self.assigned_slot.remove(assigned);
- }
- }
- }
- if let Some(root) = self.shadow_root.remove(node) {
- self.host.remove(root);
- }
- if let Some(host) = self.host.remove(node) {
- self.shadow_root.remove(host);
- }
- self.part_hosts.remove(&node);
- self.backing_pseudo_kinds.remove(&node);
- }
-
- fn retire_text(&mut self, node: StyleNodeID) {
- if let Some(slot) = self.text_assigned_slot.remove(&node)
- && let Some(nodes) = self.assigned_nodes.get_mut(&slot)
- {
- nodes.retain(|&assigned| assigned != node);
- }
- }
-}
-
/// The inverse of the element id column: which elements answer to an id name.
///
/// The name is the id as it is written, not the atom a selector is compiled against: a quirks-mode
@@ -574,26 +287,6 @@ impl ElementIdIndex {
}
}
-/// Flat-tree children of one node.
-pub enum FlatTreeChildren<'a> {
- /// The node's DOM children, which is the common case and the whole story for a document with
- /// no shadow trees.
- Dom(Children<'a>),
- /// A slot's assigned nodes, or a shadow host's shadow-root children.
- Assigned(std::slice::Iter<'a, StyleNodeID>),
-}
-
-impl Iterator for FlatTreeChildren<'_> {
- type Item = StyleNodeID;
-
- fn next(&mut self) -> Option<StyleNodeID> {
- match self {
- Self::Dom(children) => children.next(),
- Self::Assigned(nodes) => nodes.next().copied(),
- }
- }
-}
-
/// The spans a table cell or table column takes from its attributes.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub struct TableSpans {
@@ -610,21 +303,20 @@ impl Default for TableSpans {
}
}
-/// The Rust-owned projection of the tree relations selectors navigate.
+/// What the host publishes of its nodes beside the element links the projection holds: which
+/// identities are live, each element's depth, the DOM child sequences text nodes included, the
+/// text nodes' rows, the id index and the paint facts of a row built for a node.
///
/// Element columns are indexed by element index, with slot 0 unused so that a `StyleNodeID` indexes
/// its own column entry directly.
#[derive(Clone)]
-pub struct StyleNodeTree {
- // Required, dense.
- parent: Vec<Option<StyleNodeID>>,
- first_element_child: Vec<Option<StyleNodeID>>,
- next_element_sibling: Vec<Option<StyleNodeID>>,
- previous_element_sibling: Vec<Option<StyleNodeID>>,
- depth: Vec<u32>,
-
- // Conditional: allocated only for documents that need them.
- tree_scope: Option<Vec<TreeScopeID>>,
+pub struct HostTree {
+ /// What each element slot holds: its depth, its DOM child sequence links and its unique node
+ /// id. The column is copied on write in chunks, so that a fork shares it, and a write while a
+ /// fork lives copies only the chunk it lands in.
+ elements: CowColumn<ElementRow, ELEMENT_ROWS_PER_CHUNK>,
+ /// One past the greatest element slot the tree minted.
+ element_slots: usize,
live: BitColumn,
/// Identities that stand in the tree without being styled: the document, whose children the
@@ -639,20 +331,9 @@ pub struct StyleNodeTree {
#[cfg(test)]
test_identities: super::identities::StyleNodeIdAllocator,
- /// Allocated only once a shadow tree exists.
- shadow: Option<Box<ShadowRelations>>,
-
/// Allocated only once an element carries an id.
ids: Option<Box<ElementIdIndex>>,
- // The DOM child sequence, text nodes included. Elements keep these beside their element-only
- // links, which every selector walk reads; text nodes have nothing else.
- //
- // Unlike the element-only links, these are spliced when the DOM changes rather than staged,
- // because no transaction plans from them.
- first_child: Vec<Option<StyleNodeID>>,
- next_sibling: Vec<Option<StyleNodeID>>,
- previous_sibling: Vec<Option<StyleNodeID>>,
text: TextRows,
/// What a row built for the node is painted and hit-tested with: whether the node is inert,
@@ -660,12 +341,6 @@ pub struct StyleNodeTree {
/// holding a navigable. Nearly every node holds none of them, which is the absence of an entry.
/// Element, text and document identities publish here, as each gets a row.
dom_paint_facts: HashMap<StyleNodeID, u8>,
- /// The unique node id the document names the element by, published where the identity arrives
- /// and constant for as long as the element holds it. A box built for the element answers by
- /// it, and so does a box built for one of the element's pseudo-elements, which is why the
- /// render side needs it for an element that has no box of its own. The document's identity
- /// carries the document's.
- unique_node_ids: Vec<i64>,
/// The spans a table cell's or table column's attributes give it: the effective column and row
/// span, and the column span attribute's unclamped value, which only the table formatting
/// context's column handling reads. Every other element spans one of each, which is what the
@@ -678,47 +353,99 @@ pub struct StyleNodeTree {
/// Counts the changes to the DOM child sequences, to the parents and shadow roots that place a
/// node among its siblings, and to which nodes are live. See [`Self::dom_order_version`].
dom_order_version: u64,
+ /// Counts the changes to the DOM paint facts. See [`Self::dom_paint_facts_version`].
+ dom_paint_facts_version: u64,
#[cfg(test)]
depth_recompute_visits: usize,
- /// The depth of the deepest element the tree ever held, which the document's host reads.
- deepest_element: Arc<AtomicU32>,
}
-impl StyleNodeTree {
- /// Raises `deepest_element`, which the document's host reads, to the depth of the deepest element the tree holds
- /// from now on, rather than a count of the tree's own.
- pub(super) fn share_deepest_element(&mut self, deepest_element: Arc<AtomicU32>) {
- deepest_element.fetch_max(
- self.deepest_element.load(std::sync::atomic::Ordering::Relaxed),
- std::sync::atomic::Ordering::Relaxed,
- );
- self.deepest_element = deepest_element;
+/// What a [`HostTree`] holds of each element slot.
+#[derive(Clone, Copy, Default, PartialEq)]
+struct ElementRow {
+ // The DOM child sequence, text nodes included. Elements keep these beside their element-only
+ // links, which every selector walk reads; text nodes have nothing else.
+ //
+ // Unlike the element-only links, these are spliced when the DOM changes rather than staged,
+ // because no transaction plans from them.
+ first_child: Option<StyleNodeID>,
+ next_sibling: Option<StyleNodeID>,
+ previous_sibling: Option<StyleNodeID>,
+ /// The unique node id the document names the element by, published where the identity arrives
+ /// and constant for as long as the element holds it. A box built for the element answers by
+ /// it, and so does a box built for one of the element's pseudo-elements, which is why the
+ /// render side needs it for an element that has no box of its own. The document's identity
+ /// carries the document's.
+ unique_node_id: UniqueNodeId,
+}
+
+const _: () = assert!(size_of::<ElementRow>() == 20);
+
+/// The unique node id the document names a node by, in two words so that a row needs no more than 4-byte alignment.
+#[derive(Clone, Copy, Default, PartialEq, Eq)]
+struct UniqueNodeId([u32; 2]);
+
+impl From<i64> for UniqueNodeId {
+ fn from(id: i64) -> Self {
+ let bits = id.cast_unsigned();
+ Self([bits as u32, (bits >> 32) as u32])
+ }
+}
+
+impl From<UniqueNodeId> for i64 {
+ fn from(UniqueNodeId([low, high]): UniqueNodeId) -> Self {
+ (u64::from(low) | (u64::from(high) << 32)).cast_signed()
}
+}
- /// Gives a fork a depth of its own in place of the one it shares with the host.
- pub(super) fn detach_deepest_element_for_fork(&mut self) {
- let deepest = self.deepest_element.load(std::sync::atomic::Ordering::Relaxed);
- self.deepest_element = Arc::new(AtomicU32::new(deepest));
+/// How many element slots a chunk of [`HostTree`]'s column holds.
+const ELEMENT_ROWS_PER_CHUNK: usize = 32;
+
+impl HostTree {
+ /// The row of the element slot `index`, which the tree holds.
+ fn element_row(&self, index: usize) -> &ElementRow {
+ self.elements
+ .get(index)
+ .expect("the tree holds a row of every element slot it minted")
}
- /// Notes that an element of the tree is `depth` deep.
- #[inline]
- fn note_element_depth(&self, depth: u32) {
- if depth > self.deepest_element.load(std::sync::atomic::Ordering::Relaxed) {
- self.deepest_element
- .fetch_max(depth, std::sync::atomic::Ordering::Relaxed);
- }
+ /// Write the row of the element slot `index`, which the tree holds.
+ fn update_element_row(&mut self, index: usize, update: impl FnOnce(&mut ElementRow)) {
+ update(
+ &mut self
+ .elements
+ .row_mut(index)
+ .expect("the tree holds a row of every element slot it minted"),
+ );
+ }
+
+ /// The bytes of the tree's columns and indexes.
+ pub(super) fn heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {
+ use crate::heap_size::{map_bytes, vec_bytes};
+ let ids = self.ids.as_ref().map_or(0, |ids| {
+ size_of::<ElementIdIndex>()
+ + map_bytes(&ids.name_of_node)
+ + map_bytes(&ids.nodes_by_name)
+ + ids.candidate_bytes
+ });
+ let text = &self.text;
+ let text_bytes = text.links.heap_size(sizer, |_, _| 0)
+ + text.flags.heap_size(sizer, |_, _| 0)
+ + text.data.heap_size(sizer, |_, _| 0)
+ + vec_bytes(&text.pending_reuse);
+ self.elements.heap_size(sizer, |_, _| 0)
+ + self.live.heap_size()
+ + self.relation_only.heap_size()
+ + vec_bytes(&self.pending_reuse)
+ + ids
+ + text_bytes
+ + map_bytes(&self.dom_paint_facts)
+ + map_bytes(&self.table_spans)
+ + vec_bytes(&self.top_layer)
}
pub(super) fn collect_atoms(&self, atoms: &mut HashSet<StyleAtomID>) -> u64 {
let mut visited = 0_u64;
- if let Some(shadow) = &self.shadow {
- for pairs in shadow.part_hosts.values() {
- visited += u64::try_from(pairs.len()).expect("part host count exceeds u64");
- atoms.extend(pairs.iter().map(|&(atom, _)| atom));
- }
- }
// An id name is the id as written, which in a quirks-mode document no id fact holds: those
// keep the folded form. The index roots its own names rather than rely on other state to.
if let Some(ids) = &self.ids {
@@ -731,56 +458,45 @@ impl StyleNodeTree {
#[must_use]
pub fn new() -> Self {
let mut tree = Self {
- parent: Vec::new(),
- first_element_child: Vec::new(),
- next_element_sibling: Vec::new(),
- previous_element_sibling: Vec::new(),
- depth: Vec::new(),
- tree_scope: None,
+ elements: CowColumn::default(),
+ element_slots: 1,
live: BitColumn::default(),
relation_only: BitColumn::default(),
connected_element_count: 0,
pending_reuse: Vec::new(),
#[cfg(test)]
test_identities: Default::default(),
- shadow: None,
ids: None,
- first_child: Vec::new(),
- next_sibling: Vec::new(),
- previous_sibling: Vec::new(),
text: TextRows::default(),
dom_paint_facts: HashMap::default(),
- unique_node_ids: Vec::new(),
table_spans: HashMap::default(),
top_layer: Vec::new(),
dom_order_version: 0,
+ dom_paint_facts_version: 0,
#[cfg(test)]
depth_recompute_visits: 0,
- deepest_element: Arc::default(),
};
// Slot 0 is never a valid identity; reserving it keeps column indexing direct.
- tree.parent.push(None);
- tree.first_element_child.push(None);
- tree.next_element_sibling.push(None);
- tree.previous_element_sibling.push(None);
- tree.depth.push(0);
- tree.first_child.push(None);
- tree.next_sibling.push(None);
- tree.previous_sibling.push(None);
- tree.text.parent.push(None);
- tree.text.next_sibling.push(None);
- tree.text.previous_sibling.push(None);
- tree.text.data.push(ak::Utf16String::default());
+ tree.elements.grow_to(1);
+ tree.text.links.grow_to(1);
+ tree.text.flags.grow_to(1);
+ tree.text.data.grow_to(1);
tree
}
- /// Connected styleable elements, which is the count the journal's entry limit is written in.
+ /// Connected styleable elements.
#[must_use]
pub fn connected_element_count(&self) -> u32 {
self.connected_element_count
}
+ /// One past the greatest element slot the tree holds.
+ #[must_use]
+ pub fn element_slot_count(&self) -> usize {
+ self.element_slots
+ }
+
/// Mark an identity as standing in the tree without being styled. See `relation_only`.
pub fn mark_relation_only(&mut self, node: StyleNodeID) {
let Some(index) = node.element_index() else {
@@ -805,14 +521,14 @@ impl StyleNodeTree {
#[must_use]
pub fn is_live(&self, node: StyleNodeID) -> bool {
match node.text_index() {
- Some(index) => self.text.live.contains(index as usize),
+ Some(index) => self.text.flag(index, TextFlags::LIVE),
None => self.live.contains(node.element_slot()),
}
}
/// Every live element-kind identity, including the synthetic roots of shadow trees.
pub fn live_nodes(&self) -> impl Iterator<Item = StyleNodeID> + '_ {
- (1..self.parent.len()).filter_map(|index| {
+ (1..self.element_slots).filter_map(|index| {
let index = u32::try_from(index).expect("style node index space exhausted");
self.live.contains(index as usize).then(|| StyleNodeID::element(index))
})
@@ -825,40 +541,25 @@ impl StyleNodeTree {
pub fn mint_element(&mut self, node: StyleNodeID) {
self.dom_order_version += 1;
let index = node.element_index().expect("mint_element requires an element identity");
- if (index as usize) < self.parent.len() {
+ if (index as usize) < self.element_slots {
assert!(
!self.live.contains(index as usize),
"minting an element identity that is live"
);
- self.parent[index as usize] = None;
- self.first_element_child[index as usize] = None;
- self.next_element_sibling[index as usize] = None;
- self.previous_element_sibling[index as usize] = None;
- self.depth[index as usize] = 0;
- self.first_child[index as usize] = None;
- self.next_sibling[index as usize] = None;
- self.previous_sibling[index as usize] = None;
- if let Some(column) = self.tree_scope.as_mut() {
- column[index as usize] = TreeScopeID::DOCUMENT;
- }
+ // NB: The unique node id stays: the host may publish it before minting the identity.
+ self.update_element_row(index as usize, |row| {
+ *row = ElementRow {
+ unique_node_id: row.unique_node_id,
+ ..ElementRow::default()
+ }
+ });
} else {
assert_eq!(
- index as usize,
- self.parent.len(),
+ index as usize, self.element_slots,
"the host mints new element identities in order"
);
-
- self.parent.push(None);
- self.first_element_child.push(None);
- self.next_element_sibling.push(None);
- self.previous_element_sibling.push(None);
- self.depth.push(0);
- self.first_child.push(None);
- self.next_sibling.push(None);
- self.previous_sibling.push(None);
- if let Some(column) = self.tree_scope.as_mut() {
- column.push(TreeScopeID::DOCUMENT);
- }
+ self.element_slots += 1;
+ self.elements.grow_to(self.element_slots);
}
self.live.set(index as usize, true);
self.connected_element_count += 1;
@@ -882,14 +583,9 @@ impl StyleNodeTree {
node
}
- /// Retire an element identity. The slot stays reserved until [`Self::release_retired_identities`]
- /// runs at epoch retirement, so no reader can observe a reused identity.
- #[cfg(test)]
- pub fn retire_element(&mut self, node: StyleNodeID) {
- self.retire_elements(&[node]);
- }
-
- /// Retire a batch of element identities, accounting once for the capacity they release.
+ /// Retire a batch of element identities, accounting once for the capacity they release. Each
+ /// slot stays reserved until [`Self::release_retired_identities`] runs at epoch retirement, so
+ /// no reader can observe a reused identity.
pub fn retire_elements(&mut self, nodes: &[StyleNodeID]) {
self.dom_order_version += 1;
@@ -901,30 +597,17 @@ impl StyleNodeTree {
self.live.contains(index as usize),
"retiring an identity that is not live"
);
- if let Some(shadow) = &mut self.shadow {
- shadow.retire_node(node);
- }
if let Some(ids) = &mut self.ids {
ids.set(node, StyleAtomID::NONE);
}
self.live.set(index as usize, false);
self.dom_paint_facts.remove(&node);
- if let Some(unique_node_id) = self.unique_node_ids.get_mut(index as usize) {
- *unique_node_id = 0;
- }
self.table_spans.remove(&node);
self.top_layer.retain(|&member| member != node);
if !self.relation_only.set(index as usize, false).0 {
self.connected_element_count -= 1;
}
- self.parent[index as usize] = None;
- self.first_element_child[index as usize] = None;
- self.next_element_sibling[index as usize] = None;
- self.previous_element_sibling[index as usize] = None;
- self.depth[index as usize] = 0;
- self.first_child[index as usize] = None;
- self.next_sibling[index as usize] = None;
- self.previous_sibling[index as usize] = None;
+ self.update_element_row(index as usize, |row| *row = ElementRow::default());
self.pending_reuse.push(index);
}
}
@@ -962,23 +645,21 @@ impl StyleNodeTree {
self.dom_order_version += 1;
let index = node.text_index().expect("mint_text requires a text identity");
- if (index as usize) < self.text.parent.len() {
+ if (index as usize) < self.text.links.len() {
assert!(
- !self.text.live.contains(index as usize),
+ !self.text.flag(index, TextFlags::LIVE),
"minting a text identity that is live"
);
} else {
assert_eq!(
index as usize,
- self.text.parent.len(),
+ self.text.links.len(),
"the host mints new text identities in order"
);
- self.text.parent.push(None);
- self.text.next_sibling.push(None);
- self.text.previous_sibling.push(None);
- self.text.data.push(ak::Utf16String::default());
+ self.text.links.grow_to(index as usize + 1);
+ self.text.data.grow_to(index as usize + 1);
}
- self.text.live.set(index as usize, true);
+ self.text.set_flag(index, TextFlags::LIVE, true);
}
/// Mint a text identity from the tree's own space, for a test.
@@ -995,36 +676,21 @@ impl StyleNodeTree {
pub fn retire_texts(&mut self, nodes: impl IntoIterator<Item = StyleNodeID>) {
self.dom_order_version += 1;
- // Every column is named, so a new one cannot leave a retired identity's value behind for
- // the next text node issued the index.
- let TextRows {
- parent,
- next_sibling,
- previous_sibling,
- live,
- is_ascii_whitespace,
- is_in_user_agent_shadow_tree,
- is_password_input,
- data,
- pending_reuse,
- } = &mut self.text;
+ // Every column is reset, so none leaves a retired identity's value behind for the next text
+ // node issued the index.
for node in nodes {
let index = node.text_index().expect("retire_texts requires a text identity");
- let (was_live, _) = live.set(index as usize, false);
- assert!(was_live, "retiring a text identity that is not live");
- is_ascii_whitespace.set(index as usize, false);
- is_in_user_agent_shadow_tree.set(index as usize, false);
- is_password_input.set(index as usize, false);
+ assert!(
+ self.text.flag(index, TextFlags::LIVE),
+ "retiring a text identity that is not live"
+ );
+ self.text.flags.set(index as usize, TextFlags::default());
self.dom_paint_facts.remove(&node);
// Lets go of the reference the mirror held to the document's string.
- data[index as usize] = ak::Utf16String::default();
- parent[index as usize] = None;
- next_sibling[index as usize] = None;
- previous_sibling[index as usize] = None;
- pending_reuse.push(index);
- if let Some(shadow) = self.shadow.as_mut() {
- shadow.retire_text(node);
- }
+ self.text.data.set(index as usize, ak::Utf16String::default());
+ let text = &mut self.text;
+ text.links.set(index as usize, TextLinks::default());
+ text.pending_reuse.push(index);
}
}
@@ -1033,7 +699,7 @@ impl StyleNodeTree {
#[must_use]
pub fn text_is_ascii_whitespace(&self, node: StyleNodeID) -> bool {
node.text_index()
- .is_some_and(|index| self.text.is_ascii_whitespace.contains(index as usize))
+ .is_some_and(|index| self.text.flag(index, TextFlags::IS_ASCII_WHITESPACE))
}
/// Record what the text node's data now spells, as its whitespace-only state.
@@ -1042,7 +708,7 @@ impl StyleNodeTree {
return;
};
- self.text.is_ascii_whitespace.set(index as usize, value);
+ self.text.set_flag(index, TextFlags::IS_ASCII_WHITESPACE, value);
}
/// Whether the text node sits in a user agent shadow tree. Only a text node is asked; an
@@ -1050,7 +716,7 @@ impl StyleNodeTree {
#[must_use]
pub fn text_is_in_user_agent_shadow_tree(&self, node: StyleNodeID) -> bool {
node.text_index()
- .is_some_and(|index| self.text.is_in_user_agent_shadow_tree.contains(index as usize))
+ .is_some_and(|index| self.text.flag(index, TextFlags::IS_IN_USER_AGENT_SHADOW_TREE))
}
/// Record which kind of tree the text node arrived in.
@@ -1059,7 +725,8 @@ impl StyleNodeTree {
return;
};
- self.text.is_in_user_agent_shadow_tree.set(index as usize, value);
+ self.text
+ .set_flag(index, TextFlags::IS_IN_USER_AGENT_SHADOW_TREE, value);
}
/// Whether the text node holds the value of a password input. Only a text node is asked; every
@@ -1067,7 +734,7 @@ impl StyleNodeTree {
#[must_use]
pub fn text_is_password_input(&self, node: StyleNodeID) -> bool {
node.text_index()
- .is_some_and(|index| self.text.is_password_input.contains(index as usize))
+ .is_some_and(|index| self.text.flag(index, TextFlags::IS_PASSWORD_INPUT))
}
/// Record whether the text node holds the value of a password input.
@@ -1076,7 +743,7 @@ impl StyleNodeTree {
return;
};
- self.text.is_password_input.set(index as usize, value);
+ self.text.set_flag(index, TextFlags::IS_PASSWORD_INPUT, value);
}
/// Record the unique node id the document names the element by. Only an element identity, the
@@ -1087,18 +754,16 @@ impl StyleNodeTree {
};
let index = index as usize;
- if self.unique_node_ids.len() <= index {
- self.unique_node_ids.resize(index + 1, 0);
- }
- self.unique_node_ids[index] = unique_node_id;
+ self.elements.grow_to(index + 1);
+ self.update_element_row(index, |row| row.unique_node_id = unique_node_id.into());
}
/// The unique node id the document names the element by, or zero for anything else.
#[must_use]
pub fn unique_node_id(&self, node: StyleNodeID) -> i64 {
node.element_index()
- .and_then(|index| self.unique_node_ids.get(index as usize).copied())
- .unwrap_or(0)
+ .and_then(|index| self.elements.get(index as usize))
+ .map_or(0, |row| row.unique_node_id.into())
}
/// The spans a row built for the element takes from its attributes.
@@ -1126,14 +791,32 @@ impl StyleNodeTree {
/// Record what a row built for the node is painted and hit-tested with. Holding none of the
/// facts is the absence of an entry.
+ /// The nodes that are editable or an editing host.
+ pub fn editable_nodes(&self) -> impl Iterator<Item = StyleNodeID> + '_ {
+ self.dom_paint_facts.iter().filter_map(|(&node, &facts)| {
+ (facts & crate::layout::node_data::DomPaintFact::EditableOrEditingHost as u8 != 0).then_some(node)
+ })
+ }
+
pub fn set_dom_paint_facts(&mut self, node: StyleNodeID, facts: u8) {
- if facts == 0 {
- self.dom_paint_facts.remove(&node);
+ let previous = if facts == 0 {
+ self.dom_paint_facts.remove(&node)
} else {
- self.dom_paint_facts.insert(node, facts);
+ self.dom_paint_facts.insert(node, facts)
+ };
+ if previous.unwrap_or(0) != facts {
+ self.dom_paint_facts_version += 1;
}
}
+ /// A version of the DOM paint facts, which a retirement of a node moves with
+ /// [`Self::dom_order_version`]. Whatever reads none of them since it read the version reads the
+ /// same facts again.
+ #[must_use]
+ pub fn dom_paint_facts_version(&self) -> u64 {
+ self.dom_paint_facts_version
+ }
+
/// The document's top layer, in the order its members were added.
#[must_use]
pub fn top_layer(&self) -> &[StyleNodeID] {
@@ -1155,7 +838,8 @@ impl StyleNodeTree {
/// than copied.
pub fn set_text_data(&mut self, node: StyleNodeID, data: ak::Utf16String) {
if let Some(index) = node.text_index() {
- self.text.data[index as usize] = data;
+ self.text.data.grow_to(index as usize + 1);
+ self.text.data.set(index as usize, data);
}
}
@@ -1174,29 +858,29 @@ impl StyleNodeTree {
.filter(|&parent| self.is_live(parent))
.and_then(StyleNodeID::element_index)
else {
- *self.next_sibling_mut(node) = None;
- *self.previous_sibling_mut(node) = None;
+ self.set_next_sibling(node, None);
+ self.set_previous_sibling(node, None);
if let Some(index) = node.text_index() {
- self.text.parent[index as usize] = None;
+ self.text.edit_links(index, |links| links.parent = None);
}
return;
};
let parent_index = parent_index as usize;
let next = match previous {
Some(previous) => self.next_sibling_in_dom_order(previous),
- None => self.first_child[parent_index],
+ None => self.element_row(parent_index).first_child,
};
- *self.previous_sibling_mut(node) = previous;
- *self.next_sibling_mut(node) = next;
+ self.set_previous_sibling(node, previous);
+ self.set_next_sibling(node, next);
match previous {
- Some(previous) => *self.next_sibling_mut(previous) = Some(node),
- None => self.first_child[parent_index] = Some(node),
+ Some(previous) => self.set_next_sibling(previous, Some(node)),
+ None => self.update_element_row(parent_index, |row| row.first_child = Some(node)),
}
if let Some(next) = next {
- *self.previous_sibling_mut(next) = Some(node);
+ self.set_previous_sibling(next, Some(node));
}
if let Some(index) = node.text_index() {
- self.text.parent[index as usize] = parent;
+ self.text.edit_links(index, |links| links.parent = parent);
}
}
@@ -1206,31 +890,33 @@ impl StyleNodeTree {
if !self.is_live(node) {
return;
}
- let previous = self.previous_sibling_mut(node).take();
- let next = self.next_sibling_mut(node).take();
+ let previous = self.previous_sibling_in_dom_order(node);
+ let next = self.next_sibling_in_dom_order(node);
+ self.set_previous_sibling(node, None);
+ self.set_next_sibling(node, None);
match previous {
Some(previous) => {
if self.is_live(previous) {
- *self.next_sibling_mut(previous) = next;
+ self.set_next_sibling(previous, next);
}
}
None => {
if let Some(parent_index) = parent
.filter(|&parent| self.is_live(parent))
.and_then(StyleNodeID::element_index)
- && self.first_child[parent_index as usize] == Some(node)
+ && self.element_row(parent_index as usize).first_child == Some(node)
{
- self.first_child[parent_index as usize] = next;
+ self.update_element_row(parent_index as usize, |row| row.first_child = next);
}
}
}
if let Some(next) = next
&& self.is_live(next)
{
- *self.previous_sibling_mut(next) = previous;
+ self.set_previous_sibling(next, previous);
}
if let Some(index) = node.text_index() {
- self.text.parent[index as usize] = None;
+ self.text.edit_links(index, |links| links.parent = None);
}
}
@@ -1247,121 +933,101 @@ impl StyleNodeTree {
pub fn dom_children(&self, node: StyleNodeID) -> DomChildren<'_> {
DomChildren {
tree: self,
- next: node.element_index().and_then(|index| self.first_child[index as usize]),
+ next: node
+ .element_index()
+ .and_then(|index| self.element_row(index as usize).first_child),
}
}
/// The parent a text node is linked under.
#[must_use]
pub fn text_parent(&self, node: StyleNodeID) -> Option<StyleNodeID> {
- self.text.parent[node.text_index()? as usize]
+ self.text.links(node.text_index()?).parent
}
#[must_use]
pub fn next_sibling_in_dom_order(&self, node: StyleNodeID) -> Option<StyleNodeID> {
match node.text_index() {
- Some(index) => self.text.next_sibling[index as usize],
- None => self.next_sibling[node.element_slot()],
+ Some(index) => self.text.links(index).next_sibling,
+ None => self.element_row(node.element_slot()).next_sibling,
}
}
#[must_use]
pub fn previous_sibling_in_dom_order(&self, node: StyleNodeID) -> Option<StyleNodeID> {
match node.text_index() {
- Some(index) => self.text.previous_sibling[index as usize],
- None => self.previous_sibling[node.element_slot()],
+ Some(index) => self.text.links(index).previous_sibling,
+ None => self.element_row(node.element_slot()).previous_sibling,
}
}
- fn next_sibling_mut(&mut self, node: StyleNodeID) -> &mut Option<StyleNodeID> {
+ fn set_next_sibling(&mut self, node: StyleNodeID, next: Option<StyleNodeID>) {
match node.text_index() {
- Some(index) => &mut self.text.next_sibling[index as usize],
- None => &mut self.next_sibling[node.element_slot()],
+ Some(index) => self.text.edit_links(index, |links| links.next_sibling = next),
+ None => self.update_element_row(node.element_slot(), |row| row.next_sibling = next),
}
}
- fn previous_sibling_mut(&mut self, node: StyleNodeID) -> &mut Option<StyleNodeID> {
+ fn set_previous_sibling(&mut self, node: StyleNodeID, previous: Option<StyleNodeID>) {
match node.text_index() {
- Some(index) => &mut self.text.previous_sibling[index as usize],
- None => &mut self.previous_sibling[node.element_slot()],
+ Some(index) => self.text.edit_links(index, |links| links.previous_sibling = previous),
+ None => self.update_element_row(node.element_slot(), |row| row.previous_sibling = previous),
}
}
- // -- Relation maintenance ----------------------------------------------------------------
+ // -- Depth ------------------------------------------------------------------------------
- pub fn set_parent(&mut self, node: StyleNodeID, parent: Option<StyleNodeID>) {
+ /// Note that the links the projection holds moved: the parents and shadow roots that place a
+ /// node among its siblings. See [`Self::dom_order_version`].
+ pub(super) fn note_element_links_moved(&mut self) {
self.dom_order_version += 1;
- let depth = parent.map_or(0, |parent| {
- self.depth(parent).checked_add(1).expect("style tree depth exhausted")
- });
- self.set_subtree_depth(node, depth);
- let index = self.live_element_index(node);
- self.parent[index] = parent;
}
- fn set_subtree_depth(&mut self, node: StyleNodeID, depth: u32) {
- let index = self.live_element_index(node);
- let previous_depth = self.depth[index];
- if depth != previous_depth {
- let adjustment = i64::from(depth) - i64::from(previous_depth);
- let mut next = Some(node);
- while let Some(descendant) = next {
- let descendant_index = self.live_element_index(descendant);
- let depth = u32::try_from(i64::from(self.depth[descendant_index]) + adjustment)
- .expect("style tree depth exhausted");
- self.note_element_depth(depth);
- self.depth[descendant_index] = depth;
- next = self.first_element_child[descendant_index].or_else(|| {
- let mut candidate = descendant;
- loop {
- if candidate == node {
- return None;
- }
- let candidate_index = self.element_index(candidate);
- if let Some(sibling) = self.next_element_sibling[candidate_index] {
- return Some(sibling);
- }
- candidate = self.parent[candidate_index]?;
- }
- });
- }
+ /// The depth of the deepest element at or below `root`, by the links written into `projection`, which the
+ /// transaction being taken settles.
+ pub(super) fn deepest_depth_under(&mut self, projection: &Projection, root: StyleNodeID) -> u32 {
+ let written_parent = |node| {
+ projection
+ .written_relations(node)
+ .and_then(|relations| relations.parent)
+ };
+ let mut depth = 0_u32;
+ let mut ancestor = written_parent(root);
+ while let Some(node) = ancestor {
+ depth = depth.checked_add(1).expect("style tree depth exhausted");
+ ancestor = written_parent(node);
}
- }
-
- pub(super) fn set_parent_without_updating_depth(&mut self, node: StyleNodeID, parent: Option<StyleNodeID>) {
- self.dom_order_version += 1;
- let index = self.live_element_index(node);
- self.parent[index] = parent;
- }
-
- /// Update one final staged subtree after all parent and sibling columns are installed.
- pub(super) fn recompute_subtree_depth(&mut self, root: StyleNodeID) {
+ let mut deepest = depth;
let mut next = Some(root);
while let Some(node) = next {
#[cfg(test)]
{
self.depth_recompute_visits += 1;
}
- let index = self.live_element_index(node);
- let depth = self.parent[index].map_or(0, |parent| {
- self.depth(parent).checked_add(1).expect("style tree depth exhausted")
- });
- self.note_element_depth(depth);
- self.depth[index] = depth;
- next = self.first_element_child[index].or_else(|| {
- let mut candidate = node;
- loop {
- if candidate == root {
- return None;
- }
- let candidate_index = self.element_index(candidate);
- if let Some(sibling) = self.next_element_sibling[candidate_index] {
- return Some(sibling);
- }
- candidate = self.parent[candidate_index]?;
+ deepest = deepest.max(depth);
+ if let Some(child) = projection.written_first_element_child(node) {
+ depth = depth.checked_add(1).expect("style tree depth exhausted");
+ next = Some(child);
+ continue;
+ }
+ next = None;
+ let mut candidate = node;
+ while candidate != root {
+ if let Some(sibling) = projection
+ .written_relations(candidate)
+ .and_then(|relations| relations.next_element_sibling)
+ {
+ next = Some(sibling);
+ break;
}
- });
+ let Some(parent) = written_parent(candidate) else {
+ break;
+ };
+ candidate = parent;
+ depth -= 1;
+ }
}
+ deepest
}
#[cfg(test)]
@@ -1369,43 +1035,6 @@ impl StyleNodeTree {
core::mem::take(&mut self.depth_recompute_visits)
}
- pub fn set_first_element_child(&mut self, node: StyleNodeID, child: Option<StyleNodeID>) {
- let index = self.live_element_index(node);
- self.first_element_child[index] = child;
- }
-
- pub fn set_next_element_sibling(&mut self, node: StyleNodeID, sibling: Option<StyleNodeID>) {
- let index = self.live_element_index(node);
- self.next_element_sibling[index] = sibling;
- }
-
- pub fn set_previous_element_sibling(&mut self, node: StyleNodeID, sibling: Option<StyleNodeID>) {
- let index = self.live_element_index(node);
- self.previous_element_sibling[index] = sibling;
- }
-
- /// Allocate the tree-scope column. A single-scope document never pays for it.
- pub fn enable_tree_scopes(&mut self) {
- if self.tree_scope.is_some() {
- return;
- }
- self.tree_scope = Some(vec![TreeScopeID::DOCUMENT; self.parent.len()]);
- }
-
- #[must_use]
- pub fn has_tree_scopes(&self) -> bool {
- self.tree_scope.is_some()
- }
-
- pub fn set_tree_scope(&mut self, node: StyleNodeID, scope: TreeScopeID) {
- let index = self.live_element_index(node);
- let column = self
- .tree_scope
- .as_mut()
- .expect("set_tree_scope requires the tree-scope column");
- column[index] = scope;
- }
-
// -- Element ids -------------------------------------------------------------------------
/// Record the id an element answers to, or clear it with atom zero. The name is the id as
@@ -1432,18 +1061,23 @@ impl StyleNodeTree {
/// order comparisons, each a climb to the common ancestor and a walk along its children, which
/// is fine for the handful of duplicates real pages have.
#[must_use]
- pub fn element_by_id(&self, tree_scope: TreeScopeID, name: StyleAtomID) -> Option<StyleNodeID> {
+ pub(super) fn element_by_id(
+ &self,
+ projection: &Projection,
+ tree_scope: TreeScopeID,
+ name: StyleAtomID,
+ ) -> Option<StyleNodeID> {
let nodes = self.ids.as_ref()?.nodes_by_name.get(&name)?;
let mut first = None;
for &node in nodes {
let Some(index) = node.element_index() else {
continue;
};
- if !self.live.contains(index as usize) || self.tree_scope(node) != tree_scope {
+ if !self.live.contains(index as usize) || projection.tree_scope(node) != tree_scope {
continue;
}
first = match first {
- Some(current) if !self.precedes_in_tree_order(node, current) => Some(current),
+ Some(current) if !self.precedes_in_tree_order(projection, node, current) => Some(current),
_ => Some(node),
};
}
@@ -1451,616 +1085,136 @@ impl StyleNodeTree {
}
/// Whether `a` comes before `b` in the tree order of the scope they share.
- fn precedes_in_tree_order(&self, a: StyleNodeID, b: StyleNodeID) -> bool {
+ fn precedes_in_tree_order(&self, projection: &Projection, a: StyleNodeID, b: StyleNodeID) -> bool {
if a == b {
return false;
}
- // Climb the deeper of the two to the other's level. Arriving at the other node says it is
- // an ancestor, and an ancestor always comes first.
- let (mut left, mut right) = (a, b);
- for _ in self.depth(b)..self.depth(a) {
- let Some(parent) = self.parent(left) else {
- return false;
- };
- left = parent;
- }
- if left == b {
+ // The ancestor chains of the two, each from the node up to its root.
+ let chain = |node: StyleNodeID| {
+ let mut chain: SmallVec<[StyleNodeID; 32]> = SmallVec::new();
+ let mut next = Some(node);
+ while let Some(node) = next {
+ chain.push(node);
+ next = projection.parent(node);
+ }
+ chain
+ };
+ let (a_chain, b_chain) = (chain(a), chain(b));
+ // Walk both from the root end to where they part. A node on the other's chain is its ancestor, and an
+ // ancestor always comes first.
+ let shared = a_chain
+ .iter()
+ .rev()
+ .zip(b_chain.iter().rev())
+ .take_while(|(a, b)| a == b)
+ .count();
+ if shared == 0 {
return false;
}
- for _ in self.depth(a)..self.depth(b) {
- let Some(parent) = self.parent(right) else {
- return false;
- };
- right = parent;
+ if shared == b_chain.len() {
+ return false;
}
- if right == a {
+ if shared == a_chain.len() {
return true;
}
- while self.parent(left) != self.parent(right) {
- let (Some(next_left), Some(next_right)) = (self.parent(left), self.parent(right)) else {
- return false;
- };
- left = next_left;
- right = next_right;
- }
+ let left = a_chain[a_chain.len() - shared - 1];
+ let right = b_chain[b_chain.len() - shared - 1];
// Siblings now, so whichever the child sequence reaches first comes first.
- let mut sibling = self.next_element_sibling(left);
+ let mut sibling = projection.next_element_sibling(left);
while let Some(node) = sibling {
if node == right {
return true;
}
- sibling = self.next_element_sibling(node);
+ sibling = projection.next_element_sibling(node);
}
false
}
+}
- // -- Shadow relations --------------------------------------------------------------------
+/// The rows of text identities, indexed by text index with slot 0 unused. A text node owns no
+/// element relations, only its place in the DOM child sequence. A retired index waits in
+/// `pending_reuse` until its epoch retires, as an element's does.
+#[derive(Clone, Default)]
+struct TextRows {
+ /// Where each text node stands in its parent's DOM child sequence. Copied on write in chunks, so that a fork
+ /// shares it.
+ links: CowColumn<TextLinks, TEXT_LINKS_PER_CHUNK>,
+ /// What each text node is, as `TextFlags`. Copied on write in chunks, so that a fork shares it.
+ flags: CowColumn<TextFlags, TEXT_FLAGS_PER_CHUNK>,
+ /// The characters the node holds, sharing the document's string rather than copying it. The
+ /// layout tree build reads them to render a text box, so they are published where the node
+ /// arrives and wherever its data is replaced. Copied on write in chunks, as the flags are.
+ data: CowColumn<ak::Utf16String, TEXT_DATA_PER_CHUNK>,
+ pending_reuse: Vec<u32>,
+}
- fn shadow_mut(&mut self) -> &mut ShadowRelations {
- self.shadow.get_or_insert_with(Box::default)
- }
+/// How many text nodes a chunk of [`TextRows`]'s links holds.
+const TEXT_LINKS_PER_CHUNK: usize = 64;
+/// How many text nodes a chunk of [`TextRows`]'s flags holds.
+const TEXT_FLAGS_PER_CHUNK: usize = 64;
+/// How many text nodes a chunk of [`TextRows`]'s data holds.
+const TEXT_DATA_PER_CHUNK: usize = 64;
+
+/// Where one text node stands in its parent's DOM child sequence.
+#[derive(Clone, Copy, Default, PartialEq, Eq)]
+struct TextLinks {
+ parent: Option<StyleNodeID>,
+ next_sibling: Option<StyleNodeID>,
+ previous_sibling: Option<StyleNodeID>,
+}
- #[must_use]
- #[cfg(test)]
- pub fn has_shadow_relations(&self) -> bool {
- self.shadow.is_some()
- }
+const _: () = assert!(size_of::<TextLinks>() == 12);
- /// Record that `host` hosts `shadow_root`.
- pub fn set_shadow_root(&mut self, host: StyleNodeID, shadow_root: StyleNodeID) {
- self.dom_order_version += 1;
+/// What one text node is.
+#[derive(Clone, Copy, Default, PartialEq, Eq)]
+struct TextFlags(u8);
- let shadow = self.shadow_mut();
- if let Some(previous_root) = shadow.shadow_root.insert(host, shadow_root)
- && previous_root != shadow_root
- && shadow.host.get(previous_root) == Some(host)
- {
- shadow.host.remove(previous_root);
- }
- if let Some(previous_host) = shadow.host.insert(shadow_root, host)
- && previous_host != host
- && shadow.shadow_root.get(previous_host) == Some(shadow_root)
- {
- shadow.shadow_root.remove(previous_host);
- }
- }
+impl TextFlags {
+ const LIVE: u8 = 1 << 0;
+ /// Whether the node's data is nothing but ASCII whitespace, which is what decides whether the
+ /// layout tree build can collapse it away rather than give it a box of its own.
+ const IS_ASCII_WHITESPACE: u8 = 1 << 1;
+ /// Whether the node sits in a user agent shadow tree. An element records the same fact among
+ /// its construction facts; a text node has no element columns, so it records it here.
+ const IS_IN_USER_AGENT_SHADOW_TREE: u8 = 1 << 2;
+ /// Whether the node is the text of a password input, which renders as replacement characters.
+ const IS_PASSWORD_INPUT: u8 = 1 << 3;
+}
- #[must_use]
- pub fn shadow_root_of(&self, host: StyleNodeID) -> Option<StyleNodeID> {
- self.shadow.as_ref()?.shadow_root.get(host)
+impl TextRows {
+ fn links(&self, index: u32) -> TextLinks {
+ self.links.get(index as usize).copied().unwrap_or_default()
}
- #[must_use]
- pub fn host_of(&self, shadow_root: StyleNodeID) -> Option<StyleNodeID> {
- self.shadow.as_ref()?.host.get(shadow_root)
+ fn edit_links(&mut self, index: u32, edit: impl FnOnce(&mut TextLinks)) {
+ let mut links = self.links(index);
+ edit(&mut links);
+ self.links
+ .set(index as usize, links)
+ .expect("a minted text identity has a links row");
}
- /// The node's parent in the tree it is in, or a shadow root's host: the host's
- /// `parent_or_shadow_host()`, so a slotted element continues through its light-tree parent.
- #[must_use]
- pub fn parent_or_shadow_host(&self, node: StyleNodeID) -> Option<StyleNodeID> {
- self.parent(node).or_else(|| self.host_of(node))
+ fn flag(&self, index: u32, flag: u8) -> bool {
+ self.flags.get(index as usize).is_some_and(|flags| flags.0 & flag != 0)
}
- /// Assign `node` to `slot`. Passing `None` removes the assignment.
- ///
- /// Slot assignment changes flat-tree identity even when the DOM parent does not move, which is
- /// why it is its own relation rather than a derived view of the DOM tree.
- pub fn set_assigned_slot(&mut self, node: StyleNodeID, slot: Option<StyleNodeID>) {
- if slot.is_none()
- && self
- .shadow
- .as_ref()
- .is_none_or(|shadow| shadow.assigned_slot.get(node).is_none())
- {
- return;
- }
-
- let shadow = self.shadow_mut();
- shadow.assigned_slot.remove(node);
- if let Some(slot) = slot {
- shadow.assigned_slot.insert(node, slot);
- }
- }
-
- /// Replace the ordered list of nodes `slot` has assigned to it.
- ///
- /// The list is published whole rather than assembled from the per-element assignments above,
- /// because neither of the two things it has to be can be recovered from them. A text node is a
- /// slottable but holds no relation row, so its assignment cannot be staged beside an element's;
- /// and the order is the DOM's, not the order assignments arrive in: a manual assignment orders
- /// its nodes the way `assign()` named them, and a reorder among a slot's own assignees changes
- /// no node's slot at all.
- pub fn set_assigned_nodes(&mut self, slot: StyleNodeID, nodes: &[StyleNodeID]) {
- if nodes.is_empty()
- && self
- .shadow
- .as_ref()
- .is_none_or(|shadow| !shadow.assigned_nodes.contains_key(&slot))
- {
- return;
- }
-
- let shadow = self.shadow_mut();
- let mut assigned = shadow.assigned_nodes.remove(&slot).unwrap_or_default();
- // A tree-wide assignment can have moved one of the departing text nodes to another slot
- // already, and this slot must not take that newer assignment away again.
- for node in &assigned {
- if shadow.text_assigned_slot.get(node) == Some(&slot) {
- shadow.text_assigned_slot.remove(node);
- }
- }
- assigned.clear();
- assigned.extend_from_slice(nodes);
- for &node in &assigned {
- if node.text_index().is_some() {
- shadow.text_assigned_slot.insert(node, slot);
- }
- }
- if !assigned.is_empty() {
- shadow.assigned_nodes.insert(slot, assigned);
- }
- }
-
- /// The shadow host of the tree `node` is in, if it is in one.
- ///
- /// A shadow root is the parent its top-level children name, so the root of a node's parent
- /// chain is the shadow root when there is one, and that root knows its host.
- #[must_use]
- pub fn shadow_host_of(&self, node: StyleNodeID) -> Option<StyleNodeID> {
- let shadow = self.shadow.as_ref()?;
- let mut root = node;
- while let Some(parent) = self.parent(root) {
- root = parent;
- }
- shadow.host.get(root)
- }
-
- #[must_use]
- pub fn assigned_slot_of(&self, node: StyleNodeID) -> Option<StyleNodeID> {
- let shadow = self.shadow.as_ref()?;
- if node.text_index().is_some() {
- return shadow.text_assigned_slot.get(&node).copied();
- }
- shadow.assigned_slot.get(node)
- }
-
- #[must_use]
- pub fn assigned_nodes_of(&self, slot: StyleNodeID) -> &[StyleNodeID] {
- self.shadow
- .as_ref()
- .and_then(|shadow| shadow.assigned_nodes.get(&slot))
- .map_or(&[], Vec::as_slice)
- }
-
- pub fn set_part_hosts(&mut self, node: StyleNodeID, pairs: &[(StyleAtomID, StyleNodeID)]) {
- let shadow = self.shadow_mut();
- if pairs.is_empty() {
- shadow.part_hosts.remove(&node);
- } else {
- pairs.clone_into(shadow.part_hosts.entry(node).or_default());
- }
- }
-
- pub fn set_backing_pseudo_kind(&mut self, node: StyleNodeID, kind: Option<u16>) {
- match kind {
- Some(kind) => {
- self.shadow_mut().backing_pseudo_kinds.insert(node, kind);
- }
- None => {
- if let Some(shadow) = self.shadow.as_mut() {
- shadow.backing_pseudo_kinds.remove(&node);
- }
- }
- }
- }
-
- /// The element-backed pseudo-element kind the element stands for on its shadow host.
- #[must_use]
- pub fn backing_pseudo_kind_of(&self, node: StyleNodeID) -> Option<u16> {
- self.shadow
- .as_ref()
- .and_then(|shadow| shadow.backing_pseudo_kinds.get(&node))
- .copied()
- }
-
- /// Every (name, host) pair the element answers a `::part()` rule under.
- #[must_use]
- pub fn part_hosts_of(&self, node: StyleNodeID) -> &[(StyleAtomID, StyleNodeID)] {
- self.shadow
- .as_ref()
- .and_then(|shadow| shadow.part_hosts.get(&node))
- .map_or(&[], Vec::as_slice)
- }
-
- /// The flat-tree children of `node`: what inheritance and `::slotted()` actually walk.
- ///
- /// The flat tree diverges from the DOM tree in exactly two places. A shadow host's flat-tree
- /// children are its shadow root's children, and a slot's are its assigned nodes - falling back
- /// to its DOM children when nothing is assigned, which is what fallback content means.
- #[must_use]
- pub fn flat_tree_children(&self, node: StyleNodeID) -> FlatTreeChildren<'_> {
- let Some(shadow) = self.shadow.as_ref() else {
- return FlatTreeChildren::Dom(self.children(node));
- };
- if let Some(shadow_root) = shadow.shadow_root.get(node) {
- return FlatTreeChildren::Dom(self.children(shadow_root));
- }
- match shadow.assigned_nodes.get(&node) {
- Some(nodes) if !nodes.is_empty() => FlatTreeChildren::Assigned(nodes.iter()),
- _ => FlatTreeChildren::Dom(self.children(node)),
- }
- }
-
- /// The flat-tree parent whose inherited style an element consumes.
- #[must_use]
- pub fn flat_tree_parent(&self, node: StyleNodeID) -> Option<StyleNodeID> {
- if let Some(slot) = self.assigned_slot_of(node) {
- return Some(slot);
- }
- let parent = self.parent(node)?;
- if let Some(host) = self.host_of(parent) {
- return Some(host);
- }
- let shadow = self.shadow.as_ref();
- if shadow.is_some_and(|shadow| shadow.shadow_root.get(parent).is_some()) {
- return None;
- }
- if shadow
- .and_then(|shadow| shadow.assigned_nodes.get(&parent))
- .is_some_and(|assigned| !assigned.is_empty())
- {
- return None;
- }
- Some(parent)
- }
-
- /// The element whose computed values this element inherits. Unlike [`Self::flat_tree_parent`],
- /// this keeps the DOM parent of an element excluded from the flat tree: such an element can
- /// still have its style requested through CSSOM and inherits from that parent when it does.
- #[must_use]
- pub fn inheritance_parent(&self, node: StyleNodeID) -> Option<StyleNodeID> {
- if let Some(slot) = self.assigned_slot_of(node) {
- return Some(slot);
- }
- let parent = match node.text_index() {
- Some(_) => self.text_parent(node)?,
- None => self.parent(node)?,
- };
- Some(self.host_of(parent).unwrap_or(parent))
- }
-
- /// The inheritance relations and editable identities an immutable hover reads for cursor selection.
- pub(crate) fn hover_cursor_relations(&self) -> (Vec<Option<StyleNodeID>>, Vec<StyleNodeID>) {
- let mut parents = self.parent.clone();
- if self.shadow.is_some() {
- for (index, parent) in parents.iter_mut().enumerate().skip(1) {
- *parent = self.inheritance_parent(StyleNodeID::element(index as u32));
- }
- }
- let editable = self
- .dom_paint_facts
- .iter()
- .filter_map(|(&node, &facts)| {
- (facts & crate::layout::node_data::DomPaintFact::EditableOrEditingHost as u8 != 0).then_some(node)
- })
- .collect();
- (parents, editable)
- }
-
- /// Compare nodes in the order C++ must apply style reactions.
- ///
- /// This is preorder over the style-inheritance tree, extended to keep shadow-tree children
- /// before a host's light-tree children and slot fallback before assigned slottables. Comparing
- /// relation columns directly avoids materializing an ancestor path for every reaction.
- #[must_use]
- pub fn compare_style_reaction_order(&self, first: StyleNodeID, second: StyleNodeID) -> Ordering {
- if first == second {
- return Ordering::Equal;
- }
-
- let relation_depth = |mut node| {
- let mut depth = 0u32;
- while let Some((parent, _)) = self.style_reaction_parent(node) {
- node = parent;
- depth += 1;
- }
- depth
- };
-
- let mut first_node = first;
- let mut second_node = second;
- let mut first_depth = relation_depth(first);
- let mut second_depth = relation_depth(second);
- while first_depth > second_depth {
- first_node = self
- .style_reaction_parent(first_node)
- .expect("a non-root reaction node must have a parent")
- .0;
- first_depth -= 1;
- if first_node == second_node {
- return Ordering::Greater;
- }
- }
- while second_depth > first_depth {
- second_node = self
- .style_reaction_parent(second_node)
- .expect("a non-root reaction node must have a parent")
- .0;
- second_depth -= 1;
- if second_node == first_node {
- return Ordering::Less;
- }
- }
-
- loop {
- let first_parent = self.style_reaction_parent(first_node);
- let second_parent = self.style_reaction_parent(second_node);
- if first_parent.map(|(parent, _)| parent) == second_parent.map(|(parent, _)| parent) {
- let first_branch = first_parent.map_or(0, |(_, branch)| branch);
- let second_branch = second_parent.map_or(0, |(_, branch)| branch);
- return (first_branch, first_node.raw()).cmp(&(second_branch, second_node.raw()));
- }
- first_node = first_parent
- .expect("different reaction roots must meet at the virtual root")
- .0;
- second_node = second_parent
- .expect("different reaction roots must meet at the virtual root")
- .0;
- }
- }
-
- /// Rank a batch in the same dependency order as `compare_style_reaction_order`.
- /// Each ancestor is visited once, even for a deep chain of reacting descendants.
- /// Whether ranking a batch of `count` nodes with [`Self::style_reaction_order_ranks`] costs less than comparing
- /// them pairwise with [`Self::compare_style_reaction_order`]. The ranks are as long as the highest element slot
- /// they reach, so a small batch, or one that is small beside the tree, is compared directly instead.
- #[must_use]
- pub fn style_reaction_order_ranks_pay_off(&self, count: usize) -> bool {
- count > 32 && count.saturating_mul(64) >= self.parent.len()
- }
-
- pub fn style_reaction_order_ranks(&self, nodes: impl IntoIterator<Item = StyleNodeID>) -> StyleReactionOrderRanks {
- // NB: Each rank starts out unranked, becomes seen once the node's chain was walked, and is
- // assigned in the walk down from the roots.
- let mut ranks = Vec::new();
- let mark_seen = |ranks: &mut Vec<usize>, node: StyleNodeID| {
- let slot = self.element_index(node);
- if ranks.len() <= slot {
- ranks.resize(slot + 1, StyleReactionOrderRanks::UNRANKED);
- }
- std::mem::replace(&mut ranks[slot], StyleReactionOrderRanks::SEEN) != StyleReactionOrderRanks::SEEN
- };
- let mut edges: Vec<(StyleNodeID, u8, StyleNodeID)> = Vec::new();
- let mut roots = Vec::new();
- for mut node in nodes {
- while mark_seen(&mut ranks, node) {
- if let Some((parent, branch)) = self.style_reaction_parent(node) {
- edges.push((parent, branch, node));
- node = parent;
- } else {
- roots.push(node);
- break;
- }
- }
- }
- // NB: The existing order uses identity within each branch, not DOM sibling order. The edges of
- // each parent are a run, with its children in descending order so that the walk, which
- // takes the last pending node first, visits them in ascending order.
- roots.sort_unstable_by(|first, second| second.cmp(first));
- edges.sort_unstable_by(|first, second| {
- first
- .0
- .cmp(&second.0)
- .then_with(|| (second.1, second.2).cmp(&(first.1, first.2)))
- });
- // NB: Where each parent's run of edges starts, and where it ends.
- let mut child_runs = vec![(0_u32, 0_u32); ranks.len()];
- for (index, &(parent, _, _)) in edges.iter().enumerate() {
- let run = &mut child_runs[self.element_index(parent)];
- if run.0 == run.1 {
- run.0 = index as u32;
- }
- run.1 = index as u32 + 1;
- }
- let mut count = 0;
- let mut pending = roots;
- while let Some(node) = pending.pop() {
- let slot = self.element_index(node);
- ranks[slot] = count;
- count += 1;
- let (start, end) = child_runs[slot];
- pending.extend(edges[start as usize..end as usize].iter().map(|&(_, _, child)| child));
- }
- StyleReactionOrderRanks { ranks }
- }
-
- fn style_reaction_parent(&self, node: StyleNodeID) -> Option<(StyleNodeID, u8)> {
- if let Some(slot) = self.assigned_slot_of(node) {
- return Some((slot, 2));
- }
- let parent = self.parent(node)?;
- if let Some(host) = self.host_of(parent) {
- return Some((host, 0));
- }
- let branch = u8::from(self.shadow_root_of(parent).is_some());
- Some((parent, branch))
- }
-
- // -- Navigation --------------------------------------------------------------------------
-
- #[must_use]
- pub fn parent(&self, node: StyleNodeID) -> Option<StyleNodeID> {
- self.parent[self.element_index(node)]
- }
-
- #[must_use]
- pub fn first_element_child(&self, node: StyleNodeID) -> Option<StyleNodeID> {
- self.first_element_child[self.element_index(node)]
- }
-
- #[must_use]
- pub fn next_element_sibling(&self, node: StyleNodeID) -> Option<StyleNodeID> {
- self.next_element_sibling[self.element_index(node)]
- }
-
- #[must_use]
- pub fn tree_scope(&self, node: StyleNodeID) -> TreeScopeID {
- match self.tree_scope.as_ref() {
- Some(column) => column[self.element_index(node)],
- None => TreeScopeID::DOCUMENT,
- }
- }
-
- #[must_use]
- pub fn depth(&self, node: StyleNodeID) -> u32 {
- self.depth[self.element_index(node)]
- }
-
- /// The preceding element sibling, served from a resident column.
- ///
- /// This column earned its four bytes per element by measurement: the scan it replaced walked
- /// the child sequence per backward hop, and waypoint checks walking sibling steps backwards
- /// were paying it once per candidate, 19 percent of sibling-heavy style updates.
- #[must_use]
- pub fn previous_element_sibling(&self, node: StyleNodeID) -> Option<StyleNodeID> {
- self.previous_element_sibling[self.element_index(node)]
- }
-
- #[must_use]
- pub fn children(&self, node: StyleNodeID) -> Children<'_> {
- Children {
- tree: self,
- next: self.first_element_child(node),
- }
- }
-
- #[must_use]
- pub fn ancestors(&self, node: StyleNodeID) -> Ancestors<'_> {
- Ancestors {
- tree: self,
- next: self.parent(node),
- }
- }
-
- /// Preorder stream of `root` and its descendants. Broad regions are streamed this way rather
- /// than joined against postings.
- #[must_use]
- pub fn preorder(&self, root: StyleNodeID) -> Preorder<'_> {
- Preorder {
- tree: self,
- root,
- next: Some(root),
- }
- }
-
- /// Whether `node` lies inside the subtree rooted at `root`. Because `StyleNodeID` is not a
- /// tree-order label, a subtree impact region is not a numeric interval. The depth column rejects
- /// impossible membership immediately and bounds the remaining parent walk exactly.
- #[must_use]
- pub fn is_in_subtree_of(&self, node: StyleNodeID, root: StyleNodeID) -> bool {
- let node_depth = self.depth(node);
- let root_depth = self.depth(root);
- if node_depth < root_depth {
- return false;
- }
- let mut candidate = node;
- for _ in root_depth..node_depth {
- let Some(parent) = self.parent(candidate) else {
- return false;
- };
- candidate = parent;
- }
- candidate == root
- }
-
- /// Whether `node` is `root` or lies below it in the shadow-including tree: the climb out of a
- /// shadow tree continues at the host rather than stopping there.
- ///
- /// `root` names an element or a shadow root. A climb that runs out of parents has reached a
- /// child of the document, which no element contains, so it answers false rather than taking a
- /// document identity to compare against.
- #[must_use]
- pub fn is_in_shadow_including_subtree_of(&self, node: StyleNodeID, root: StyleNodeID) -> bool {
- if node == root {
- return true;
- }
- if root.text_index().is_some() {
- return false;
- }
- // Only an element owns a child sequence, so a text node is answered for by the element it
- // is linked under.
- let mut candidate = match node.text_index() {
- Some(_) => match self.text_parent(node) {
- Some(parent) => parent,
- None => return false,
- },
- None => node,
- };
- loop {
- if candidate == root {
- return true;
- }
- candidate = match self.host_of(candidate) {
- Some(host) => host,
- None => match self.parent(candidate) {
- Some(parent) => parent,
- None => return false,
- },
- };
- }
- }
-
- // -- Accounting --------------------------------------------------------------------------
-
- fn element_index(&self, node: StyleNodeID) -> usize {
- debug_assert!(
- node.element_index().is_some(),
- "tree relations are keyed by element identity"
- );
- node.element_slot()
- }
-
- fn live_element_index(&self, node: StyleNodeID) -> usize {
- let index = node
- .element_index()
- .expect("tree relations are keyed by element identity");
- assert!(
- self.live.contains(index as usize),
- "mutating relations of a retired identity"
- );
- index as usize
+ fn set_flag(&mut self, index: u32, flag: u8, value: bool) {
+ let index = index as usize;
+ self.flags.grow_to(index + 1);
+ let flags = *self
+ .flags
+ .get(index)
+ .expect("the column was just grown to hold the row");
+ let flags = TextFlags(match value {
+ true => flags.0 | flag,
+ false => flags.0 & !flag,
+ });
+ self.flags.set(index, flags);
}
}
-/// The rows of text identities, indexed by text index with slot 0 unused. A text node owns no
-/// element relations, only its place in the DOM child sequence. A retired index waits in
-/// `pending_reuse` until its epoch retires, as an element's does.
-#[derive(Clone, Default)]
-struct TextRows {
- parent: Vec<Option<StyleNodeID>>,
- next_sibling: Vec<Option<StyleNodeID>>,
- previous_sibling: Vec<Option<StyleNodeID>>,
- live: BitColumn,
- /// Whether the node's data is nothing but ASCII whitespace, which is what decides whether the
- /// layout tree build can collapse it away rather than give it a box of its own.
- is_ascii_whitespace: BitColumn,
- /// Whether the node sits in a user agent shadow tree. An element records the same fact among
- /// its construction facts; a text node has no element columns, so it records it here.
- is_in_user_agent_shadow_tree: BitColumn,
- /// Whether the node is the text of a password input, which renders as replacement characters.
- is_password_input: BitColumn,
- /// The characters the node holds, sharing the document's string rather than copying it. The
- /// layout tree build reads them to render a text box, so they are published where the node
- /// arrives and wherever its data is replaced.
- data: Vec<ak::Utf16String>,
- pending_reuse: Vec<u32>,
-}
-
-impl TextRows {}
-
pub struct DomChildren<'a> {
- tree: &'a StyleNodeTree,
+ tree: &'a HostTree,
next: Option<StyleNodeID>,
}
@@ -2074,93 +1228,25 @@ impl Iterator for DomChildren<'_> {
}
}
-pub struct Children<'a> {
- tree: &'a StyleNodeTree,
- next: Option<StyleNodeID>,
-}
-
-impl Iterator for Children<'_> {
- type Item = StyleNodeID;
-
- fn next(&mut self) -> Option<StyleNodeID> {
- let current = self.next?;
- self.next = self.tree.next_element_sibling(current);
- Some(current)
- }
-}
-
-pub struct Ancestors<'a> {
- tree: &'a StyleNodeTree,
- next: Option<StyleNodeID>,
-}
-
-impl Iterator for Ancestors<'_> {
- type Item = StyleNodeID;
-
- fn next(&mut self) -> Option<StyleNodeID> {
- let current = self.next?;
- self.next = self.tree.parent(current);
- Some(current)
- }
-}
-
-pub struct Preorder<'a> {
- tree: &'a StyleNodeTree,
- root: StyleNodeID,
- next: Option<StyleNodeID>,
-}
-
-impl Iterator for Preorder<'_> {
- type Item = StyleNodeID;
-
- fn next(&mut self) -> Option<StyleNodeID> {
- let current = self.next?;
- self.next = self.tree.first_element_child(current).or_else(|| {
- let mut node = current;
- loop {
- if node == self.root {
- return None;
- }
- if let Some(sibling) = self.tree.next_element_sibling(node) {
- return Some(sibling);
- }
- node = self.tree.parent(node)?;
- }
- });
- Some(current)
- }
-}
-
-/// Where each node of a batch, and each node on the chains above them, stands in the order style
-/// reactions apply, indexed by the node.
-pub struct StyleReactionOrderRanks {
- ranks: Vec<usize>,
-}
-
-impl StyleReactionOrderRanks {
- const UNRANKED: usize = usize::MAX;
- const SEEN: usize = usize::MAX - 1;
-
- #[cfg(test)]
- fn len(&self) -> usize {
- self.ranks.iter().filter(|&&rank| rank < Self::SEEN).count()
- }
-}
-
-impl std::ops::Index<&StyleNodeID> for StyleReactionOrderRanks {
- type Output = usize;
-
- fn index(&self, node: &StyleNodeID) -> &usize {
- let rank = &self.ranks[node.element_slot()];
- assert!(*rank < Self::SEEN, "a node outside the ranked batch has no rank");
- rank
- }
-}
-
#[cfg(test)]
mod tests {
use super::*;
+ #[test]
+ fn a_fork_writing_one_text_link_copies_one_chunk_of_links() {
+ let mut tree = HostTree::new();
+ let texts: Vec<StyleNodeID> = (0..8 * TEXT_LINKS_PER_CHUNK).map(|_| tree.allocate_text()).collect();
+ let mut fork = tree.clone();
+ let mut sizer = crate::heap_size::HeapSizer::default();
+ let whole = tree.text.links.heap_size(&mut sizer, |_, _| 0);
+ assert!(whole > 8 * TEXT_LINKS_PER_CHUNK * size_of::<TextLinks>());
+ fork.set_next_sibling(texts[70], Some(texts[71]));
+ let copied = fork.text.links.heap_size(&mut sizer, |_, _| 0);
+ assert!(copied < 3 * TEXT_LINKS_PER_CHUNK * size_of::<TextLinks>());
+ assert_eq!(fork.next_sibling_in_dom_order(texts[70]), Some(texts[71]));
+ assert_eq!(tree.next_sibling_in_dom_order(texts[70]), None);
+ }
+
#[test]
fn element_and_text_identities_index_their_own_kinds() {
let element = StyleNodeID::element(7);
@@ -2173,102 +1259,65 @@ mod tests {
assert_eq!(StyleNodeID::from_raw(text.raw()), Some(text));
}
- #[test]
- fn radix_sorts_style_node_identities() {
- let mut nodes = vec![
- StyleNodeID::element(i32::MAX as u32),
- StyleNodeID::element(256),
- StyleNodeID::element(65_536),
- StyleNodeID::element(255),
- StyleNodeID::element(1),
- ];
-
- nodes = radix_sort_style_node_ids(nodes);
-
- assert_eq!(
- nodes,
- vec![
- StyleNodeID::element(1),
- StyleNodeID::element(255),
- StyleNodeID::element(256),
- StyleNodeID::element(65_536),
- StyleNodeID::element(i32::MAX as u32),
- ]
- );
- }
-
- #[test]
- fn tree_staging_keeps_exact_before_and_after_rows_across_apply() {
- let node = StyleNodeID::element(1);
- let parent = StyleNodeID::element(2);
- let final_first_child = StyleNodeID::element(4);
- let mut first_after = TreeRelations::detached(TreeScopeID::DOCUMENT);
- let before = Some(first_after);
- first_after.parent = Some(parent);
- let mut final_after = first_after;
- final_after.assigned_slot = Some(StyleNodeID::element(3));
- let mut staging = TreeRelationStaging::default();
-
- staging.stage_row(node, before, Some(first_after));
- staging.stage_first_child(parent, None, Some(node));
- staging.mark_applied();
- assert!(staging.dirty_rows().is_empty());
- assert!(staging.dirty_first_children().next().is_none());
- staging.stage_row(node, Some(first_after), Some(final_after));
- staging.stage_first_child(parent, Some(node), Some(final_first_child));
-
- assert_eq!(staging.current_row(node, None), Some(final_after));
- assert_eq!(staging.before_relations(node, Some(final_after)), before);
- assert_eq!(staging.before_first_child(parent, Some(final_first_child)), None);
- assert!(!staging.is_applied());
- let rows: Vec<_> = staging.rows().collect();
- let first_children: Vec<_> = staging.first_children().collect();
- assert_eq!(rows, vec![(node, before, Some(final_after))]);
- assert_eq!(first_children, vec![(parent, None, Some(final_first_child))]);
- assert!(!staging.is_empty());
- }
-
- #[test]
- fn dirty_tree_rows_are_sorted_by_node_identity() {
- let low = StyleNodeID::element(1);
- let high = StyleNodeID::element(70);
- let relations = Some(TreeRelations::detached(TreeScopeID::DOCUMENT));
- let mut staging = TreeRelationStaging::default();
-
- staging.stage_row(high, None, relations);
- staging.stage_row(low, None, relations);
-
- assert_eq!(
- staging.dirty_rows(),
- vec![(low, None, relations), (high, None, relations)]
- );
- }
-
- /// Builds `parent -> [children]` shapes without repeating relation bookkeeping in every test.
+ /// Builds `parent -> [children]` shapes in the projection beside the tree without repeating
+ /// relation bookkeeping in every test.
struct TreeFixture {
- tree: StyleNodeTree,
+ tree: HostTree,
+ projection: Projection,
}
impl TreeFixture {
fn new() -> Self {
- let tree = StyleNodeTree::new();
- Self { tree }
+ Self {
+ tree: HostTree::new(),
+ projection: Projection::default(),
+ }
}
fn element(&mut self) -> StyleNodeID {
- self.tree.allocate_element()
+ let node = self.tree.allocate_element();
+ self.projection.mint(node);
+ self.projection.set_connected(node, true);
+ node
}
+ /// Write the links of `children` under `parent`. [`Self::commit`] makes them the ones read.
fn attach_children(&mut self, parent: StyleNodeID, children: &[StyleNodeID]) {
- self.tree.set_first_element_child(parent, children.first().copied());
+ self.projection
+ .set_first_element_child(parent, children.first().copied());
for (index, &child) in children.iter().enumerate() {
- self.tree.set_parent(child, Some(parent));
- self.tree
+ self.projection.set_parent(child, Some(parent));
+ self.projection
.set_next_element_sibling(child, children.get(index + 1).copied());
- self.tree
+ self.projection
.set_previous_element_sibling(child, index.checked_sub(1).map(|index| children[index]));
}
}
+
+ fn retire(&mut self, nodes: &[StyleNodeID]) {
+ self.tree.retire_elements(nodes);
+ for &node in nodes {
+ self.projection.retire(node);
+ }
+ }
+
+ /// Make the written links the ones read, and the depths the ones they give.
+ fn commit(&mut self) {
+ let roots: Vec<StyleNodeID> = self
+ .tree
+ .live_nodes()
+ .filter(|&node| {
+ self.projection
+ .written_relations(node)
+ .is_none_or(|relations| relations.parent.is_none())
+ })
+ .collect();
+ for root in roots {
+ let _ = self.tree.deepest_depth_under(&self.projection, root);
+ }
+ self.projection.commit();
+ self.projection.release();
+ }
}
#[test]
@@ -2301,19 +1350,40 @@ mod tests {
let nested = fixture.element();
fixture.attach_children(root, &[first, second]);
fixture.attach_children(first, &[nested]);
+ fixture.commit();
let name = StyleAtomID(7);
// The order the elements take the name in is not tree order.
fixture.tree.set_element_id_name(second, name);
fixture.tree.set_element_id_name(nested, name);
- assert_eq!(fixture.tree.element_by_id(TreeScopeID::DOCUMENT, name), Some(nested));
+ assert_eq!(
+ fixture
+ .tree
+ .element_by_id(&fixture.projection, TreeScopeID::DOCUMENT, name),
+ Some(nested)
+ );
fixture.tree.set_element_id_name(first, name);
- assert_eq!(fixture.tree.element_by_id(TreeScopeID::DOCUMENT, name), Some(first));
+ assert_eq!(
+ fixture
+ .tree
+ .element_by_id(&fixture.projection, TreeScopeID::DOCUMENT, name),
+ Some(first)
+ );
fixture.tree.set_element_id_name(first, StyleAtomID::NONE);
- assert_eq!(fixture.tree.element_by_id(TreeScopeID::DOCUMENT, name), Some(nested));
- assert_eq!(fixture.tree.element_by_id(TreeScopeID::DOCUMENT, StyleAtomID(8)), None);
+ assert_eq!(
+ fixture
+ .tree
+ .element_by_id(&fixture.projection, TreeScopeID::DOCUMENT, name),
+ Some(nested)
+ );
+ assert_eq!(
+ fixture
+ .tree
+ .element_by_id(&fixture.projection, TreeScopeID::DOCUMENT, StyleAtomID(8)),
+ None
+ );
}
#[test]
@@ -2322,22 +1392,26 @@ mod tests {
let root = fixture.element();
let children = [fixture.element(), fixture.element(), fixture.element()];
fixture.attach_children(root, &children);
+ fixture.commit();
// Three elements sharing a name spill its candidate list out of line.
let name = StyleAtomID(7);
for child in children {
fixture.tree.set_element_id_name(child, name);
}
assert_eq!(
- fixture.tree.element_by_id(TreeScopeID::DOCUMENT, name),
+ fixture
+ .tree
+ .element_by_id(&fixture.projection, TreeScopeID::DOCUMENT, name),
Some(children[0])
);
- for child in children {
- fixture.tree.set_parent(child, None);
- }
- fixture.tree.set_first_element_child(root, None);
- fixture.tree.retire_elements(&children);
- assert_eq!(fixture.tree.element_by_id(TreeScopeID::DOCUMENT, name), None);
+ fixture.retire(&children);
+ assert_eq!(
+ fixture
+ .tree
+ .element_by_id(&fixture.projection, TreeScopeID::DOCUMENT, name),
+ None
+ );
// The spilled list went with the name, and the controller was told.
}
@@ -2353,68 +1427,7 @@ mod tests {
}
#[test]
- fn traversal_walks_the_resident_columns() {
- let mut fixture = TreeFixture::new();
- let root = fixture.element();
- let first = fixture.element();
- let second = fixture.element();
- let third = fixture.element();
- let grandchild = fixture.element();
- fixture.attach_children(root, &[first, second, third]);
- fixture.attach_children(second, &[grandchild]);
-
- assert_eq!(
- fixture.tree.children(root).collect::<Vec<_>>(),
- vec![first, second, third]
- );
- assert_eq!(
- fixture.tree.ancestors(grandchild).collect::<Vec<_>>(),
- vec![second, root]
- );
- assert_eq!(
- fixture.tree.preorder(root).collect::<Vec<_>>(),
- vec![root, first, second, grandchild, third]
- );
- assert_eq!(
- fixture.tree.preorder(second).collect::<Vec<_>>(),
- vec![second, grandchild]
- );
-
- assert_eq!(fixture.tree.previous_element_sibling(first), None);
- assert_eq!(fixture.tree.previous_element_sibling(third), Some(second));
-
- assert_eq!(fixture.tree.depth(root), 0);
- assert_eq!(fixture.tree.depth(second), 1);
- assert_eq!(fixture.tree.depth(grandchild), 2);
-
- assert!(fixture.tree.is_in_subtree_of(grandchild, root));
- assert!(fixture.tree.is_in_subtree_of(root, root));
- assert!(!fixture.tree.is_in_subtree_of(first, second));
- }
-
- #[test]
- fn moving_a_subtree_updates_every_descendant_depth() {
- let mut fixture = TreeFixture::new();
- let root = fixture.element();
- let first = fixture.element();
- let second = fixture.element();
- let child = fixture.element();
- let grandchild = fixture.element();
- fixture.attach_children(root, &[first, second]);
- fixture.attach_children(first, &[child]);
- fixture.attach_children(child, &[grandchild]);
-
- fixture.attach_children(second, &[first]);
-
- assert_eq!(fixture.tree.depth(first), 2);
- assert_eq!(fixture.tree.depth(child), 3);
- assert_eq!(fixture.tree.depth(grandchild), 4);
- assert!(fixture.tree.is_in_subtree_of(grandchild, second));
- assert!(!fixture.tree.is_in_subtree_of(second, first));
- }
-
- #[test]
- fn staged_parent_changes_recompute_depth_after_final_links_are_installed() {
+ fn the_deepest_depth_follows_the_links_written_into_the_projection() {
let mut fixture = TreeFixture::new();
let root = fixture.element();
let parent = fixture.element();
@@ -2422,18 +1435,35 @@ mod tests {
fixture.attach_children(root, &[parent]);
fixture.attach_children(parent, &[child]);
- fixture.tree.set_parent_without_updating_depth(child, Some(root));
- fixture.tree.set_parent_without_updating_depth(parent, Some(child));
- fixture.tree.set_first_element_child(root, Some(child));
- fixture.tree.set_first_element_child(child, Some(parent));
- fixture.tree.set_first_element_child(parent, None);
- fixture.tree.set_next_element_sibling(parent, None);
- fixture.tree.set_next_element_sibling(child, None);
- fixture.tree.recompute_subtree_depth(child);
+ assert_eq!(fixture.tree.deepest_depth_under(&fixture.projection, root), 2);
+ assert_eq!(fixture.tree.deepest_depth_under(&fixture.projection, child), 2);
+
+ fixture.projection.set_parent(child, Some(root));
+ fixture.projection.set_parent(parent, Some(child));
+ fixture.projection.set_first_element_child(root, Some(child));
+ fixture.projection.set_first_element_child(child, Some(parent));
+ fixture.projection.set_first_element_child(parent, None);
+ fixture.projection.set_next_element_sibling(parent, None);
+ fixture.projection.set_next_element_sibling(child, None);
- assert_eq!(fixture.tree.depth(root), 0);
- assert_eq!(fixture.tree.depth(child), 1);
- assert_eq!(fixture.tree.depth(parent), 2);
+ assert_eq!(fixture.tree.deepest_depth_under(&fixture.projection, child), 2);
+ assert_eq!(fixture.tree.deepest_depth_under(&fixture.projection, parent), 2);
+ assert_eq!(fixture.tree.deepest_depth_under(&fixture.projection, root), 2);
+ }
+
+ #[test]
+ fn a_fork_shares_text_data_and_flags_until_one_side_writes() {
+ let mut tree = HostTree::new();
+ let text = tree.allocate_text();
+ tree.set_text_is_ascii_whitespace(text, true);
+ let fork = tree.clone();
+ let (data_version, flags_version) = (tree.text.data.version(), tree.text.flags.version());
+ tree.set_text_is_ascii_whitespace(text, false);
+ tree.set_text_data(text, ak::Utf16String::from_utf16(&[u16::from(b'x')]));
+ assert!(fork.text_is_ascii_whitespace(text));
+ assert!(fork.text_data(text).is_some_and(ak::Utf16String::is_empty));
+ assert_eq!(tree.text.flags.version(), flags_version + 1);
+ assert_eq!(tree.text.data.version(), data_version + 1);
}
#[test]
@@ -2443,7 +1473,7 @@ mod tests {
let second = fixture.element();
assert_eq!(fixture.tree.connected_element_count(), 2);
- fixture.tree.retire_element(first);
+ fixture.retire(&[first]);
assert!(!fixture.tree.is_live(first));
assert_eq!(fixture.tree.connected_element_count(), 1);
assert_eq!(fixture.tree.retired_identities_pending_release(), 1);
@@ -2494,7 +1524,7 @@ mod tests {
fixture.tree.set_table_spans(element, spans);
assert_eq!(fixture.tree.table_spans(element), spans);
- fixture.tree.retire_element(element);
+ fixture.retire(&[element]);
fixture.tree.release_retired_identities();
assert_eq!(fixture.tree.allocate_element(), element);
assert_eq!(fixture.tree.table_spans(element), TableSpans::default());
@@ -2509,7 +1539,7 @@ mod tests {
fixture.tree.set_top_layer(&[third, first, second]);
assert_eq!(fixture.tree.top_layer(), [third, first, second]);
- fixture.tree.retire_element(first);
+ fixture.retire(&[first]);
assert_eq!(fixture.tree.top_layer(), [third, second]);
fixture.tree.release_retired_identities();
assert_eq!(fixture.tree.allocate_element(), first);
@@ -2529,7 +1559,7 @@ mod tests {
assert_eq!(fixture.tree.dom_paint_facts(element), 0);
fixture.tree.set_dom_paint_facts(element, 1);
- fixture.tree.retire_element(element);
+ fixture.retire(&[element]);
fixture.tree.retire_texts([text]);
fixture.tree.release_retired_identities();
assert_eq!(fixture.tree.allocate_element(), element);
@@ -2554,7 +1584,7 @@ mod tests {
vec![first_text, element, last_text]
);
assert_eq!(fixture.tree.text_parent(last_text), Some(parent));
- assert_eq!(fixture.tree.children(parent).count(), 0);
+ assert_eq!(fixture.projection.children(parent).count(), 0);
assert_eq!(fixture.tree.connected_element_count(), 2);
// A move is an unlink followed by a link at the new place.
@@ -2584,20 +1614,6 @@ mod tests {
assert_eq!(fixture.tree.next_sibling_in_dom_order(reused), None);
}
- #[test]
- fn a_text_slottable_holds_a_place_in_its_slots_assigned_list() {
- let mut fixture = TreeFixture::new();
- let slot = fixture.element();
- let element = fixture.element();
- let text = fixture.tree.allocate_text();
- fixture.tree.set_assigned_nodes(slot, &[text, element]);
- assert_eq!(fixture.tree.assigned_nodes_of(slot), &[text, element]);
- assert_eq!(fixture.tree.assigned_slot_of(text), Some(slot));
-
- fixture.tree.retire_texts([text]);
- assert_eq!(fixture.tree.assigned_nodes_of(slot), &[element]);
- }
-
#[test]
fn a_relation_only_identity_roots_the_dom_child_sequence_without_counting_as_an_element() {
let mut fixture = TreeFixture::new();
@@ -2613,57 +1629,15 @@ mod tests {
fixture.tree.dom_children(document).collect::<Vec<_>>(),
vec![document_element]
);
- assert_eq!(fixture.tree.parent(document_element), None);
+ assert_eq!(fixture.projection.parent(document_element), None);
- fixture.tree.retire_elements(&[document, document_element]);
+ fixture.retire(&[document, document_element]);
assert_eq!(fixture.tree.connected_element_count(), 0);
fixture.tree.release_retired_identities();
let reused = fixture.element();
assert!(!fixture.tree.is_relation_only(reused));
}
- #[test]
- fn a_reused_identity_starts_in_the_document_tree_scope() {
- let mut fixture = TreeFixture::new();
- let node = fixture.element();
- fixture.tree.enable_tree_scopes();
- fixture.tree.set_tree_scope(node, TreeScopeID(1));
- fixture.tree.retire_element(node);
- fixture.tree.release_retired_identities();
-
- let reused = fixture.element();
- assert_eq!(reused, node);
- assert_eq!(fixture.tree.tree_scope(reused), TreeScopeID::DOCUMENT);
- }
-
- #[test]
- fn reused_element_identities_do_not_inherit_shadow_relations() {
- let mut fixture = TreeFixture::new();
- let host = fixture.element();
- let root = fixture.element();
- let slot = fixture.element();
- let slotted = fixture.element();
- let part = StyleAtomID(1);
- fixture.tree.set_shadow_root(host, root);
- fixture.tree.set_assigned_slot(slotted, Some(slot));
- fixture.tree.set_assigned_nodes(slot, &[slotted]);
- fixture.tree.set_part_hosts(host, &[(part, host)]);
-
- fixture.tree.retire_element(host);
- fixture.tree.retire_element(slot);
- assert_eq!(fixture.tree.host_of(root), None);
- assert_eq!(fixture.tree.assigned_slot_of(slotted), None);
-
- fixture.tree.release_retired_identities();
- let reused_slot = fixture.element();
- let reused_host = fixture.element();
- assert_eq!(reused_slot, slot);
- assert_eq!(reused_host, host);
- assert_eq!(fixture.tree.shadow_root_of(reused_host), None);
- assert_eq!(fixture.tree.assigned_nodes_of(reused_slot), &[]);
- assert_eq!(fixture.tree.part_hosts_of(reused_host), &[]);
- }
-
#[test]
fn column_capacity_is_charged_to_tier_one_and_released_with_the_columns() {
let mut fixture = TreeFixture::new();
@@ -2672,257 +1646,6 @@ mod tests {
}
}
- #[test]
- fn a_document_with_no_shadow_tree_pays_nothing_for_the_flat_tree() {
- let mut fixture = TreeFixture::new();
- let parent = fixture.element();
- let child = fixture.element();
- fixture.attach_children(parent, &[child]);
-
- assert!(!fixture.tree.has_shadow_relations());
- assert_eq!(fixture.tree.flat_tree_children(parent).collect::<Vec<_>>(), vec![child]);
- assert_eq!(fixture.tree.assigned_nodes_of(parent), &[]);
- }
-
- #[test]
- fn the_shadow_including_subtree_test_climbs_out_of_a_shadow_tree_to_its_host() {
- let mut fixture = TreeFixture::new();
- let root_element = fixture.element();
- let host = fixture.element();
- let light_child = fixture.element();
- let shadow_root = fixture.element();
- let shadow_child = fixture.element();
- let nested_host = fixture.element();
- let nested_shadow_root = fixture.element();
- let nested_shadow_child = fixture.element();
- let outside = fixture.element();
- let text = fixture.tree.allocate_text();
- fixture.attach_children(root_element, &[host, outside]);
- fixture.attach_children(host, &[light_child]);
- fixture.attach_children(shadow_root, &[shadow_child, nested_host]);
- fixture.tree.set_shadow_root(host, shadow_root);
- fixture.attach_children(nested_shadow_root, &[nested_shadow_child]);
- fixture.tree.set_shadow_root(nested_host, nested_shadow_root);
- fixture.tree.link_in_dom_order(text, Some(shadow_child), None);
-
- let is_in = |node, root| fixture.tree.is_in_shadow_including_subtree_of(node, root);
- assert!(is_in(host, host), "the test is inclusive");
- assert!(is_in(light_child, host), "a light child lies below its host");
- assert!(is_in(shadow_child, host), "and so does what its shadow tree holds");
- assert!(is_in(text, host), "text inside that tree included");
- assert!(
- is_in(nested_shadow_child, host),
- "a shadow tree nested inside that one included"
- );
- assert!(
- is_in(shadow_child, shadow_root),
- "a shadow root still holds its own tree"
- );
- assert!(!is_in(outside, host), "a sibling subtree lies outside");
- assert!(!is_in(host, light_child), "a child is not an ancestor of its parent");
- assert!(!is_in(host, text), "a text node holds nothing but itself");
- assert!(
- is_in(light_child, root_element),
- "the climb reaches the element above the host"
- );
- }
-
- #[test]
- fn a_shadow_host_takes_its_flat_tree_children_from_its_shadow_root() {
- let mut fixture = TreeFixture::new();
- let host = fixture.element();
- let light_child = fixture.element();
- let shadow_root = fixture.element();
- let shadow_child = fixture.element();
- fixture.attach_children(host, &[light_child]);
- fixture.attach_children(shadow_root, &[shadow_child]);
- fixture.tree.set_shadow_root(host, shadow_root);
-
- assert_eq!(
- fixture.tree.flat_tree_children(host).collect::<Vec<_>>(),
- vec![shadow_child],
- "the light child reaches the flat tree only through a slot"
- );
- assert_eq!(fixture.tree.shadow_root_of(host), Some(shadow_root));
- assert_eq!(fixture.tree.host_of(shadow_root), Some(host));
- assert_eq!(fixture.tree.flat_tree_parent(shadow_child), Some(host));
- assert_eq!(fixture.tree.flat_tree_parent(light_child), None);
- }
-
- #[test]
- fn replacing_a_shadow_root_unlinks_the_previous_root() {
- let mut fixture = TreeFixture::new();
- let host = fixture.element();
- let previous_root = fixture.element();
- let current_root = fixture.element();
-
- fixture.tree.set_shadow_root(host, previous_root);
- fixture.tree.set_shadow_root(host, current_root);
-
- assert_eq!(fixture.tree.shadow_root_of(host), Some(current_root));
- assert_eq!(fixture.tree.host_of(previous_root), None);
- assert_eq!(fixture.tree.host_of(current_root), Some(host));
-
- fixture.tree.retire_element(previous_root);
- assert_eq!(fixture.tree.shadow_root_of(host), Some(current_root));
- assert_eq!(fixture.tree.host_of(current_root), Some(host));
- }
-
- #[test]
- fn a_slot_takes_its_flat_tree_children_from_its_assignment() {
- let mut fixture = TreeFixture::new();
- let slot = fixture.element();
- let fallback = fixture.element();
- let first = fixture.element();
- let second = fixture.element();
- fixture.attach_children(slot, &[fallback]);
-
- // With nothing assigned, the slot's own children are its fallback content.
- assert_eq!(
- fixture.tree.flat_tree_children(slot).collect::<Vec<_>>(),
- vec![fallback]
- );
-
- fixture.tree.set_assigned_slot(first, Some(slot));
- fixture.tree.set_assigned_slot(second, Some(slot));
- fixture.tree.set_assigned_nodes(slot, &[first, second]);
- assert_eq!(
- fixture.tree.flat_tree_children(slot).collect::<Vec<_>>(),
- vec![first, second],
- "assigned nodes replace fallback content"
- );
- assert_eq!(fixture.tree.assigned_slot_of(first), Some(slot));
- assert_eq!(fixture.tree.flat_tree_parent(first), Some(slot));
- assert_eq!(fixture.tree.flat_tree_parent(fallback), None);
- }
-
- #[test]
- fn style_reaction_order_covers_shadow_light_fallback_and_assigned_branches() {
- let mut fixture = TreeFixture::new();
- let document = fixture.element();
- let host = fixture.element();
- let light_child = fixture.element();
- let shadow_root = fixture.element();
- let slot = fixture.element();
- let fallback = fixture.element();
- let assigned = fixture.element();
- fixture.attach_children(document, &[host]);
- fixture.attach_children(host, &[light_child, assigned]);
- fixture.attach_children(shadow_root, &[slot]);
- fixture.attach_children(slot, &[fallback]);
- fixture.tree.set_shadow_root(host, shadow_root);
- fixture.tree.set_assigned_slot(assigned, Some(slot));
- fixture.tree.set_assigned_nodes(slot, &[assigned]);
-
- let mut reactions = vec![light_child, assigned, fallback, slot, host];
- reactions.sort_unstable_by(|first, second| fixture.tree.compare_style_reaction_order(*first, *second));
-
- assert_eq!(reactions, vec![host, slot, fallback, assigned, light_child]);
- let ranks = fixture.tree.style_reaction_order_ranks(reactions.iter().copied());
- for &first in &reactions {
- for &second in &reactions {
- assert_eq!(
- ranks[&first].cmp(&ranks[&second]),
- fixture.tree.compare_style_reaction_order(first, second)
- );
- }
- }
- }
-
- #[test]
- fn reaction_ranks_cover_sparse_batches_and_deep_chains() {
- let mut fixture = TreeFixture::new();
- let first_root = fixture.element();
- let second_root = fixture.element();
- let mut chain = vec![first_root];
- for _ in 0..4096 {
- let child = fixture.element();
- fixture.attach_children(*chain.last().unwrap(), &[child]);
- chain.push(child);
- }
- let leaf = *chain.last().unwrap();
- let ranks = fixture.tree.style_reaction_order_ranks([second_root, leaf, leaf]);
- assert_eq!(ranks.len(), chain.len() + 1);
- for pair in chain.windows(2) {
- assert!(ranks[&pair[0]] < ranks[&pair[1]]);
- }
- assert!(ranks[&leaf] < ranks[&second_root]);
- }
-
- #[test]
- fn reassigning_a_slot_moves_the_node_without_touching_the_dom_tree() {
- let mut fixture = TreeFixture::new();
- let first_slot = fixture.element();
- let second_slot = fixture.element();
- let node = fixture.element();
- let dom_parent = fixture.element();
- fixture.attach_children(dom_parent, &[node]);
-
- fixture.tree.set_assigned_slot(node, Some(first_slot));
- fixture.tree.set_assigned_nodes(first_slot, &[node]);
- assert_eq!(fixture.tree.assigned_nodes_of(first_slot), &[node]);
-
- fixture.tree.set_assigned_slot(node, Some(second_slot));
- fixture.tree.set_assigned_nodes(first_slot, &[]);
- fixture.tree.set_assigned_nodes(second_slot, &[node]);
- assert_eq!(
- fixture.tree.assigned_nodes_of(first_slot),
- &[],
- "the old slot no longer lists it"
- );
- assert_eq!(fixture.tree.assigned_nodes_of(second_slot), &[node]);
- assert_eq!(
- fixture.tree.parent(node),
- Some(dom_parent),
- "the DOM parent is unchanged, which is exactly why slotting is its own relation"
- );
-
- fixture.tree.set_assigned_slot(node, None);
- fixture.tree.set_assigned_nodes(second_slot, &[]);
- assert_eq!(fixture.tree.assigned_nodes_of(second_slot), &[]);
- assert_eq!(fixture.tree.assigned_slot_of(node), None);
- }
-
- #[test]
- fn part_exposure_is_its_own_sparse_relation() {
- let mut fixture = TreeFixture::new();
- let element = fixture.element();
- assert_eq!(fixture.tree.part_hosts_of(element), &[]);
-
- let pairs = [(StyleAtomID(7), element), (StyleAtomID(8), element)];
- fixture.tree.set_part_hosts(element, &pairs);
- assert_eq!(fixture.tree.part_hosts_of(element), &pairs);
- let mut atoms = HashSet::default();
- assert_eq!(fixture.tree.collect_atoms(&mut atoms), 2);
- assert_eq!(atoms, [StyleAtomID(7), StyleAtomID(8)].into_iter().collect());
-
- fixture.tree.set_part_hosts(element, &[]);
- assert_eq!(fixture.tree.part_hosts_of(element), &[]);
- atoms.clear();
- assert_eq!(fixture.tree.collect_atoms(&mut atoms), 0);
- assert!(atoms.is_empty());
- }
-
- #[test]
- fn shadow_relations_are_charged_only_where_they_exist() {
- let mut fixture = TreeFixture::new();
- for _ in 0..100 {
- fixture.element();
- }
-
- let host = StyleNodeID::element(1);
- let root = StyleNodeID::element(2);
- let slot = StyleNodeID::element(3);
- let slotted = StyleNodeID::element(4);
- fixture.tree.set_shadow_root(host, root);
- assert!(fixture.tree.has_shadow_relations());
-
- fixture.tree.set_assigned_slot(slotted, Some(slot));
- fixture.tree.set_assigned_nodes(slot, &[slotted]);
-
- fixture.tree.set_part_hosts(host, &[(StyleAtomID(1), host)]);
- }
-
#[test]
fn per_node_relation_state_fits_the_mandatory_budget() {
// Rust stores four relation columns, depth, and the style-record handle per node. The DOM
diff --git a/Libraries/LibWeb/Rust/src/css/style/weak_pool.rs b/Libraries/LibWeb/Rust/src/css/style/weak_pool.rs
index 427ac4ffb01..3b3b15167ed 100644
--- a/Libraries/LibWeb/Rust/src/css/style/weak_pool.rs
+++ b/Libraries/LibWeb/Rust/src/css/style/weak_pool.rs
@@ -4,31 +4,59 @@
* SPDX-License-Identifier: BSD-2-Clause
*/
-use super::fast_hash::FastMap as HashMap;
+use hashbrown::HashTable;
use std::sync::{Arc, Weak};
/// The smallest reference count a pool lets itself grow to before it first sweeps.
const MINIMUM_SWEEP_THRESHOLD: usize = 64;
+/// A weak reference to a pooled value, with the hash it is pooled under.
+struct Slot<T> {
+ hash: u64,
+ value: Weak<T>,
+}
+
/// An interning pool: weak references to equal immutable values, by content hash.
///
/// The pool never keeps a value alive, and a value never reaches back into its pool when it is
/// dropped, so a value can die on any thread, and a pool shared behind a lock is only locked
/// while something is interned through it.
/// A dead reference still holds its value's allocation, though not the value, until it is dropped
-/// when its bucket is next searched or by a full sweep, which runs whenever the references have
+/// when its hash is next searched or by a full sweep, which runs whenever the references have
/// doubled since the last one, so dead references never outnumber the live ones by much.
+///
+/// NB: Each reference is a slot of one table, and values with equal hashes take slots of their
+/// own, so a value costs one slot rather than a list per hash with an allocation behind it.
pub(super) struct WeakPool<T> {
- by_hash: HashMap<u64, Vec<Weak<T>>>,
- references: usize,
+ slots: HashTable<Slot<T>>,
sweep_threshold: usize,
}
+/// A fork's pool finds the values its parent's found, as long as they live.
+impl<T> Clone for WeakPool<T> {
+ fn clone(&self) -> Self {
+ let mut slots = HashTable::with_capacity(self.slots.len());
+ for slot in &self.slots {
+ slots.insert_unique(
+ slot.hash,
+ Slot {
+ hash: slot.hash,
+ value: slot.value.clone(),
+ },
+ |slot| slot.hash,
+ );
+ }
+ Self {
+ slots,
+ sweep_threshold: self.sweep_threshold,
+ }
+ }
+}
+
impl<T> Default for WeakPool<T> {
fn default() -> Self {
Self {
- by_hash: HashMap::default(),
- references: 0,
+ slots: HashTable::new(),
sweep_threshold: MINIMUM_SWEEP_THRESHOLD,
}
}
@@ -37,65 +65,45 @@ impl<T> Default for WeakPool<T> {
impl<T> WeakPool<T> {
/// A live value stored under `hash` that `matches` accepts.
pub(super) fn find(&mut self, hash: u64, mut matches: impl FnMut(&T) -> bool) -> Option<Arc<T>> {
- let bucket = self.by_hash.get_mut(&hash)?;
- let before = bucket.len();
- bucket.retain(|candidate| candidate.strong_count() != 0);
- self.references -= before - bucket.len();
- let found = bucket
- .iter()
- .filter_map(Weak::upgrade)
- .find(|candidate| matches(candidate));
- if bucket.is_empty() {
- self.by_hash.remove(&hash);
- }
- found
+ self.forget(hash, |slot| slot.value.strong_count() == 0);
+ self.slots
+ .iter_hash(hash)
+ .filter(|slot| slot.hash == hash)
+ .filter_map(|slot| slot.value.upgrade())
+ .find(|candidate| matches(candidate))
}
/// Remember `value` under `hash`, for a later equal value to find.
pub(super) fn insert(&mut self, hash: u64, value: &Arc<T>) {
- self.by_hash.entry(hash).or_default().push(Arc::downgrade(value));
- self.references += 1;
- if self.references >= self.sweep_threshold {
+ let slot = Slot {
+ hash,
+ value: Arc::downgrade(value),
+ };
+ self.slots.insert_unique(hash, slot, |slot| slot.hash);
+ if self.slots.len() >= self.sweep_threshold {
self.sweep();
}
}
- /// Make `value`, which may have been published under `hash`, private to its owner. When the
- /// owner holds the only strong reference the pool just forgets it, so it can be edited in place;
- /// otherwise `copy` makes a private value.
- pub(super) fn make_private(&mut self, hash: Option<u64>, value: &mut Arc<T>, copy: impl FnOnce(&T) -> T) {
- // A pool reference is only upgraded under the pool's lock, so while it is held a value with
- // one strong reference cannot gain another.
- if Arc::strong_count(value) == 1
- && let Some(hash) = hash
- && let Some(bucket) = self.by_hash.get_mut(&hash)
- {
- let before = bucket.len();
- bucket.retain(|candidate| !std::ptr::eq(candidate.as_ptr(), Arc::as_ptr(value)));
- self.references -= before - bucket.len();
- if bucket.is_empty() {
- self.by_hash.remove(&hash);
- }
- }
- if Arc::get_mut(value).is_none() {
- *value = Arc::new(copy(value));
+ /// Drop the references under `hash` that `forgotten` accepts.
+ fn forget(&mut self, hash: u64, mut forgotten: impl FnMut(&Slot<T>) -> bool) {
+ while let Ok(entry) = self.slots.find_entry(hash, |slot| slot.hash == hash && forgotten(slot)) {
+ entry.remove();
}
}
fn sweep(&mut self) {
- self.by_hash.retain(|_, bucket| {
- bucket.retain(|candidate| candidate.strong_count() != 0);
- !bucket.is_empty()
- });
- self.references = self.by_hash.values().map(Vec::len).sum();
- self.sweep_threshold = (self.references * 2).max(MINIMUM_SWEEP_THRESHOLD);
+ self.slots.retain(|slot| slot.value.strong_count() != 0);
+ self.slots.shrink_to_fit(|slot| slot.hash);
+ self.sweep_threshold = (self.slots.len() * 2).max(MINIMUM_SWEEP_THRESHOLD);
}
#[cfg(test)]
pub(super) fn live_values_under(&self, hash: u64) -> usize {
- self.by_hash.get(&hash).map_or(0, |bucket| {
- bucket.iter().filter(|candidate| candidate.strong_count() != 0).count()
- })
+ self.slots
+ .iter_hash(hash)
+ .filter(|slot| slot.hash == hash && slot.value.strong_count() != 0)
+ .count()
}
}
@@ -111,7 +119,7 @@ mod tests {
pool.insert(u64::from(value.as_ref() % 3), &value);
}
// Every value died right after insertion; the sweeps kept the table near empty.
- assert!(pool.references < MINIMUM_SWEEP_THRESHOLD);
+ assert!(pool.slots.len() < MINIMUM_SWEEP_THRESHOLD);
let kept = Arc::new(7);
pool.insert(7, &kept);
@@ -123,24 +131,4 @@ mod tests {
assert!(pool.find(7, |_| true).is_none());
assert_eq!(pool.live_values_under(7), 0);
}
-
- #[test]
- fn a_sole_owner_edits_in_place_and_a_shared_value_is_copied() {
- let mut pool = WeakPool::<u32>::default();
- let mut sole = Arc::new(1);
- pool.insert(1, &sole);
- let address = Arc::as_ptr(&sole);
- pool.make_private(Some(1), &mut sole, |_| unreachable!("a sole owner is never copied"));
- assert_eq!(Arc::as_ptr(&sole), address);
- assert!(Arc::get_mut(&mut sole).is_some());
- assert!(pool.find(1, |_| true).is_none());
-
- let mut shared = Arc::new(2);
- pool.insert(2, &shared);
- let other = Arc::clone(&shared);
- pool.make_private(Some(2), &mut shared, |value| *value);
- assert!(!Arc::ptr_eq(&shared, &other));
- assert!(Arc::get_mut(&mut shared).is_some());
- assert!(Arc::ptr_eq(&pool.find(2, |_| true).unwrap(), &other));
- }
}
diff --git a/Meta/Linters/check_rust_address_keys.py b/Meta/Linters/check_rust_address_keys.py
new file mode 100755
index 00000000000..c6654a56209
--- /dev/null
+++ b/Meta/Linters/check_rust_address_keys.py
@@ -0,0 +1,83 @@
+#!/usr/bin/env python3
+
+# Copyright (c) 2026-present, the Ladybird developers.
+#
+# SPDX-License-Identifier: BSD-2-Clause
+
+"""Keeps bare addresses out of what LibWeb's Rust code remembers.
+
+An address held as an integer outlives what it names without saying so, and the next allocation there then
+passes for the value that was freed: an element takes another's style. Hold a `PointerKey` (css/style/pointer_key.rs),
+which holds a count of what it names, or a counter of your own. Handing C++ a pointer with `.cast()` stays fine.
+
+ALLOWED lists the casts that stand, by file, each of which holds what it names some other way, or is compared and
+gone within a call. A file holding fewer than listed fails too, so that the list only shrinks.
+
+The check is a line-based heuristic, not a parser: review has to catch what it misses.
+"""
+
+import pathlib
+import re
+import subprocess
+import sys
+
+ROOTS = ["Libraries/LibWeb/Rust/src/css", "Libraries/LibWeb/Rust/src/layout", "Libraries/LibWeb/Rust/src/painting"]
+
+PATTERN = re.compile(
+ r"as_ptr\([^()]*\)\s+as usize"
+ r"|\.pointer\(\)\s+as usize"
+ r"|\.addr\(\)"
+ r"|from_ref\([^()]*\)\s+as usize"
+ r"|expose_provenance\(\)"
+)
+
+ALLOWED = {
+ "css/computed_values.rs": 1,
+ "css/custom_properties.rs": 2,
+ "css/parser/syntax_parser/ownership_tests.rs": 2,
+ "css/rule/read.rs": 1,
+ "css/style/bridge.rs": 1,
+ "css/style/custom_property_environments.rs": 1,
+ "css/style/effect_descriptions.rs": 1,
+ "css/style/engine_calls.rs": 1,
+ "css/style/font_resolution.rs": 2,
+ "css/style/kept_past_release.rs": 3,
+ "css/style/pipeline/compute.rs": 1,
+ "css/style/pipeline/custom_properties.rs": 4,
+ "css/style/pipeline/custom_property_moves.rs": 1,
+ "css/style/pipeline/install.rs": 1,
+ "css/style/pipeline/records.rs": 3,
+ "css/style/pipeline/results.rs": 1,
+ "css/style/pipeline/rules.rs": 2,
+ "css/style/pipeline/sharing.rs": 1,
+ "css/style/pipeline/traversal.rs": 5,
+ "css/style_compute/ffi_test_stubs.rs": 1,
+ "layout/layout_node_arena.rs": 1,
+}
+
+
+def main():
+ files = subprocess.run(
+ ["git", "ls-files", "--", *(f"{root}/*.rs" for root in ROOTS)], capture_output=True, text=True, check=True
+ ).stdout.split()
+ failures = []
+ for file in files:
+ if file.endswith("/pointer_key.rs"):
+ continue
+ lines = [
+ (number, line)
+ for number, line in enumerate(pathlib.Path(file).read_text().splitlines(), 1)
+ if PATTERN.search(line)
+ ]
+ allowed = ALLOWED.get(file.removeprefix("Libraries/LibWeb/Rust/src/"), 0)
+ if len(lines) > allowed:
+ failures.extend(f"{file}:{number}: {line.strip()}" for number, line in lines)
+ elif len(lines) < allowed:
+ failures.append(f"{file}: holds {len(lines)} address casts, lower its allowance of {allowed}")
+ for failure in failures:
+ print(f"bare address, hold a PointerKey: {failure}")
+ return 1 if failures else 0
+
+
+if __name__ == "__main__":
+ sys.exit(main())
diff --git a/Tests/LibWeb/Ref/expected/css/placeholder-host-class-change-ref.html b/Tests/LibWeb/Ref/expected/css/placeholder-host-class-change-ref.html
new file mode 100644
index 00000000000..2aacb42c5fc
--- /dev/null
+++ b/Tests/LibWeb/Ref/expected/css/placeholder-host-class-change-ref.html
@@ -0,0 +1,6 @@
+<!DOCTYPE html>
+<style>
+ input { font-size: 40px; }
+ input.x::placeholder { color: rgb(0, 150, 0); }
+</style>
+<input class="x" placeholder="placeholder">
diff --git a/Tests/LibWeb/Ref/input/css/placeholder-host-class-change.html b/Tests/LibWeb/Ref/input/css/placeholder-host-class-change.html
new file mode 100644
index 00000000000..5d09bbb4af8
--- /dev/null
+++ b/Tests/LibWeb/Ref/input/css/placeholder-host-class-change.html
@@ -0,0 +1,11 @@
+<!DOCTYPE html>
+<link rel="match" href="../../expected/css/placeholder-host-class-change-ref.html">
+<style>
+ input { font-size: 40px; }
+ input.x::placeholder { color: rgb(0, 150, 0); }
+</style>
+<input id="field" placeholder="placeholder">
+<script>
+ document.body.offsetWidth;
+ document.getElementById("field").classList.add("x");
+</script>