Truly independent web browser
LibWeb: Index a document's rules and match their selector components
Andreas Kling5f0a5d8baf29
diff --git a/Libraries/LibWeb/CSS/SelectorMatching.cpp b/Libraries/LibWeb/CSS/SelectorMatching.cppindex a3091c1291f..f9c5d363bfc 100644--- a/Libraries/LibWeb/CSS/SelectorMatching.cpp+++ b/Libraries/LibWeb/CSS/SelectorMatching.cpp@@ -182,7 +182,7 @@ static bool element_popover_is_open(DOM::Element const& element)X(OptimalValue, meter->value_state() == HTML::HTMLMeterElement::ValueState::Optimal) \X(SuboptimalValue, meter->value_state() == HTML::HTMLMeterElement::ValueState::Suboptimal)-CSS::PseudoClassBitmap element_states(DOM::Element const& element)+CSS::PseudoClassBitmap element_states(DOM::Element const& element, AskLocalLink ask_local_link){CSS::PseudoClassBitmap states;auto set = [&](CSS::PseudoClass pseudo_class, bool holds) {@@ -204,7 +204,7 @@ CSS::PseudoClassBitmap element_states(DOM::Element const& element)set(CSS::PseudoClass::Link, is_link);set(CSS::PseudoClass::Visited, is_visited);set(CSS::PseudoClass::AnyLink, is_link || is_visited);- if (is_link || is_visited)+ if ((is_link || is_visited) && ask_local_link == AskLocalLink::Yes)set(CSS::PseudoClass::LocalLink, element.matches_local_link_pseudo_class());// The rest belong to kinds of element, and asking a `<div>` about them costs one type checkdiff --git a/Libraries/LibWeb/CSS/SelectorMatching.h b/Libraries/LibWeb/CSS/SelectorMatching.hindex ca21537c711..c067a3297c4 100644--- a/Libraries/LibWeb/CSS/SelectorMatching.h+++ b/Libraries/LibWeb/CSS/SelectorMatching.h@@ -50,6 +50,12 @@ WEB_API bool element_matches_state(DOM::Element const&, CSS::PseudoClass);// Asking `element_matches_state` once per pseudo-class recomputes what several of them share - an// element's validity is the answer to four of them, its required state to two - and does it for// every element that connects. This asks each shared question once and is the same answers.-WEB_API CSS::PseudoClassBitmap element_states(DOM::Element const&);+//+// Whether a link is a local link is answered by parsing its URL, which is asked only where something reads it.+enum class AskLocalLink : u8 {+ No,+ Yes,+};+WEB_API CSS::PseudoClassBitmap element_states(DOM::Element const&, AskLocalLink);}diff --git a/Libraries/LibWeb/CSS/StyleScope.cpp b/Libraries/LibWeb/CSS/StyleScope.cppindex 123c99b6ffa..5a3a13ffe7a 100644--- a/Libraries/LibWeb/CSS/StyleScope.cpp+++ b/Libraries/LibWeb/CSS/StyleScope.cpp@@ -8,10 +8,13 @@#include <AK/StringBuilder.h>#include <AK/Utf16StringBuilder.h>+#include <LibCore/EventLoop.h>+#include <LibCore/Timer.h>#include <LibWeb/CSS/Enums.h>#include <LibWeb/CSS/FontFaceSet.h>#include <LibWeb/CSS/Parser/Parser.h>#include <LibWeb/CSS/PropertyID.h>+#include <LibWeb/CSS/RustMediaList.h>#include <LibWeb/CSS/StyleComputeFFI.h>#include <LibWeb/CSS/StyleComputer.h>#include <LibWeb/CSS/StyleEngineInput.h>@@ -26,6 +29,7 @@#include <LibWeb/Loader/ContentBlocker.h>#include <LibWeb/Namespace.h>#include <LibWeb/Page/Page.h>+#include <LibWeb/Platform/EventLoopPlugin.h>#include <LibWeb/ValueParserRustFFI.h>namespace Web::CSS {@@ -356,6 +360,31 @@ static StyleSheetState& svg_stylesheet()return *sheet;}+void StyleScope::prepare_user_agent_rules(DOM::Document& document)+{+ // NB: A document outside an event loop has no task to do this in, and is only there to be looked at by a test.+ static bool prepared = false;+ if (prepared || !Core::EventLoop::is_running())+ return;+ prepared = true;+ Platform::EventLoopPlugin::the().deferred_invoke(GC::create_function(document.heap(), [document = GC::Ref { document }] {+ auto& sheet = default_stylesheet();+ publish_user_agent_sheet(sheet, document);+ MediaEnvironmentSnapshot environment { document };+ Parser::ValueParserFFI::rust_user_agent_style_sheet_index_ahead(sheet.native_sheet().handle(), environment.ffi_environment());+ }));++ // What only the process keeps goes some time after its last use, however idle the process is by then.+ static auto& prune_timer = *new RefPtr<Core::Timer>;+ prune_timer = Core::Timer::create_repeating(AK::Duration::from_seconds(60), [] { Parser::ValueParserFFI::rust_style_prune_kept_data(); });+ prune_timer->start();+}++void StyleScope::release_kept_data()+{+ Parser::ValueParserFFI::rust_style_release_kept_data();+}+void StyleScope::for_each_user_agent_stylesheet(bool include_quirks_mode_stylesheet, bool include_mathml_and_svg_stylesheets, Function<void(CSS::StyleSheetState&, StyleSheetIdentifier const&)> const& callback){auto callback_with_identifier = [&](StyleSheetState& sheet, Utf16String url) {@@ -467,7 +496,7 @@ void StyleRuleCache::add_rules_from_sheet(StyleSheetState& sheet, CascadeOrigin// a single value is meaningful.if (value->tag == StyleValueFFI::StyleValueData::Tag::ValueList) {auto const& list = value->value_list.values;- if (list.length == 0)+ if (list.length() == 0)return;value = static_cast<StyleValueFFI::StyleValueData const*>(list.pointer[0].pointer);}@@ -483,7 +512,7 @@ void StyleRuleCache::add_rules_from_sheet(StyleSheetState& sheet, CascadeOrigin}if (property_id == PropertyID::AnimationComposition) {AnimationComposition composition = AnimationComposition::Replace;- if (value->tag == StyleValueFFI::StyleValueData::Tag::ValueList && value->value_list.values.length == 1)+ if (value->tag == StyleValueFFI::StyleValueData::Tag::ValueList && value->value_list.values.length() == 1)value = static_cast<StyleValueFFI::StyleValueData const*>(value->value_list.values.pointer[0].pointer);if (value->tag == StyleValueFFI::StyleValueData::Tag::Keyword) {if (static_cast<Keyword>(value->keyword.keyword) == Keyword::Add)@@ -590,7 +619,7 @@ void StyleScope::publish_animation_keyframes()return;StyleEngineFFI::style_engine_set_tree_scope_animation_keyframes(document().style_computer().style_engine().host(), style_engine_tree_scope().value(),- bit_cast<FlatPtr>(as_if<DOM::ShadowRoot>(*m_node)), name_lengths.span(), name_units.span(),+ name_lengths.span(), name_units.span(),keyframe_sets.span());m_published_keyframe_sets = move(published);}@@ -642,7 +671,6 @@ Optional<StyleScope::DepartedAnimationKeyframes> StyleScope::take_published_animreturn {};return DepartedAnimationKeyframes {.tree_scope = shadow_root->style_engine_tree_scope(),- .shadow_root_identity = bit_cast<FlatPtr>(shadow_root),.keyframe_sets = move(m_published_keyframe_sets),.has_position_try_rules = has_position_try_rules,};@@ -656,6 +684,10 @@ TreeScopeID StyleScope::style_engine_tree_scope() constvoid StyleScope::invalidate_counter_style_cache(){m_needs_counter_style_cache_update = true;+ if (auto* shadow_root = as_if<DOM::ShadowRoot>(*m_node))+ document().note_counter_style_scope_to_settle(*shadow_root);+ else+ document().set_counter_style_scopes_need_update(true);// Only this style scope and those whose counter style names pass on to it, which may include counter styles that// extend the ones defined in this scope, can resolve differently.@@ -664,6 +696,7 @@ void StyleScope::invalidate_counter_style_cache()for (auto const* ancestor = scope.parent_style_scope(); ancestor; ancestor = ancestor->parent_style_scope()) {if (ancestor == this) {scope.m_needs_counter_style_cache_update = true;+ shadow_root.document().note_counter_style_scope_to_settle(shadow_root);break;}}@@ -700,6 +733,12 @@ void StyleScope::build_counter_style_cache(Layout::BegunRead const& read)Vector<CounterStyleRule> rules;auto& style_engine = document().style_computer().style_engine();auto const tree_scope = style_engine_tree_scope();+ // NB: Asking the style engine for the index of a layer waits on it, and the predefined counter styles alone are+ // over a hundred rules in one layer, so each layer is asked for once.+ HashMap<u32, u32> layer_indices;+ auto layer_index = [&](u32 layer) {+ return layer_indices.ensure(layer, [&] { return StyleEngineFFI::style_engine_layer_index(style_engine.host(), &read, tree_scope, layer); });+ };auto collect_counter_style_rules = [&](CSS::CascadeOrigin cascade_origin, CSS::StyleSheetState const& style_sheet) {if (!style_sheet.native_media_list().matches())return;@@ -712,7 +751,7 @@ void StyleScope::build_counter_style_cache(Layout::BegunRead const& read).name = Utf16FlyString { rule.name() },.descriptors = rule.descriptors(),.origin = cascade_origin_precedence(cascade_origin),- .layer = StyleEngineFFI::style_engine_layer_index(style_engine.host(), &read, tree_scope, layer),+ .layer = layer_index(layer),});});};diff --git a/Libraries/LibWeb/CSS/StyleScope.h b/Libraries/LibWeb/CSS/StyleScope.hindex b21b7f40380..53d172c3f6b 100644--- a/Libraries/LibWeb/CSS/StyleScope.h+++ b/Libraries/LibWeb/CSS/StyleScope.h@@ -120,7 +120,6 @@ public:// leaves its document, with the keyframe sets the row names: they stay alive until the row is given up.struct DepartedAnimationKeyframes {TreeScopeID tree_scope;- FlatPtr shadow_root_identity { 0 };Vector<NonnullRefPtr<Animations::KeyframeEffect::KeyFrameSet const>> keyframe_sets;// NB: Whether the scope published a `@position-try` row too, which is given up along with this one.bool has_position_try_rules { false };@@ -128,6 +127,11 @@ public:[[nodiscard]] Optional<DepartedAnimationKeyframes> take_published_animation_keyframes();void for_each_stylesheet(CascadeOrigin, Function<void(CSS::StyleSheetState&)> const&) const;+ // Has the process keep the rules of the default user agent sheet and index them on a thread of their own, before the+ // first document needing them does, once a task after this one runs.+ static void prepare_user_agent_rules(DOM::Document&);+ // Lets go of the parsed sheets and sheet segments only the process keeps, past the documents that used them.+ static WEB_API void release_kept_data();static WEB_API void for_each_user_agent_stylesheet(bool include_quirks_mode_stylesheet, bool include_mathml_and_svg_stylesheets, Function<void(CSS::StyleSheetState&, StyleSheetIdentifier const&)> const&);void build_user_style_sheet_if_needed();diff --git a/Libraries/LibWeb/CSS/StyleSheetState.cpp b/Libraries/LibWeb/CSS/StyleSheetState.cppindex ac7668e6579..62ce3c117fc 100644--- a/Libraries/LibWeb/CSS/StyleSheetState.cpp+++ b/Libraries/LibWeb/CSS/StyleSheetState.cpp@@ -173,6 +173,15 @@ void StyleSheetState::set_rules(RustRuleList rules)m_native_sheet.rules().replace(rules);}+Optional<Utf16String> StyleSheetState::source_text() const+{+ bool has_text = false;+ auto text = Utf16String::adopt_raw(Parser::ValueParserFFI::rust_rule_list_source_text(m_native_sheet.rules().handle(), &has_text));+ if (!has_text)+ return {};+ return text;+}+CSSRuleList const& StyleSheetState::rules() const{if (!m_rules) {@@ -240,8 +249,6 @@ size_t StyleSheetState::external_memory_size() constsize = JS::saturating_add_external_memory_size(size, JS::utf16_string_external_memory_size(m_title));if (!m_rules)size = JS::saturating_add_external_memory_size(size, m_native_sheet.rules().external_memory_size());- if (m_source_text.has_value())- size = JS::saturating_add_external_memory_size(size, JS::utf16_string_external_memory_size(*m_source_text));size = JS::saturating_add_external_memory_size(size, JS::hash_map_external_memory_size(m_css_connected_font_faces));size = JS::saturating_add_external_memory_size(size, JS::vector_external_memory_size(m_import_rules));size = JS::saturating_add_external_memory_size(size, JS::hash_map_external_memory_size(m_imports));@@ -645,15 +652,20 @@ void StyleSheetState::load_pending_image_resources(DOM::Document& document)// Keep image-bearing values alive only until the pending requests below have been started.// Their parsed data stays in the native rules; CSSOM wrappers do not own resource bindings.+ // NB: The process interns equal values, so a sheet repeating one image across its rules names+ // one value many times. Each is registered once, rather than with a wrapper per use.struct Context {StyleSheetState& sheet;+ HashTable<void const*> seen;Vector<NonnullRefPtr<StyleValue const>> images;- } context { *this, {} };+ } context { *this, {}, {} };// A constructed sheet can be adopted by many shadow roots in the same document. Discover// its images once, unless a rule-list mutation gives it new resources to register.if (exchange(m_needs_image_resource_registration, false)) {Parser::ValueParserFFI::rust_rule_list_visit_images(m_native_sheet.rules().handle(), &context, [](void* data, void const* value) {auto& context = *static_cast<Context*>(data);+ if (context.seen.set(value) != HashSetResult::InsertedNewEntry)+ return;auto image = StyleValue::adopt_rust_style_value_data(StyleValueFFI::rust_style_value_retain(static_cast<StyleValueFFI::StyleValueData const*>(value)));const_cast<StyleValue&>(*image).set_style_sheet(&context.sheet);context.images.append(move(image));diff --git a/Libraries/LibWeb/CSS/StyleSheetState.h b/Libraries/LibWeb/CSS/StyleSheetState.hindex bf26009bfef..9183f824ff4 100644--- a/Libraries/LibWeb/CSS/StyleSheetState.h+++ b/Libraries/LibWeb/CSS/StyleSheetState.h@@ -143,12 +143,13 @@ public:bool constructed() const { return m_native_sheet.flag(RustStyleSheet::Flag::Constructed); }GC::Ptr<DOM::Document const> constructor_document() const { return m_constructor_document; }+ GC::Ptr<DOM::Document> parsing_document() const { return m_parsing_document; }void set_constructor_document(GC::Ptr<DOM::Document const> constructor_document) { m_constructor_document = constructor_document; }bool disallow_modification() const { return m_native_sheet.flag(RustStyleSheet::Flag::DisallowModification); }- void set_source_text(Utf16String source) { m_source_text = move(source); }- Optional<Utf16String> source_text() const { return m_source_text; }+ // The text the sheet was parsed from, which its parse shares between the documents it serves.+ Optional<Utf16String> source_text() const;void add_critical_subresource(StyleSheetImport&);void remove_critical_subresource(StyleSheetImport&);@@ -233,8 +234,6 @@ private:Optional<ReferrerPolicy::ReferrerPolicy> m_fetched_referrer_policy;Utf16String m_title;- Optional<Utf16String> m_source_text;-mutable GC::Weak<CSSRuleList> m_rules;GC::Ptr<DOM::Document> m_parsing_document;HashMap<u64, WeakPtr<FontFaceState>> m_css_connected_font_faces;diff --git a/Libraries/LibWeb/DOM/SelectorQuery.cpp b/Libraries/LibWeb/DOM/SelectorQuery.cppindex 679e12f60ed..32d188e40e1 100644--- a/Libraries/LibWeb/DOM/SelectorQuery.cpp+++ b/Libraries/LibWeb/DOM/SelectorQuery.cpp@@ -5,6 +5,8 @@*/#include <AK/Array.h>+#include <AK/QuickSort.h>+#include <LibGC/RootVector.h>#include <LibGC/WeakInlines.h>#include <LibWeb/CSS/SelectorMatching.h>#include <LibWeb/DOM/Document.h>@@ -204,25 +206,37 @@ constexpr CSS::SelectorFFI::FfiDomSelectorCallbacks dom_selector_callbacks {return subject.child_index_from_end(SiblingsOfType);}VERIFY_NOT_REACHED(); },- .next_element_in_subtree = [](void const* node, void const* root, uintptr_t local_name, u64 attribute_names) -> void const* {+ .next_element_in_subtree = [](void const* node, void const* root, uintptr_t local_name, uintptr_t class_name, u64 names) -> void const* {auto const& stay_within = node_from_ffi(root);auto const* next = node_from_ffi(node).next_in_pre_order(&stay_within);while (next) {auto const* element = as_if<Element>(*next);- if (element && (element->subtree_attribute_name_filter() & attribute_names) != attribute_names) {- // No element of this subtree has every attribute name, so skip past it.+ if (element && (element->subtree_name_filter() & names) != names) {+ // No element of this subtree has every name, so skip past it.while (next != &stay_within && !next->next_sibling())next = next->parent();next = next == &stay_within ? nullptr : next->next_sibling();continue;}- if (element && (!local_name || element->local_name().raw_identity() == local_name))+ if (element && (!local_name || element->local_name().raw_identity() == local_name)+ && (!class_name || any_of(element->class_names(), [&](auto const& name) { return name.raw_identity() == class_name; })))return node_to_ffi(element);next = next->next_in_pre_order(&stay_within);}return nullptr;},- .attribute_name_filter_bit = [](uintptr_t local_name) { return Element::attribute_name_filter_bit(Utf16FlyString::from_raw(local_name)); },+ .name_filter_bit = [](uintptr_t local_name) { return Element::name_filter_bit(Utf16FlyString::from_raw(local_name)); },+ .tree_name_filter = [](void const* node) -> u64 {+ // The filter of a document's one element child holds every name of the document's tree.+ auto const& root = node_from_ffi(node).root();+ if (auto const* document = as_if<Document>(root)) {+ auto const* document_element = document->document_element();+ return document_element ? document_element->subtree_name_filter() : 0;+ }+ if (auto const* element = as_if<Element>(root))+ return element->subtree_name_filter();+ return NumericLimits<u64>::max();+ },.shadow_root = [](void const* element) { return node_to_ffi(element_from_ffi(element).shadow_root().ptr()); },.host = [](void const* shadow_root) { return node_to_ffi(static_cast<ShadowRoot const&>(node_from_ffi(shadow_root)).host()); },.id_or_class_equals_ignoring_ascii_case = [](void const* pointer, bool is_class, uintptr_t name_identity) {@@ -293,7 +307,7 @@ public:GC::Ptr<Element> first(ParentNode& root) const{GC::Ptr<Element> result;- for_each_in_subtree(root, [&](Element& element) {+ for_each_match(root, [&](Element& element) {result = element;return true;});@@ -302,13 +316,69 @@ public:void collect(ParentNode& root, Vector<GC::RawPtr<Element>>& elements) const{- for_each_in_subtree(root, [&](Element& element) {+ for_each_match(root, [&](Element& element) {elements.append(element);return false;});}private:+ // Calls `callback` with each element under `root` that matches the query, in tree order, until it returns true.+ template<typename Callback>+ void for_each_match(ParentNode& root, Callback callback) const+ {+ using enum CSS::SelectorFFI::FfiDomIdLookupKind;+ auto lookup = CSS::SelectorFFI::rust_dom_selector_program_id_lookup(m_query.program);+ // NB: An id the query names is looked up in the id map of the tree the query is made in, which holds the+ // elements of a connected tree. A quirks-mode document compares ids ignoring case, which the map does not.+ auto const& document = root.document();+ if (lookup.kind == None || !root.is_connected() || document.in_quirks_mode()) {+ for_each_in_subtree(root, callback);+ return;+ }+ auto const& tree_root = root.root();+ auto const* shadow_root = as_if<ShadowRoot>(tree_root);+ auto const& element_by_id = shadow_root ? shadow_root->element_by_id() : document.element_by_id();+ auto elements = element_by_id.elements_with_id(Utf16FlyString::from_raw(lookup.id));+ auto is_under_root = [&](Node const& node) {+ return &tree_root == &root ? &node != &root : node.is_descendant_of(root);+ };++ if (lookup.kind == Subject) {+ // Only the elements with the id can match.+ GC::RootVector<GC::Ref<Element>, 1> candidates;+ for (auto const& element : elements) {+ if (element && is_under_root(*element))+ candidates.append(*element);+ }+ if (candidates.size() > 1)+ quick_sort(candidates, [](auto const& a, auto const& b) { return a->is_before(*b); });+ for (auto& element : candidates) {+ if (matches(*element) && callback(*element))+ return;+ }+ return;+ }++ // No element without the id holds a match.+ if (elements.is_empty())+ return;+ // NB: The subtrees of several elements with the id can nest, which only a walk of the whole tree visits once.+ if (elements.size() > 1 || !elements[0]) {+ for_each_in_subtree(root, callback);+ return;+ }+ // Every match is under the element with the id, or under its parent past a sibling combinator.+ Node* search_root = elements[0].ptr().ptr();+ if (lookup.kind == AncestorsParent)+ search_root = search_root->parent();+ if (!search_root || !(search_root == &root || is_under_root(*search_root))) {+ for_each_in_subtree(root, callback);+ return;+ }+ for_each_in_subtree(as<ParentNode>(*search_root), callback);+ }+template<typename Callback>void for_each_in_subtree(ParentNode& root, Callback callback) const{diff --git a/Libraries/LibWeb/Rust/src/css/style/batch_matcher.rs b/Libraries/LibWeb/Rust/src/css/style/batch_matcher.rsdeleted file mode 100644index cf9792be06d..00000000000--- a/Libraries/LibWeb/Rust/src/css/style/batch_matcher.rs+++ /dev/null@@ -1,2410 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! The optimized exact batch matcher.-//!-//! This physical plan streams a scope through rule dispatch, ancestor summaries, prefix states,-//! relation and position workspaces, retained witnesses, and optional cascade-winner pruning. Its-//! output is exact, but its accelerators make it unsuitable as the correctness reference. That role-//! belongs to [`super::exact_matcher::ExactMatcher`].--use super::prefix::PrefixTransitionContext;-use smallvec::SmallVec;--use super::ScopeDispatchShape;-use super::cascade::Top1Cascade;-use super::index::AncestorDispatchFacts;-use super::index::AncestorDispatchTopologyID;-use super::index::CandidateEntries;-use super::index::DispatchCandidateWorkspace;-use super::index::DispatchEntry;-use super::index::DispatchKey;-use super::index::ParentDispatchFacts;-use super::index::RuleDispatch;-use super::index::StyleNodeFacts;-use super::instrumentation::Counter;-use super::instrumentation::Counters;-use super::prefix::PrefixEvaluation;-use super::prefix::PrefixMatchSetID;-use super::prefix::PrefixStates;-use super::prefix::PrefixTransitionGap;-use super::prefix::PrefixTransitionLookup;-use super::program::CascadeOrigin;-use super::program::EntryID;-use super::program::RuleID;-use super::program::SelectorProgramID;-use super::program::StyleSheetProgram;-use super::relative_selector::WitnessEffect;-use super::selector::Incomplete;-use super::selector::MatchEvaluationSide;-use super::selector::MatchEvaluator;-use super::selector::MatchScratch;-use super::selector::SelectorEntry;-use super::selector::SelectorProgram;-use super::selector::SelectorPrograms;-use super::selector::Specificity;-use super::tree::PseudoElementTarget;-use super::tree::StyleNodeID;-use super::tree::StyleNodeTree;-use super::tree::TreeScopeID;--/// One rule matching one style node, with the metadata later semantics need.-///-/// The metadata is deliberately small: a selector-list entry and its specificity. Anything static-/// for the selector stays in the program rather than being copied per match.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]-pub struct RuleMatch {- /// The originating element. A pseudo-element match carries its target separately.- pub node: StyleNodeID,- pub pseudo_element: Option<PseudoElementTarget>,- pub rule: RuleID,- pub program: SelectorProgramID,- pub entry: u32,- /// The entry's normal-declaration cascade rank in its tree scope's dispatch. This is complete- /// for an unscoped match; a scoped match also needs its dynamically resolved proximity.- pub cascade_order: u32,- pub specificity: Specificity,- /// The tree scope the rule decided from, which is where its sheet is attached and not- /// necessarily where the element is. `:host`, `::slotted()` and `::part()` all decide for an- /// element outside their own tree, and where the element's cascade weighs that tree is what- /// orders the rule against the contexts around it - so the match carries the scope rather than- /// the cascade deriving it from the element.- pub tree_scope: TreeScopeID,- /// Generational hops from the scoping root the match resolved through, or `u32::MAX` for a rule- /// that is not scoped. A nearer root wins, which is why an unscoped rule is infinitely far.- pub scope_proximity: u32,-}--/// Concrete matches for one evaluation, sorted by style node.-///-/// This is transaction-local scratch: the cascade consumes it and it is discarded. It is not-/// an inverse match relation and is never retained.-#[derive(Default)]-pub struct RuleMatches {- matches: Vec<RuleMatch>,- selector_truth: Option<Vec<super::SelectorTruth>>,-}--impl RuleMatches {- #[must_use]- pub fn new() -> Self {- Self::default()- }-- #[must_use]- pub fn as_slice(&self) -> &[RuleMatch] {- &self.matches- }-- #[must_use]- pub fn as_mut_vec(&mut self) -> &mut Vec<RuleMatch> {- &mut self.matches- }-- #[must_use]- pub fn len(&self) -> usize {- self.matches.len()- }-- #[must_use]- #[cfg(test)]- pub fn is_empty(&self) -> bool {- self.matches.is_empty()- }-- /// Matches for one style node, which is contiguous because the vector is sorted by node.- #[must_use]- #[cfg(test)]- pub fn matches_for(&self, node: StyleNodeID) -> &[RuleMatch] {- let start = self.matches.partition_point(|entry| entry.node < node);- let end = self.matches[start..].partition_point(|entry| entry.node == node) + start;- &self.matches[start..end]- }-- pub(super) fn enable_selector_truth(&mut self) {- self.selector_truth.get_or_insert_default();- }-- fn selector_truth_len(&self) -> usize {- self.selector_truth.as_ref().map_or(0, Vec::len)- }-- fn record_selector_truth(&mut self, entry: EntryID, tree_scope: TreeScopeID, scope_proximity: u32) {- if let Some(truth) = self.selector_truth.as_mut() {- truth.push(super::SelectorTruth {- entry,- tree_scope,- scope_proximity,- });- }- }-- fn truncate(&mut self, matches: usize, selector_truth: usize) {- self.matches.truncate(matches);- if let Some(truth) = self.selector_truth.as_mut() {- truth.truncate(selector_truth);- }- }-- pub(super) fn take_prepared_selector_truth(&mut self) -> Option<Vec<super::SelectorTruth>> {- let mut truth = self.selector_truth.take()?;-- truth.sort_unstable();- truth.dedup();- Some(truth)- }-- #[must_use]- pub fn take(&mut self) -> Vec<RuleMatch> {- std::mem::take(&mut self.matches)- }-- pub fn release(&mut self) {- self.matches = Vec::new();- self.selector_truth = None;- }-}--/// Builds the dispatch index for one style scope from the attached program.-///-/// Only live style rules with a compiled selector participate. A rule of any other kind reaches its-/// consumers through its own typed delta - a keyframes edit starts at animations referencing its-/// name, not at every element in the scope - so bucketing it here would be routing it to the wrong-/// place.-#[must_use]-#[cfg(test)]-pub fn build_scope_dispatch(- program: &StyleSheetProgram,- programs: &SelectorPrograms,- tree_scope: TreeScopeID,-) -> RuleDispatch {- let mut dispatch = RuleDispatch::new();- // The user-agent and user origins have no scope of their own: they decide for every element in- // the document, whichever tree it is in. Their sheets are attached to the document scope, so a- // shadow scope has to take them from there.- if tree_scope != TreeScopeID::DOCUMENT {- // A shadow root built from the document's styles rather than its own takes the author- // origin from there too.- let take = match program.scope_uses_document_sheets(tree_scope) {- true => SheetsToTake::All,- false => SheetsToTake::NonAuthorOnly,- };- insert_scope_sheets(&mut dispatch, program, programs, TreeScopeID::DOCUMENT, take);- }- // Dispatch identity is independent of cascade order, which is assigned after construction.- // Put the document contribution first so shadow roots share a prefix even when their local- // sheets differ, letting a later scope extend the already-built common topology.- insert_scope_sheets(&mut dispatch, program, programs, tree_scope, SheetsToTake::All);- // A standalone dispatch belongs to no engine, so it interns into pools of its own.- dispatch.finish_prefixes(&mut super::prefix::PrefixPools::default());- dispatch-}--/// Describe the selector topology of one effective scope and align each concrete rule with the-/// dense dispatch entries that topology will produce.-pub(super) fn scope_dispatch_shape_and_rules(- program: &StyleSheetProgram,- programs: &SelectorPrograms,- tree_scope: TreeScopeID,-) -> (ScopeDispatchShape, Vec<RuleID>) {- let mut shape = Vec::new();- let mut rules = Vec::new();- let mut collect = |tree_scope, take| {- for_each_scope_rule(program, tree_scope, take, |sheet, rule, selector_program| {- shape.push((selector_program, program.sheet_origin(sheet) == CascadeOrigin::Author));- let compiled = programs.get(selector_program);- for index in 0..compiled.entries().len() {- let metadata = compiled.dispatch_metadata(index);- let copies = if metadata.key == DispatchKey::Universal {- metadata.subject_dispatch_keys().len().max(1)- } else {- 1- };- rules.extend(std::iter::repeat_n(rule, copies));- }- });- };- if tree_scope != TreeScopeID::DOCUMENT {- let take = match program.scope_uses_document_sheets(tree_scope) {- true => SheetsToTake::All,- false => SheetsToTake::NonAuthorOnly,- };- collect(TreeScopeID::DOCUMENT, take);- }- collect(tree_scope, SheetsToTake::All);- (ScopeDispatchShape(shape.into_iter().collect()), rules)-}--/// Put selector batches in a stable topology order, keeping equal batches in their source order.-/// Cascade cache keys must be captured before this changes the rule binding order.-pub(super) fn canonicalize_scope_dispatch(- shape: &mut ScopeDispatchShape,- rules: &mut Vec<RuleID>,- programs: &SelectorPrograms,-) {- let key = |&(program, author): &(SelectorProgramID, bool)| (author, program.0);- if shape.0.is_sorted_by_key(key) {- return;- }- let mut offset = 0_usize;- let mut batches: Vec<_> = shape- .0- .iter()- .copied()- .map(|item| {- let compiled = programs.get(item.0);- let count: usize = (0..compiled.entries().len())- .map(|index| {- let metadata = compiled.dispatch_metadata(index);- if metadata.key == DispatchKey::Universal {- metadata.subject_dispatch_keys().len().max(1)- } else {- 1- }- })- .sum();- let end = offset- .checked_add(count)- .expect("dispatch rule binding space exhausted");- let range = offset..end;- offset = end;- (item, range)- })- .collect();- assert_eq!(offset, rules.len());- batches.sort_by_key(|(item, _)| key(item));- let mut ordered_rules = Vec::with_capacity(rules.len());- let ordered_shape = shape.0.make_mut();- for (index, (item, range)) in batches.into_iter().enumerate() {- ordered_shape[index] = item;- ordered_rules.extend_from_slice(&rules[range]);- }- *rules = ordered_rules;-}--/// Which of a scope's sheets a dispatch build takes.-#[derive(Clone, Copy, PartialEq, Eq)]-enum SheetsToTake {- All,- /// Only the origins that decide outside the scope they are attached to.- NonAuthorOnly,-}--#[cfg(test)]-fn insert_scope_sheets(- dispatch: &mut RuleDispatch,- program: &StyleSheetProgram,- programs: &SelectorPrograms,- tree_scope: TreeScopeID,- take: SheetsToTake,-) {- for_each_scope_rule(program, tree_scope, take, |sheet, rule, selector_program| {- insert_scope_rule(- dispatch,- programs,- rule,- selector_program,- program.sheet_origin(sheet) == CascadeOrigin::Author,- );- });-}--pub(super) fn insert_scope_rule(- dispatch: &mut RuleDispatch,- programs: &SelectorPrograms,- rule: RuleID,- selector_program: SelectorProgramID,- author: bool,-) {- let compiled = programs.get(selector_program);- for index in 0..compiled.entries().len() {- let metadata = compiled.dispatch_metadata(index);- let key = metadata.key;- let subject_dispatch = metadata.subject_dispatch_keys();- let template = super::index::DispatchEntry {- identity: programs.entry_id(- selector_program,- u32::try_from(index).expect("selector entry space exhausted"),- ),- rule,- program: selector_program,- entry: u32::try_from(index).expect("selector entry space exhausted"),- cascade_order: 0,- required_attribute_value: metadata.required_attribute_value,- required_parent: metadata.required_parent,- required_ancestor: metadata.required_ancestor,- required_ancestor_index: None,- required_subject_bloom: metadata.required_subject_bloom,- prefix_matched: false,- multi_key: false,- };- // A subject whose one key is universal but whose disjunction has selective branches- // - `:is(dl, ol) :is(.a, .b)` dispatches on nothing alone - goes under each branch's- // key instead of in front of every element. The cover is sound by the same contract- // routing relies on, and it comes back empty rather than truncated, so an entry is- // never unreachable from a key it needs.- let branch_keys = match key {- DispatchKey::Universal => subject_dispatch,- _ => &[],- };- if branch_keys.is_empty() {- let dispatch_entry = dispatch.insert(key, template);- if let Some(chain) = metadata.prefix_chain() {- // NB: Structural truth bits are admitted for author rules only. The- // convergence walk consumes only author routes, so a user-agent- // positional chain would put its tests into every document's- // automaton, taxing each transition and widening every tree- // flush's re-compare frontier, without any route ever being- // subsumed in return.- dispatch.add_prefix_entry(programs, selector_program, chain, dispatch_entry, author);- }- } else {- // NB: A branch copy carries no required attribute value: a disjunction branch's- // value is not required by the subject, and one copy serves every branch- // naming the same attribute.- //- // NB: A branch copy stays out of the prefix program. The prefix pass emits one- // match per registered entry, so registering every copy would report the- // same rule once per branch key the element carries; the candidate walk- // deduplicates them by the rank the copies share instead.- for &branch_key in branch_keys {- dispatch.insert(- branch_key,- super::index::DispatchEntry {- multi_key: true,- ..template- },- );- }- }- }-}--fn for_each_scope_rule(- program: &StyleSheetProgram,- tree_scope: TreeScopeID,- take: SheetsToTake,- mut callback: impl FnMut(super::program::SheetID, RuleID, SelectorProgramID),-) {- for &sheet in program.sheets_in_scope(tree_scope) {- if take == SheetsToTake::NonAuthorOnly- && !matches!(- program.sheet_origin(sheet),- CascadeOrigin::UserAgent | CascadeOrigin::User- )- {- continue;- }- for rule in program.rules_in_sheet(sheet) {- // A rule behind a condition that does not hold, or in a disabled sheet, stays in the- // dispatch: activation is match-time state, filtered at candidate consumption, so a- // condition flipping does not invalidate the dispatch structure or anything derived- // from it. Only structural liveness excludes a rule here.- if !program.rule_is_live(rule) {- continue;- }- let version = program.rule_version(rule);- if !version.kind.matches_elements() {- continue;- }- let Some(selector_program) = version.selector_program else {- continue;- };- callback(sheet, rule, selector_program);- }- }-}--/// Exact ancestor requirements, packed once per fact-batch row.-///-/// Many selector entries ask the same question of one candidate's ancestry. Walking that ancestry-/// for each entry repeats both relation steps and fact lookups, so a cold batch assigns every-/// required key one bit and inherits the bits from parent to child once.-#[derive(Clone)]-pub(super) struct AncestorRequirements {- words_per_row: usize,- bits: Vec<u64>,- /// Rows whose ancestry the bits do not fully describe, so nothing may be rejected from them.- unbounded: Vec<bool>,- /// The one row a per-element summary describes, or none when every row has a slice of its own.- single_row: Option<u32>,- selected_rows: Vec<u32>,-}--impl AncestorRequirements {- pub(super) fn build(tree: &StyleNodeTree, facts: &StyleNodeFacts, dispatch: &RuleDispatch) -> Self {- let words_per_row = dispatch.ancestor_key_count().div_ceil(u64::BITS as usize);- let row_count = facts.row_count();- let mut bits = vec![0; row_count.saturating_mul(words_per_row)];- let mut unbounded = vec![false; row_count];- let mut computed = vec![false; row_count];- let mut chain = Vec::with_capacity(row_count);-- // The batch holds a row per element, so a parent with no row is not one: a shadow root,- // which publishes nothing and stands between a tree and whatever hosts it. Inheriting stops- // there - and from there on the bits are no longer the whole answer, because a selector can- // cross that boundary. `:host(.h) .inner` requires `.h` of the host, which is not an- // ancestor of anything inside the tree. Rows below a boundary are therefore marked- // unbounded and reject nothing, exactly as walking the ancestors does when it meets a node- // it has no facts for.- let parent_row = |node: StyleNodeID| tree.parent(node).and_then(|parent| facts.row_of(parent));-- // Rows normally arrive in tree order. Following parents until an already-built row also- // keeps this exact for a differently ordered batch without making deep DOM trees recurse.- for start in 0..row_count {- if !facts.has_row(u32::try_from(start).expect("fact batch row space exhausted")) {- computed[start] = true;- unbounded[start] = true;- continue;- }- if computed[start] {- continue;- }- let mut row = start;- while !computed[row] {- chain.push(u32::try_from(row).expect("fact batch row space exhausted"));- let Some(parent) = parent_row(facts.node_at(row as u32)) else {- break;- };- row = parent as usize;- }-- while let Some(row) = chain.pop() {- let row = row as usize;- let node = facts.node_at(row as u32);- if let Some(parent_row) = parent_row(node) {- let parent = tree.parent(node).expect("a parent row implies a parent");- let parent_row = parent_row as usize;- unbounded[row] = unbounded[parent_row];- for word in 0..words_per_row {- bits[row * words_per_row + word] = bits[parent_row * words_per_row + word];- }- facts.for_each_dispatch_key(parent_row as u32, tree.parent(parent).is_none(), |key| {- let Some(index) = dispatch.ancestor_key_index(key) else {- return;- };- let index = index as usize;- bits[row * words_per_row + index / u64::BITS as usize] |= 1_u64 << (index % u64::BITS as usize);- });- } else {- unbounded[row] = tree.parent(node).is_some();- }- computed[row] = true;- }- }-- Self {- words_per_row,- bits,- unbounded,- single_row: None,- selected_rows: Vec::new(),- }- }-- /// Summarize one element's ancestor requirements with a single walk.- ///- /// `None` means the facts materialized so far do not describe the element itself, which is for- /// the caller to answer rather than this. Running out of ancestors part of the way up is a- /// different thing and is recorded the same way the batch build records it: as a row the bits- /// do not describe, which rejects nothing.- #[must_use]- pub(super) fn build_for_node(- tree: &StyleNodeTree,- facts: &StyleNodeFacts,- dispatch: &RuleDispatch,- node: StyleNodeID,- ) -> Option<Self> {- let row = facts.row_of(node)?;- let words_per_row = dispatch.ancestor_key_count().div_ceil(u64::BITS as usize);- let mut bits = vec![0; words_per_row];- let mut unbounded = false;- let mut current = node;- while let Some(parent) = tree.parent(current) {- let Some(parent_row) = facts.row_of(parent) else {- unbounded = true;- break;- };- facts.for_each_dispatch_key(parent_row, tree.parent(parent).is_none(), |key| {- let Some(index) = dispatch.ancestor_key_index(key) else {- return;- };- let index = index as usize;- bits[index / u64::BITS as usize] |= 1_u64 << (index % u64::BITS as usize);- });- current = parent;- }- Some(Self {- words_per_row,- bits,- unbounded: vec![unbounded],- single_row: Some(row),- selected_rows: Vec::new(),- })- }-- fn build_for_nodes(- tree: &StyleNodeTree,- facts: &StyleNodeFacts,- dispatch: &RuleDispatch,- nodes: &[StyleNodeID],- ) -> Self {- let mut selected_rows: Vec<u32> = nodes.iter().filter_map(|&node| facts.row_of(node)).collect();- selected_rows.sort_unstable();- selected_rows.dedup();- let words_per_row = dispatch.ancestor_key_count().div_ceil(u64::BITS as usize);- let mut bits = Vec::with_capacity(selected_rows.len().saturating_mul(words_per_row));- let mut unbounded = Vec::with_capacity(selected_rows.len());- for &row in &selected_rows {- let local = Self::build_for_node(tree, facts, dispatch, facts.node_at(row)).unwrap();- bits.extend_from_slice(&local.bits);- unbounded.push(local.unbounded[0]);- }- Self {- words_per_row,- bits,- unbounded,- single_row: None,- selected_rows,- }- }-- #[must_use]- pub(super) fn dispatch_facts(&self, row: u32) -> AncestorDispatchFacts<'_> {- let row = match self.single_row {- Some(single_row) => {- debug_assert_eq!(row, single_row);- 0- }- None if !self.selected_rows.is_empty() => self- .selected_rows- .binary_search(&row)- .expect("a matched row must have prepared ancestor requirements"),- None => row as usize,- };- let first = row * self.words_per_row;- AncestorDispatchFacts::new(&self.bits[first..first + self.words_per_row], self.unbounded[row])- }-}--/// Exact ancestor summaries prepared before one synchronous matching traversal.-#[derive(Clone, Default)]-pub(super) struct AncestorRequirementsCache {- // Concrete rule identities and cascade ranks do not affect ancestor requirements.- by_topology: Vec<(AncestorDispatchTopologyID, AncestorRequirements)>,-}--impl AncestorRequirementsCache {- pub(super) fn prepare(- &mut self,- tree: &StyleNodeTree,- facts: &StyleNodeFacts,- dispatch: &RuleDispatch,- nodes: Option<&[StyleNodeID]>,- ) -> &AncestorRequirements {- let topology = dispatch.ancestor_topology_id();- if !self.by_topology.iter().any(|(held, _)| *held == topology) {- let requirements = match nodes {- Some(nodes) => AncestorRequirements::build_for_nodes(tree, facts, dispatch, nodes),- None => AncestorRequirements::build(tree, facts, dispatch),- };- self.by_topology.push((topology, requirements));- }- self.get(dispatch)- }-- pub(super) fn get(&self, dispatch: &RuleDispatch) -> &AncestorRequirements {- let topology = dispatch.ancestor_topology_id();- &self- .by_topology- .iter()- .find(|(held, _)| *held == topology)- .expect("ancestor requirements must be prepared before matching")- .1- }-- pub(super) fn release(&mut self) {- self.by_topology = Vec::new();- }-}--/// Exactly evaluates rule matching over a region, consulting no derived state.-pub struct BatchMatcher<'a> {- tree: &'a StyleNodeTree,- facts: &'a StyleNodeFacts,- dispatch: &'a RuleDispatch,- programs: &'a SelectorPrograms,- /// The stylesheet program, for the activation filter: the dispatch keeps every structurally- /// live rule, and whether one decides right now is asked per candidate.- program: &'a StyleSheetProgram,- /// The tree scope whose rules are being evaluated.- scope: TreeScopeID,- /// The shadow root of the tree whose rules are being evaluated, when it is one.- shadow_root: Option<StyleNodeID>,- /// Whether the node being asked stands outside this tree and is slotted into it. Only- /// `::slotted()` reaches such a node; the tree's ordinary selectors decide inside it.- node_is_slotted_in: bool,- /// Whether the node being asked is inside a tree this scope contains, exposed to it as a part.- /// Only `::part()` reaches such a node.- node_is_a_part_exposed_here: bool,- /// Whether the node being asked is the host of the tree whose rules these are. A host stands- /// outside the tree its own root opens and is featureless there, so only `:host` reaches it.- node_is_the_host_of_this_tree: bool,- ancestor_requirements: Option<&'a AncestorRequirements>,- /// Evaluate only these rules, sorted by (rule, program). The retained-answer patch asks one- /// node about exactly the rules a transaction reached, through the same machinery a full- /// match uses.- rule_filter: Option<&'a [(RuleID, SelectorProgramID)]>,- cascade_only: bool,-}--/// Pruning remains relevant when an incomplete attempt retains completed candidates for a retry.-pub(super) struct BatchMatchOutcome {- pub result: Result<(), Incomplete>,- pub answer_is_exact: bool,-}--/// Reusable output-side state for one exact matching attempt.-pub(super) struct BatchMatchState<'a> {- pub match_workspace: Option<&'a mut MatchScratch>,- pub witness_effects: Option<&'a mut Vec<WitnessEffect>>,- pub dispatch_workspace: &'a mut DispatchCandidateWorkspace,- pub requests: Option<&'a mut Vec<Incomplete>>,- pub completed: Option<&'a mut [bool]>,- pub prefix_states: Option<(&'a mut PrefixStates, &'a mut PrefixTransitionContext)>,- pub deferred_prefix_matches: Option<&'a mut Option<PrefixMatchSetID>>,-}--#[allow(clippy::too_many_arguments)]-fn append_matched_entry(- out: &mut RuleMatches,- start: usize,- node: StyleNodeID,- scope: TreeScopeID,- candidate: DispatchEntry,- compiled: &SelectorProgram,- entry: &SelectorEntry,- scope_proximity: u32,- completed: &mut Option<&mut [bool]>,- counters: &Counters,- count_emission: CountRuleMatchEmission,-) {- out.record_selector_truth(candidate.identity, scope, scope_proximity);- let candidate_index = candidate.cascade_order as usize;- // A selector list can match through several entries. Only its greatest matching specificity- // contributes, independently for the element and each pseudo-element target.- if compiled.entries().len() > 1 {- let existing = match completed.is_some() {- true => out.matches.iter_mut().find(|existing| {- existing.node == node- && existing.tree_scope == scope- && existing.rule == candidate.rule- && existing.pseudo_element == entry.pseudo_element- }),- false => out.matches[start..]- .iter_mut()- .find(|existing| existing.rule == candidate.rule && existing.pseudo_element == entry.pseudo_element),- };- if let Some(existing) = existing {- if entry.specificity > existing.specificity {- existing.entry = candidate.entry;- existing.cascade_order = candidate.cascade_order;- existing.specificity = entry.specificity;- existing.scope_proximity = scope_proximity;- }- if let Some(completed) = completed.as_deref_mut() {- completed[candidate_index] = true;- }- return;- }- }-- out.matches.push(RuleMatch {- node,- pseudo_element: entry.pseudo_element,- rule: candidate.rule,- program: candidate.program,- entry: candidate.entry,- cascade_order: candidate.cascade_order,- tree_scope: scope,- specificity: entry.specificity,- scope_proximity,- });- if count_emission == CountRuleMatchEmission::Yes {- counters.bump(Counter::RuleMatchesEmitted);- }- if let Some(completed) = completed.as_deref_mut() {- completed[candidate_index] = true;- }-}--#[derive(Clone, Copy, PartialEq, Eq)]-pub(super) enum CountRuleMatchEmission {- No,- Yes,-}--#[allow(clippy::too_many_arguments)]-pub(super) fn append_prefix_matches(- out: &mut RuleMatches,- node: StyleNodeID,- scope: TreeScopeID,- dispatch: &RuleDispatch,- program: &StyleSheetProgram,- programs: &SelectorPrograms,- matches: &[EntryID],- counters: &Counters,- count_emission: CountRuleMatchEmission,-) {- let mut completed = None;- for &matched in matches {- for candidate in dispatch.entries_for_identity(matched) {- if !candidate.prefix_matched {- continue;- }- if !program.rule_can_decide(candidate.rule) {- continue;- }- let compiled = programs.get(candidate.program);- let entry = &compiled.entries()[candidate.entry as usize];- append_matched_entry(- out,- 0,- node,- scope,- candidate,- compiled,- entry,- u32::MAX,- &mut completed,- counters,- count_emission,- );- }- }-}--#[allow(clippy::too_many_arguments)]-pub(super) fn append_selector_truth_matches(- out: &mut RuleMatches,- node: StyleNodeID,- program: &StyleSheetProgram,- programs: &SelectorPrograms,- dispatch: &RuleDispatch,- truth: &[super::SelectorTruth],- counters: &Counters,-) {- let mut completed = None;- for &matched in truth {- let mut previous = None;- for candidate in dispatch.entries_for_identity(matched.entry) {- let candidate_key = (candidate.rule, candidate.program, candidate.entry);- if previous == Some(candidate_key) {- continue;- }- previous = Some(candidate_key);- if !program.rule_can_decide(candidate.rule) {- continue;- }- let compiled = programs.get(candidate.program);- let entry = &compiled.entries()[candidate.entry as usize];- append_matched_entry(- out,- 0,- node,- matched.tree_scope,- candidate,- compiled,- entry,- matched.scope_proximity,- &mut completed,- counters,- CountRuleMatchEmission::No,- );- }- }-}--pub(super) fn append_retained_matches(- out: &mut RuleMatches,- node: StyleNodeID,- tree_scope: TreeScopeID,- programs: &SelectorPrograms,- dispatch: &RuleDispatch,- matches: &[super::RetainedRuleMatch],-) -> Option<()> {- out.matches.reserve_exact(matches.len());- for &stored_match in matches {- let mut matched = stored_match;- matched.tree_scope = tree_scope;- let cascade_order = dispatch.cascade_order_for_entry(matched.rule, matched.program, matched.entry)?;- let matched = matched.materialize(node, programs, cascade_order)?;- if programs.get(matched.program).entries().len() > 1- && let Some(existing) = out.matches.iter_mut().find(|existing| {- existing.rule == matched.rule- && existing.tree_scope == matched.tree_scope- && existing.pseudo_element == matched.pseudo_element- })- {- if matched.specificity > existing.specificity {- *existing = matched;- }- continue;- }- out.matches.push(matched);- }- Some(())-}--impl<'a> BatchMatcher<'a> {- #[must_use]- pub fn new(- tree: &'a StyleNodeTree,- facts: &'a StyleNodeFacts,- dispatch: &'a RuleDispatch,- programs: &'a SelectorPrograms,- program: &'a StyleSheetProgram,- ) -> Self {- Self {- tree,- facts,- dispatch,- programs,- program,- scope: TreeScopeID::DOCUMENT,- shadow_root: None,- node_is_slotted_in: false,- node_is_a_part_exposed_here: false,- node_is_the_host_of_this_tree: false,- ancestor_requirements: None,- rule_filter: None,- cascade_only: false,- }- }-- /// Match only rules that can still contribute to the cascade.- #[must_use]- pub fn for_cascade(mut self) -> Self {- self.cascade_only = true;- self- }-- fn cascade_properties_of(&self, entry: DispatchEntry) -> Option<&'a [u16]> {- self.dispatch.cascade_properties(entry)- }-- /// Evaluate the rules of one tree scope. What a rule's scope is decides how deeply encapsulated- /// it is, which the cascade compares.- #[must_use]- pub fn in_scope(mut self, scope: TreeScopeID) -> Self {- self.scope = scope;- self- }-- /// Evaluate rules attached to one shadow tree rather than to the document.- #[must_use]- pub fn in_shadow_tree(mut self, shadow_root: StyleNodeID) -> Self {- self.shadow_root = Some(shadow_root);- self- }-- /// Ask this tree's rules of a node that is slotted into it rather than in it.- #[must_use]- pub fn for_a_node_slotted_in(mut self) -> Self {- self.node_is_slotted_in = true;- self- }-- /// Ask this scope's rules of a node inside a shadow tree it contains, exposed to it as a part.- #[must_use]- pub fn for_a_part_exposed_here(mut self) -> Self {- self.node_is_a_part_exposed_here = true;- self- }-- /// Ask this tree's rules of the host it hangs off, which stands outside the tree.- #[must_use]- pub fn for_the_host_of_this_tree(mut self) -> Self {- self.node_is_the_host_of_this_tree = true;- self- }-- #[must_use]- pub(super) fn with_ancestor_requirements(mut self, requirements: &'a AncestorRequirements) -> Self {- self.ancestor_requirements = Some(requirements);- self- }-- /// Evaluate only these rules, sorted by (rule, program).- #[must_use]- pub(super) fn with_rule_filter(mut self, rules: &'a [(RuleID, SelectorProgramID)]) -> Self {- self.rule_filter = Some(rules);- self- }-- /// A filtered ask is a patch re-deriving part of one answer; only a full evaluation counts- /// as matching activity.- fn count_rule_match_emission(&self) -> CountRuleMatchEmission {- match self.rule_filter.is_none() {- true => CountRuleMatchEmission::Yes,- false => CountRuleMatchEmission::No,- }- }-- fn rule_filter_admits(&self, rule: RuleID, program: SelectorProgramID) -> bool {- self.rule_filter- .is_none_or(|rules| rules.binary_search(&(rule, program)).is_ok())- }-- pub(super) fn filtered_rules_are_narrow(&self, rules: &[(RuleID, SelectorProgramID)]) -> bool {- let mut entry_count = 0;- for &(rule, program) in rules {- if !self.program.rule_can_decide(rule) || self.program.rule_version(rule).selector_program != Some(program)- {- continue;- }- entry_count += self.programs.get(program).entries().len();- // Dispatch pays a fixed cost to gather the node's subject buckets before applying the- // rule filter. Exact enumeration avoids that cost for a narrow patch, but gives up the- // subject index's pruning, so keep broad selector lists on the indexed path.- if entry_count > 128 {- return false;- }- }- true- }-- fn match_filtered_rules_directly(- &self,- node: StyleNodeID,- row: u32,- rules: &[(RuleID, SelectorProgramID)],- evaluator: &mut MatchEvaluator<'_>,- out: &mut RuleMatches,- counters: &Counters,- ) -> Result<(), Incomplete> {- let start = out.matches.len();- let selector_truth_start = out.selector_truth_len();- let is_document_root = self.tree.parent(node).is_none();- for &(rule, program) in rules {- if !self.program.rule_can_decide(rule) || self.program.rule_version(rule).selector_program != Some(program)- {- continue;- }- let compiled = self.programs.get(program);- for (entry_index, entry) in compiled.entries().iter().enumerate() {- let subject_dispatch = compiled.subject_dispatch_keys(entry_index);- let matched_dispatch_key = subject_dispatch- .iter()- .copied()- .find(|&key| self.facts.carries_dispatch_key(row, key, is_document_root));- if !subject_dispatch.is_empty() && matched_dispatch_key.is_none() {- continue;- }- if compiled.subject_required_keys(entry_index).iter().any(|&key| {- Some(key) != matched_dispatch_key && !self.facts.carries_dispatch_key(row, key, is_document_root)- }) {- continue;- }- let entry_index = u32::try_from(entry_index).expect("selector entry space exhausted");- let Some(cascade_order) = self.dispatch.cascade_order_for_entry(rule, program, entry_index) else {- continue;- };- if self.node_is_slotted_in && !compiled.subject_is_slotted(entry.root) {- continue;- }- if self.node_is_a_part_exposed_here && !compiled.subject_is_a_part(entry.root) {- continue;- }- if self.node_is_the_host_of_this_tree && !compiled.subject_is_the_host(entry.root) {- continue;- }- counters.bump(Counter::CandidateChecks);- let matches = match evaluator.matches_entry_for_program(program, compiled, entry, node, counters) {- Ok(matches) => matches,- Err(incomplete) => {- out.truncate(start, selector_truth_start);- return Err(incomplete);- }- };- if !matches {- continue;- }- let scope_proximity = match evaluator.scope_proximity_of(compiled, entry, node, counters) {- Ok(scope_proximity) => scope_proximity,- Err(incomplete) => {- out.truncate(start, selector_truth_start);- return Err(incomplete);- }- };- let matched = RuleMatch {- node,- pseudo_element: entry.pseudo_element,- rule,- program,- entry: entry_index,- cascade_order,- tree_scope: self.scope,- specificity: entry.specificity,- scope_proximity,- };- out.record_selector_truth(- self.programs.entry_id(program, entry_index),- self.scope,- scope_proximity,- );- if let Some(existing) = out.matches[start..]- .iter_mut()- .find(|existing| existing.rule == rule && existing.pseudo_element == entry.pseudo_element)- {- if matched.specificity > existing.specificity {- *existing = matched;- }- } else {- out.matches.push(matched);- }- }- }- Ok(())- }-- /// Evaluate every style node in the subtree rooted at `root`, appending matches in node order.- ///- /// A missing fact row aborts the pass rather than being answered: the caller widens its batch- /// and asks again. Partial output is never published.- #[cfg(test)]- pub fn match_subtree(- &self,- root: StyleNodeID,- out: &mut RuleMatches,- counters: &Counters,- ) -> Result<(), Incomplete> {- let start = out.matches.len();- let selector_truth_start = out.selector_truth_len();- let mut dispatch_workspace = DispatchCandidateWorkspace::default();- let mut prefix_states = PrefixStates::new();- let mut prefix_context = PrefixTransitionContext::new(&mut prefix_states, self.facts);- for node in self.tree.preorder(root) {- if let Err(incomplete) = self- .match_node_collecting_requests(- node,- out,- counters,- BatchMatchState {- match_workspace: None,- witness_effects: None,- dispatch_workspace: &mut dispatch_workspace,- requests: None,- completed: None,- prefix_states: Some((&mut prefix_states, &mut prefix_context)),- deferred_prefix_matches: None,- },- )- .result- {- out.truncate(start, selector_truth_start);- return Err(incomplete);- }- }- out.matches[start..].sort_unstable_by_key(|entry| (entry.node, entry.rule));- Ok(())- }-- /// Evaluate one style node exactly.- #[cfg(test)]- pub fn match_node(&self, node: StyleNodeID, out: &mut RuleMatches, counters: &Counters) -> Result<(), Incomplete> {- let mut dispatch_workspace = DispatchCandidateWorkspace::default();- let mut prefix_states = PrefixStates::new();- let mut prefix_context = PrefixTransitionContext::new(&mut prefix_states, self.facts);- self.match_node_collecting_requests(- node,- out,- counters,- BatchMatchState {- match_workspace: None,- witness_effects: None,- dispatch_workspace: &mut dispatch_workspace,- requests: None,- completed: None,- prefix_states: Some((&mut prefix_states, &mut prefix_context)),- deferred_prefix_matches: None,- },- )- .result- }-- /// Evaluate one style node while retaining every fact request the candidate set discovers.- ///- /// The ordinary document pass materializes the whole scope and has nothing to batch. An- /// element-at-a-time cold ask starts from a deliberately small fact set, though, and restarting- /// at the first missing row makes independent selector paths each replay every candidate that- /// preceded them. Collecting the exact requests lets that caller materialize them together and- /// retry the unfinished candidates together.- pub(super) fn match_node_collecting_requests(- &self,- node: StyleNodeID,- out: &mut RuleMatches,- counters: &Counters,- state: BatchMatchState<'_>,- ) -> BatchMatchOutcome {- let mut answer_is_exact = true;- let BatchMatchState {- match_workspace,- witness_effects,- dispatch_workspace,- mut requests,- mut completed,- prefix_states,- deferred_prefix_matches,- } = state;- let Some(row) = self.facts.row_of(node) else {- return BatchMatchOutcome {- result: Err(Incomplete::MissingFacts(node)),- answer_is_exact,- };- };- // A filtered ask is a patch re-deriving part of one answer, not a cold evaluation.- if self.rule_filter.is_none() {- counters.bump(Counter::ColdNodesEvaluated);- }-- let mut evaluator = MatchEvaluator::new(self.tree, self.facts);- if let Some(workspace) = match_workspace {- evaluator = evaluator.with_match_workspace(workspace, MatchEvaluationSide::Current);- }- if let Some(shadow_root) = self.shadow_root {- evaluator = evaluator.in_shadow_tree(shadow_root);- }- if self.node_is_a_part_exposed_here {- evaluator = evaluator.for_a_part_exposed_in(self.scope);- }- if let Some(witnesses) = witness_effects {- evaluator = evaluator.observing_witnesses(witnesses);- }- if let Some(rules) = self.rule_filter.filter(|rules| self.filtered_rules_are_narrow(rules)) {- return BatchMatchOutcome {- result: self.match_filtered_rules_directly(node, row, rules, &mut evaluator, out, counters),- answer_is_exact,- };- }- let start = out.matches.len();- let selector_truth_start = out.selector_truth_len();- let mut used_prefixes = false;- let mut cascade_pruning_blocked = false;- if !self.node_is_slotted_in && !self.node_is_a_part_exposed_here && !self.node_is_the_host_of_this_tree {- let prefix_matches = match prefix_states {- None => None,- Some((states, context)) => {- let mut evaluation = PrefixEvaluation::new(- self.dispatch.prefixes(),- self.tree,- self.facts,- self.programs,- &mut evaluator,- self.shadow_root,- None,- );- match states.match_set_for(- &mut context.scratch,- &mut context.effects,- &mut evaluation,- node,- counters,- ) {- PrefixTransitionLookup::Known(matches) => Some((states, matches)),- // The sibling-aware walk reads the node's left context, which a selective- // batch may not have materialized yet. A missing row is answered the way- // every other missing row is, so the automaton keeps the entries it owns- // instead of flooding the exact fallback with them. A request-collecting- // pass names the whole left context at once to preserve its one-restart- // contract; an aborting pass reports the first gap and lets the caller's- // sibling window widen around it.- PrefixTransitionLookup::Missing(PrefixTransitionGap::Incomplete(Incomplete::MissingFacts(- missing,- ))) if self.dispatch.prefixes().has_sibling_steps() => {- let Some(requests) = requests.as_deref_mut() else {- return BatchMatchOutcome {- result: Err(Incomplete::MissingFacts(missing)),- answer_is_exact,- };- };- let mut level = Some(node);- while let Some(current) = level {- let mut previous = self.tree.previous_element_sibling(current);- while let Some(sibling) = previous {- if self.facts.row_of(sibling).is_none() {- requests.push(Incomplete::MissingFacts(sibling));- }- previous = self.tree.previous_element_sibling(sibling);- }- level = self- .tree- .parent(current)- .filter(|&parent| Some(parent) != self.shadow_root);- }- None- }- PrefixTransitionLookup::Missing(_) => None,- }- }- };- if let Some((states, prefix_matches)) = prefix_matches {- used_prefixes = true;- for &matched in states.matches_in(prefix_matches) {- out.record_selector_truth(matched, self.scope, u32::MAX);- }- cascade_pruning_blocked = self.cascade_only- && states.matches_in(prefix_matches).iter().any(|&matched| {- self.dispatch- .entries_for_identity(matched)- .filter(|candidate| candidate.prefix_matched)- .any(|candidate| self.dispatch.cascade_pruning_blocker(candidate))- });- if let Some(deferred) = deferred_prefix_matches {- *deferred = Some(prefix_matches);- } else {- for &matched in states.matches_in(prefix_matches) {- for candidate in self.dispatch.entries_for_identity(matched) {- if !candidate.prefix_matched {- continue;- }- if !self.rule_filter_admits(candidate.rule, candidate.program) {- continue;- }- if !self.program.rule_can_decide(candidate.rule) {- continue;- }- let candidate_index = candidate.cascade_order as usize;- if completed.as_deref().is_some_and(|completed| completed[candidate_index]) {- continue;- }- let compiled = self.programs.get(candidate.program);- let entry = &compiled.entries()[candidate.entry as usize];- append_matched_entry(- out,- start,- node,- self.scope,- candidate,- compiled,- entry,- u32::MAX,- &mut completed,- counters,- self.count_rule_match_emission(),- );- }- }- }- }- }- let mut first_incomplete = None;- // Copies of a multi-key entry share one cascade order; an element carrying two of the- // entry's branch keys walks past the second copy here. The list stays tiny because only- // disjunction subjects are multi-key.- let mut seen_multi_key_orders: SmallVec<[u32; 4]> = SmallVec::new();- let is_document_root = self.tree.parent(node).is_none();- let parent_facts = match self.tree.parent(node) {- None => ParentDispatchFacts::NoElementParent,- Some(parent) => match self.facts.row_of(parent) {- Some(row) => ParentDispatchFacts::Known {- row,- is_document_root: self.tree.parent(parent).is_none(),- },- None => ParentDispatchFacts::Unknown,- },- };- let ancestor_facts = self- .ancestor_requirements- .map(|requirements| requirements.dispatch_facts(row));- let mut cascade_winners = Top1Cascade::with_capacity(0);- let mut matched_pseudo_targets: SmallVec<[_; 2]> = SmallVec::new();- if self.cascade_only {- for matched in out- .matches- .iter()- .filter(|matched| matched.node == node && matched.tree_scope == self.scope)- {- if self.dispatch.cascade_pruning_blocker_for_order(matched.cascade_order) {- cascade_pruning_blocked = true;- }- let compiled = self.programs.get(matched.program);- let entry = &compiled.entries()[matched.entry as usize];- let Some(properties) = self.dispatch.cascade_properties_for_order(matched.cascade_order) else {- continue;- };- if let Some(target) = entry.pseudo_element- && !matched_pseudo_targets.contains(&target)- {- matched_pseudo_targets.push(target);- }- for &property in properties {- cascade_winners.consider((entry.pseudo_element, property), matched.cascade_order, ());- }- }- }- let candidates = match used_prefixes {- true => CandidateEntries::NonPrefix,- false => CandidateEntries::All,- };- for candidate in self.dispatch.candidates_for(- self.facts,- row,- is_document_root,- parent_facts,- ancestor_facts,- candidates,- self.cascade_only,- dispatch_workspace,- ) {- let candidate_index = candidate.cascade_order as usize;- if candidate.multi_key {- if seen_multi_key_orders.contains(&candidate.cascade_order) {- continue;- }- seen_multi_key_orders.push(candidate.cascade_order);- }- if completed.as_deref().is_some_and(|completed| completed[candidate_index]) {- continue;- }- if !self.rule_filter_admits(candidate.rule, candidate.program) {- continue;- }- // A rule behind a condition that does not hold decides nothing right now. Its entry- // stays in the dispatch so the condition can flip without rebuilding it.- if !self.program.rule_can_decide(candidate.rule) {- if let Some(completed) = completed.as_deref_mut() {- completed[candidate_index] = true;- }- continue;- }- if candidate.prefix_matched && used_prefixes {- if let Some(completed) = completed.as_deref_mut() {- completed[candidate_index] = true;- }- continue;- }- let compiled = self.programs.get(candidate.program);- let entry = &compiled.entries()[candidate.entry as usize];- if self.cascade_only- && !cascade_pruning_blocked- && let Some(properties) = self.cascade_properties_of(candidate)- {- let pseudo_target_is_known = entry- .pseudo_element- .is_none_or(|target| matched_pseudo_targets.contains(&target));- if pseudo_target_is_known- && properties.iter().all(|&property| {- cascade_winners- .winner(&(entry.pseudo_element, property))- .is_some_and(|winner| winner.priority >= candidate.cascade_order)- })- {- answer_is_exact = false;- counters.bump(Counter::CascadeCandidatesRejectedByWinner);- if let Some(completed) = completed.as_deref_mut() {- completed[candidate_index] = true;- }- continue;- }- }- counters.bump(Counter::CandidateChecks);- // A slotted element is in this tree's light DOM, not in the tree: only the rules that- // name it as such reach it.- if self.node_is_slotted_in && !compiled.subject_is_slotted(entry.root) {- if let Some(completed) = completed.as_deref_mut() {- completed[candidate_index] = true;- }- continue;- }- // A part is inside a tree this scope does not decide in: only the rules that name it as- // a part reach it.- if self.node_is_a_part_exposed_here && !compiled.subject_is_a_part(entry.root) {- if let Some(completed) = completed.as_deref_mut() {- completed[candidate_index] = true;- }- continue;- }- // Considered within its own shadow trees, a host is featureless: only `:host`, `:host()`- // and `:host-context()` are allowed to match it, and a `*` or a `.thing` in the tree- // decides nothing about the element the tree hangs off.- // https://drafts.csswg.org/css-scoping-1/#host-element-in-tree- if self.node_is_the_host_of_this_tree && !compiled.subject_is_the_host(entry.root) {- if let Some(completed) = completed.as_deref_mut() {- completed[candidate_index] = true;- }- continue;- }- // The filter rejects what it can prove and decides nothing else. A node the fact store- // holds no row for - a shadow root, which publishes nothing at all - answers neither- // way, so a candidate standing under one goes to the evaluator rather than being- // rejected on a question nobody answered.- if let Some(required) = candidate.required_parent {- let rejected = self- .tree- .parent(node)- .is_none_or(|parent| evaluator.node_cannot_carry_dispatch_key(required, parent));- if rejected {- if let Some(completed) = completed.as_deref_mut() {- completed[candidate_index] = true;- }- continue;- }- }- if let Some(required) = candidate.required_ancestor {- // The summary is exact within the node's own scope, where it also knows that a- // shadow root carries nothing. The walk cannot: a node it has no row for answers- // neither way, so it admits and the evaluator settles it.- let rejected = match (ancestor_facts, candidate.required_ancestor_index) {- (Some(_), Some(_)) => false,- _ => self- .tree- .ancestors(node)- .all(|ancestor| evaluator.node_cannot_carry_dispatch_key(required, ancestor)),- };- if rejected {- if let Some(completed) = completed.as_deref_mut() {- completed[candidate_index] = true;- }- continue;- }- }- match evaluator.matches_entry_for_program(candidate.program, compiled, entry, node, counters) {- Ok(true) => {}- Ok(false) => {- if let Some(completed) = completed.as_deref_mut() {- completed[candidate_index] = true;- }- continue;- }- Err(incomplete) => {- if self.dispatch.cascade_pruning_blocker(candidate) {- cascade_pruning_blocked = true;- }- first_incomplete.get_or_insert(incomplete);- if let Some(requests) = requests.as_deref_mut() {- if !requests.contains(&incomplete) {- requests.push(incomplete);- }- continue;- }- out.truncate(start, selector_truth_start);- return BatchMatchOutcome {- result: Err(incomplete),- answer_is_exact,- };- }- }-- let scope_proximity = match evaluator.scope_proximity_of(compiled, entry, node, counters) {- Ok(proximity) => proximity,- Err(incomplete) => {- first_incomplete.get_or_insert(incomplete);- if let Some(requests) = requests.as_deref_mut() {- if !requests.contains(&incomplete) {- requests.push(incomplete);- }- continue;- }- out.truncate(start, selector_truth_start);- return BatchMatchOutcome {- result: Err(incomplete),- answer_is_exact,- };- }- };- if self.dispatch.cascade_pruning_blocker(candidate) {- cascade_pruning_blocked = true;- }- if self.cascade_only- && !cascade_pruning_blocked- && let Some(properties) = self.cascade_properties_of(candidate)- {- if let Some(target) = entry.pseudo_element- && !matched_pseudo_targets.contains(&target)- {- matched_pseudo_targets.push(target);- }- for &property in properties {- cascade_winners.consider((entry.pseudo_element, property), candidate.cascade_order, ());- }- }- append_matched_entry(- out,- start,- node,- self.scope,- candidate,- compiled,- entry,- scope_proximity,- &mut completed,- counters,- self.count_rule_match_emission(),- );- }- if let Some(incomplete) = first_incomplete {- if completed.is_none() {- out.truncate(start, selector_truth_start);- }- return BatchMatchOutcome {- result: Err(incomplete),- answer_is_exact,- };- }- BatchMatchOutcome {- result: Ok(()),- answer_is_exact,- }- }-}--#[cfg(test)]-mod tests {- use super::super::index::AttributeFact;- use super::super::index::StateSet;- use super::super::index::StyleAtomID;- use super::super::planning::SelectorTruthChanges;- use super::super::planning::record_match_set_difference;- use super::super::program::CascadeOrigin;- use super::super::program::RuleKind;- use super::super::program::StyleSheetObjectID;- use super::super::selector::FeatureTest;- use super::super::selector::NthPosition;- use super::super::selector::SelectorOp;- use super::super::selector::SelectorProgramBuilder;- use super::super::selector::TagTest;- use super::*;-- const TAG_DIV: StyleAtomID = StyleAtomID(1);- const TAG_SPAN: StyleAtomID = StyleAtomID(2);- const CLASS_THEME: StyleAtomID = StyleAtomID(10);- const CLASS_ITEM: StyleAtomID = StyleAtomID(11);- const CLASS_MISSING: StyleAtomID = StyleAtomID(12);- const ID_HEADER: StyleAtomID = StyleAtomID(20);-- /// `div.theme > [ div.item, span#header, div.item ]`- struct Document {- tree: StyleNodeTree,- facts: StyleNodeFacts,- programs: SelectorPrograms,- program: StyleSheetProgram,- nodes: Vec<StyleNodeID>,- counters: Counters,- }-- impl Document {- fn new() -> Self {- let mut tree = StyleNodeTree::new();- let nodes: Vec<StyleNodeID> = (0..4).map(|_| tree.allocate_element()).collect();- tree.set_first_element_child(nodes[0], Some(nodes[1]));- for index in 1..4 {- tree.set_parent(nodes[index], Some(nodes[0]));- tree.set_next_element_sibling(nodes[index], nodes.get(index + 1).copied());- tree.set_previous_element_sibling(nodes[index], (index > 1).then(|| nodes[index - 1]));- }-- let mut facts = StyleNodeFacts::new();- facts.push_row(- nodes[0],- TAG_DIV,- StyleAtomID::NONE,- StateSet::default(),- &[CLASS_THEME],- &[],- );- facts.push_row(- nodes[1],- TAG_DIV,- StyleAtomID::NONE,- StateSet::default(),- &[CLASS_ITEM],- &[],- );- facts.push_row(nodes[2], TAG_SPAN, ID_HEADER, StateSet::default(), &[], &[]);- facts.push_row(- nodes[3],- TAG_DIV,- StyleAtomID::NONE,- StateSet::default(),- &[CLASS_ITEM],- &[],- );-- let mut program = StyleSheetProgram::new();- let sheet = program.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- program.attach_sheet(sheet, TreeScopeID::DOCUMENT);-- Self {- tree,- facts,- programs: SelectorPrograms::new(),- program,- nodes,- counters: Counters::new(),- }- }-- fn sheet(&self) -> super::super::program::SheetID {- super::super::program::SheetID(0)- }-- /// Attach a style rule whose selector program is built by `build`.- fn add_rule(&mut self, build: impl FnOnce(&mut SelectorProgramBuilder)) -> RuleID {- let mut builder = SelectorProgramBuilder::new();- build(&mut builder);- let compiled = self.programs.add(builder.finish());- let sheet = self.sheet();- let rule = self.program.append_rule(sheet, None, RuleKind::Style);- let mut version = self.program.rule_version(rule);- version.selector_program = Some(compiled);- self.program.replace_rule_version(rule, version);- rule- }-- fn run(&mut self) -> RuleMatches {- let dispatch = build_scope_dispatch(&self.program, &self.programs, TreeScopeID::DOCUMENT);- let ancestor_requirements = AncestorRequirements::build(&self.tree, &self.facts, &dispatch);- let interpreter = BatchMatcher::new(&self.tree, &self.facts, &dispatch, &self.programs, &self.program)- .with_ancestor_requirements(&ancestor_requirements);- let mut matches = RuleMatches::new();- interpreter- .match_subtree(self.nodes[0], &mut matches, &self.counters)- .expect("the batch covers the whole document");-- matches- }-- fn matched_nodes(&self, matches: &RuleMatches, rule: RuleID) -> Vec<usize> {- matches- .as_slice()- .iter()- .filter(|entry| entry.rule == rule)- .map(|entry| self.nodes.iter().position(|node| *node == entry.node).unwrap())- .collect()- }- }-- fn class_rule(class: StyleAtomID) -> impl FnOnce(&mut SelectorProgramBuilder) {- move |builder| {- let feature = builder.push_feature(FeatureTest::Class(class));- builder.push_entry(feature);- }- }-- #[test]- fn a_cold_pass_finds_exactly_the_matching_rules() {- let mut document = Document::new();- let item = document.add_rule(class_rule(CLASS_ITEM));- let header = document.add_rule(|builder| {- let feature = builder.push_feature(FeatureTest::Id(ID_HEADER));- builder.push_entry(feature);- });- let descendant = document.add_rule(|builder| {- let theme = builder.push_feature(FeatureTest::Class(CLASS_THEME));- let ancestor = builder.push(SelectorOp::Ancestor(theme));- let span = builder.push_feature(FeatureTest::TagName(TagTest::exact(TAG_SPAN)));- let root = builder.push_compound(&[span, ancestor]);- builder.push_entry(root);- });-- let matches = document.run();- assert_eq!(document.matched_nodes(&matches, item), vec![1, 3]);- assert_eq!(document.matched_nodes(&matches, header), vec![2]);- assert_eq!(document.matched_nodes(&matches, descendant), vec![2]);- }-- #[test]- fn shared_selector_entries_join_every_rule_after_prefix_matching() {- let mut document = Document::new();- let mut builder = SelectorProgramBuilder::new();- class_rule(CLASS_ITEM)(&mut builder);- let selector_program = document.programs.add(builder.finish());- let mut rules = Vec::new();- for _ in 0..2 {- let rule = document.program.append_rule(document.sheet(), None, RuleKind::Style);- let mut version = document.program.rule_version(rule);- version.selector_program = Some(selector_program);- document.program.replace_rule_version(rule, version);- rules.push(rule);- }-- let matches = document.run();- assert_eq!(document.matched_nodes(&matches, rules[0]), vec![1, 3]);- assert_eq!(document.matched_nodes(&matches, rules[1]), vec![1, 3]);- assert_eq!(document.counters.get(Counter::CandidateChecks), 0);- }-- #[test]- fn shared_prefix_identity_emits_only_rows_admitted_to_the_automaton() {- let mut document = Document::new();- let user_agent_sheet = document- .program- .add_sheet(StyleSheetObjectID(2), CascadeOrigin::UserAgent);- document.program.attach_sheet(user_agent_sheet, TreeScopeID::DOCUMENT);-- let mut builder = SelectorProgramBuilder::new();- let any = builder.push_feature(FeatureTest::AnyElement);- let first_of_type = builder.push(SelectorOp::NthPosition(NthPosition {- step: 0,- offset: 1,- from_end: false,- of_selector: None,- of_type: true,- }));- let root = builder.push_compound(&[any, first_of_type]);- builder.push_entry(root);- let selector_program = document.programs.add(builder.finish());-- let author_sheet = document.sheet();- let mut add_rule = |sheet| {- let rule = document.program.append_rule(sheet, None, RuleKind::Style);- let mut version = document.program.rule_version(rule);- version.selector_program = Some(selector_program);- document.program.replace_rule_version(rule, version);- rule- };- let user_agent_rule = add_rule(user_agent_sheet);- let author_rule = add_rule(author_sheet);-- let matches = document.run();- assert_eq!(document.matched_nodes(&matches, user_agent_rule), vec![0, 1, 2]);- assert_eq!(document.matched_nodes(&matches, author_rule), vec![0, 1, 2]);-- let dispatch = build_scope_dispatch(&document.program, &document.programs, TreeScopeID::DOCUMENT);- let entry = document.programs.entry_id(selector_program, 0);- let rows: Vec<_> = dispatch.entries_for_identity(entry).collect();- assert_eq!(rows.len(), 2);- assert_eq!(rows.iter().filter(|row| row.prefix_matched).count(), 1);-- let mut changes = SelectorTruthChanges::default();- record_match_set_difference(- &mut changes,- true,- document.nodes[0],- &[],- &[entry],- &dispatch,- &document.program,- );- let mut changed_rules: Vec<_> = changes.deltas.as_slice().iter().map(|delta| delta.rule).collect();- changed_rules.sort_unstable();- assert_eq!(changed_rules, vec![user_agent_rule, author_rule]);- }-- #[test]- fn prefix_states_keep_descendants_but_expire_children() {- let mut document = Document::new();- document.tree.set_next_element_sibling(document.nodes[1], None);- document.tree.set_parent(document.nodes[2], Some(document.nodes[1]));- document- .tree- .set_first_element_child(document.nodes[1], Some(document.nodes[2]));- document.tree.set_next_element_sibling(document.nodes[2], None);- document.tree.set_previous_element_sibling(document.nodes[2], None);- document.tree.set_parent(document.nodes[3], Some(document.nodes[2]));- document- .tree- .set_first_element_child(document.nodes[2], Some(document.nodes[3]));-- let child = document.add_rule(|builder| {- let theme = builder.push_feature(FeatureTest::Class(CLASS_THEME));- let parent = builder.push(SelectorOp::Parent(theme));- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let root = builder.push_compound(&[item, parent]);- builder.push_entry(root);- });- let descendant = document.add_rule(|builder| {- let theme = builder.push_feature(FeatureTest::Class(CLASS_THEME));- let ancestor = builder.push(SelectorOp::Ancestor(theme));- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let root = builder.push_compound(&[item, ancestor]);- builder.push_entry(root);- });-- let matches = document.run();- assert_eq!(document.matched_nodes(&matches, child), vec![1]);- assert_eq!(document.matched_nodes(&matches, descendant), vec![1, 3]);- assert_eq!(document.counters.get(Counter::CandidateChecks), 0);- }-- #[test]- fn prefix_states_stop_at_a_shadow_root() {- let mut document = Document::new();- let rule = document.add_rule(|builder| {- let any = builder.push_feature(FeatureTest::AnyElement);- let parent = builder.push(SelectorOp::Parent(any));- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let root = builder.push_compound(&[item, parent]);- builder.push_entry(root);- });-- let dispatch = build_scope_dispatch(&document.program, &document.programs, TreeScopeID::DOCUMENT);- let interpreter = BatchMatcher::new(- &document.tree,- &document.facts,- &dispatch,- &document.programs,- &document.program,- )- .in_shadow_tree(document.nodes[0]);- let mut matches = RuleMatches::new();- interpreter- .match_node(document.nodes[1], &mut matches, &document.counters)- .expect("the batch covers the shadow child");- assert!(document.matched_nodes(&matches, rule).is_empty());- }-- #[test]- fn non_prefix_entries_stay_in_the_exact_fallback_dispatch() {- let mut document = Document::new();- // An of-selector positional answer evaluates an arbitrary program against every- // sibling, so the entry stays on the exact match evaluator. Sibling combinators no- // longer qualify: they register in the unified prefix automaton like the down-axis- // chains. Node 3 is the second `.item` among its siblings: the span between the items- // counts only in the plain child sequence.- let rule = document.add_rule(|builder| {- let counted = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let second_item = builder.push(SelectorOp::NthPosition(NthPosition {- step: 0,- offset: 2,- from_end: false,- of_selector: Some(counted),- of_type: false,- }));- let root = builder.push_compound(&[item, second_item]);- builder.push_entry(root);- });-- let matches = document.run();- assert_eq!(document.matched_nodes(&matches, rule), vec![3]);- assert_ne!(document.counters.get(Counter::CandidateChecks), 0);- }-- #[test]- fn plain_positional_entries_match_through_the_prefix_automaton() {- let mut document = Document::new();- // A plain an+b answer is a pure function of tree position, carried as a positional- // truth bit in every transition key, so the entry is admitted and no candidate is ever- // checked by the exact evaluator.- let rule = document.add_rule(|builder| {- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let third = builder.push(SelectorOp::NthPosition(NthPosition {- step: 0,- offset: 3,- from_end: false,- of_selector: None,- of_type: false,- }));- let root = builder.push_compound(&[item, third]);- builder.push_entry(root);- });-- let matches = document.run();- assert_eq!(document.matched_nodes(&matches, rule), vec![3]);- assert_eq!(document.counters.get(Counter::CandidateChecks), 0);- }-- #[test]- fn sibling_entries_match_through_the_prefix_automaton() {- let mut document = Document::new();- let rule = document.add_rule(|builder| {- let header = builder.push_feature(FeatureTest::Id(ID_HEADER));- let previous = builder.push(SelectorOp::PreviousSibling(header));- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let root = builder.push_compound(&[item, previous]);- builder.push_entry(root);- });-- let matches = document.run();- assert_eq!(document.matched_nodes(&matches, rule), vec![3]);- assert_eq!(document.counters.get(Counter::CandidateChecks), 0);- }-- #[test]- fn equivalent_prefix_compounds_are_evaluated_once_per_node() {- let mut document = Document::new();- let first = document.add_rule(class_rule(CLASS_ITEM));- let second = document.add_rule(class_rule(CLASS_ITEM));-- let matches = document.run();- assert_eq!(document.matched_nodes(&matches, first), vec![1, 3]);- assert_eq!(document.matched_nodes(&matches, second), vec![1, 3]);- assert_eq!(document.counters.get(Counter::PrefixCompoundsEvaluated), 1);- }-- #[test]- fn prefix_transitions_probe_parent_steps_by_local_dispatch_key() {- let mut document = Document::new();- let mut item_rule = None;- for target in 100..164 {- let target = if target == 100 { CLASS_ITEM } else { StyleAtomID(target) };- let rule = document.add_rule(|builder| {- let theme = builder.push_feature(FeatureTest::Class(CLASS_THEME));- let ancestor = builder.push(SelectorOp::Ancestor(theme));- let target = builder.push_feature(FeatureTest::Class(target));- let root = builder.push_compound(&[target, ancestor]);- builder.push_entry(root);- });- if target == CLASS_ITEM {- item_rule = Some(rule);- }- }-- let matches = document.run();- assert_eq!(document.matched_nodes(&matches, item_rule.unwrap()), vec![1, 3]);- }-- #[test]- fn prefix_continuations_are_shared_independently_of_local_matches() {- let mut document = Document::new();- let item = document.add_rule(class_rule(CLASS_ITEM));- let header = document.add_rule(|builder| {- let feature = builder.push_feature(FeatureTest::Id(ID_HEADER));- builder.push_entry(feature);- });-- let matches = document.run();- assert_eq!(document.matched_nodes(&matches, item), vec![1, 3]);- assert_eq!(document.matched_nodes(&matches, header), vec![2]);- }-- #[test]- fn prefix_cache_hits_preserve_local_matches() {- let mut document = Document::new();- let item = document.add_rule(class_rule(CLASS_ITEM));- let dispatch = build_scope_dispatch(&document.program, &document.programs, TreeScopeID::DOCUMENT);- let interpreter = BatchMatcher::new(- &document.tree,- &document.facts,- &dispatch,- &document.programs,- &document.program,- );- let mut dispatch_workspace = DispatchCandidateWorkspace::default();- let mut prefix_states = PrefixStates::new();- let mut prefix_context = PrefixTransitionContext::new(&mut prefix_states, &document.facts);- let mut matches = RuleMatches::new();- for _ in 0..2 {- interpreter- .match_node_collecting_requests(- document.nodes[1],- &mut matches,- &document.counters,- BatchMatchState {- match_workspace: None,- witness_effects: None,- dispatch_workspace: &mut dispatch_workspace,- requests: None,- completed: None,- prefix_states: Some((&mut prefix_states, &mut prefix_context)),- deferred_prefix_matches: None,- },- )- .result- .expect("the node has complete facts");- }- assert_eq!(document.matched_nodes(&matches, item), vec![1, 1]);- }-- #[test]- fn matches_are_sorted_by_style_node_and_addressable_per_node() {- let mut document = Document::new();- document.add_rule(class_rule(CLASS_ITEM));- document.add_rule(class_rule(CLASS_THEME));- let universal = document.add_rule(|builder| {- let any = builder.push_feature(FeatureTest::AnyElement);- builder.push_entry(any);- });-- let matches = document.run();- let nodes: Vec<StyleNodeID> = matches.as_slice().iter().map(|entry| entry.node).collect();- assert!(nodes.windows(2).all(|pair| pair[0] <= pair[1]));-- let for_second = matches.matches_for(document.nodes[1]);- assert_eq!(for_second.len(), 2);- assert!(for_second.iter().any(|entry| entry.rule == universal));- assert_eq!(matches.matches_for(document.nodes[2]).len(), 1);- }-- #[test]- fn a_candidate_only_considers_rules_its_own_features_reach() {- let mut document = Document::new();- for class in 100..200_u32 {- document.add_rule(class_rule(StyleAtomID(class)));- }- document.add_rule(class_rule(CLASS_ITEM));-- let matches = document.run();- assert_eq!(matches.len(), 2);- // Four nodes, and only the ones carrying .item reach a bucket with anything in it.- assert!(- document.counters.get(Counter::CandidateChecks) < 10,- "a hundred unrelated rules must not be checked per candidate: {}",- document.counters.get(Counter::CandidateChecks)- );- }-- #[test]- fn a_shared_ancestor_summary_is_built_once_and_released() {- let mut document = Document::new();- document.add_rule(|builder| {- let theme = builder.push_feature(FeatureTest::Class(CLASS_THEME));- let ancestor = builder.push(SelectorOp::Ancestor(theme));- let any = builder.push_feature(FeatureTest::AnyElement);- let root = builder.push_compound(&[any, ancestor]);- builder.push_entry(root);- });- let dispatch = build_scope_dispatch(&document.program, &document.programs, TreeScopeID::DOCUMENT);-- let mut cache = AncestorRequirementsCache::default();- cache.prepare(&document.tree, &document.facts, &dispatch, None);-- cache.prepare(&document.tree, &document.facts, &dispatch, None);-- cache.release();- }-- #[test]- fn prepared_sparse_ancestor_requirements_match_the_exact_batch() {- let mut document = Document::new();- document.add_rule(|builder| {- let theme = builder.push_feature(FeatureTest::Class(CLASS_THEME));- let ancestor = builder.push(SelectorOp::Ancestor(theme));- let any = builder.push_feature(FeatureTest::AnyElement);- let root = builder.push_compound(&[any, ancestor]);- builder.push_entry(root);- });- let dispatch = build_scope_dispatch(&document.program, &document.programs, TreeScopeID::DOCUMENT);- let nodes = [document.nodes[2], document.nodes[1]];- let requirements = AncestorRequirements::build_for_nodes(&document.tree, &document.facts, &dispatch, &nodes);- let mut expected = RuleMatches::new();- let mut actual = RuleMatches::new();- for node in nodes {- BatchMatcher::new(- &document.tree,- &document.facts,- &dispatch,- &document.programs,- &document.program,- )- .match_node(node, &mut expected, &document.counters)- .unwrap();- BatchMatcher::new(- &document.tree,- &document.facts,- &dispatch,- &document.programs,- &document.program,- )- .with_ancestor_requirements(&requirements)- .match_node(node, &mut actual, &document.counters)- .unwrap();- }- assert!(!actual.is_empty());- assert_eq!(actual.as_slice(), expected.as_slice());- }-- #[test]- fn a_missing_required_ancestor_rejects_before_selector_evaluation() {- let mut document = Document::new();- let rule = document.add_rule(|builder| {- let missing = builder.push_feature(FeatureTest::Class(CLASS_MISSING));- let ancestor = builder.push(SelectorOp::Ancestor(missing));- let span = builder.push_feature(FeatureTest::TagName(TagTest::exact(TAG_SPAN)));- let root = builder.push_compound(&[span, ancestor]);- builder.push_entry(root);- });-- let matches = document.run();- assert!(document.matched_nodes(&matches, rule).is_empty());- assert_eq!(document.counters.get(Counter::CandidateChecks), 0);- assert_eq!(document.counters.get(Counter::CombinatorSteps), 0);- }-- #[test]- fn a_required_ancestor_is_found_through_a_parent_compound() {- let mut document = Document::new();- let rule = document.add_rule(|builder| {- let missing = builder.push_feature(FeatureTest::Class(CLASS_MISSING));- let ancestor = builder.push(SelectorOp::Ancestor(missing));- let theme = builder.push_feature(FeatureTest::Class(CLASS_THEME));- let parent_compound = builder.push_compound(&[theme, ancestor]);- let parent = builder.push(SelectorOp::Parent(parent_compound));- let span = builder.push_feature(FeatureTest::TagName(TagTest::exact(TAG_SPAN)));- let root = builder.push_compound(&[span, parent]);- builder.push_entry(root);- });-- let matches = document.run();- assert!(document.matched_nodes(&matches, rule).is_empty());- assert_eq!(document.counters.get(Counter::CandidateChecks), 0);- assert_eq!(document.counters.get(Counter::CombinatorSteps), 0);- }-- #[test]- fn a_selector_list_contributes_its_greatest_matching_specificity_once() {- let mut document = Document::new();- let rule = document.add_rule(|builder| {- let class = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let class_entry = builder.push_entry(class);- builder.set_entry_specificity(- class_entry,- Specificity {- classes: 1,- ..Specificity::default()- },- );- let tag = builder.push_feature(FeatureTest::TagName(TagTest::exact(TAG_DIV)));- let tag_entry = builder.push_entry(tag);- builder.set_entry_specificity(- tag_entry,- Specificity {- types: 1,- ..Specificity::default()- },- );- });-- let matches = document.run();- let for_item = matches.matches_for(document.nodes[1]);- assert_eq!(for_item.len(), 1, "one rule matching twice is still one match");- assert_eq!(for_item[0].rule, rule);- assert_eq!(- for_item[0].specificity,- Specificity {- classes: 1,- ..Specificity::default()- },- "the greater matching entry wins regardless of declaration order"- );- }-- #[test]- fn a_pseudo_element_rule_matches_the_originating_element_and_projects_onto_the_pseudo() {- use super::super::tree::PseudoElementKind;-- let mut document = Document::new();- let before = PseudoElementTarget::new(PseudoElementKind(1));- let rule = {- let mut builder = SelectorProgramBuilder::new();- let class = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- builder.push_entry_for_pseudo(class, Some(before));- let compiled = document.programs.add(builder.finish());- let sheet = document.sheet();- let rule = document.program.append_rule(sheet, None, RuleKind::Style);- let mut version = document.program.rule_version(rule);- version.selector_program = Some(compiled);- document.program.replace_rule_version(rule, version);- rule- };-- let matches = document.run();- assert_eq!(document.matched_nodes(&matches, rule), vec![1, 3]);- assert!(- matches- .as_slice()- .iter()- .all(|entry| entry.pseudo_element == Some(before)),- "the match names the originating element and carries the target"- );- }-- #[test]- fn a_rule_matching_an_element_and_its_pseudo_produces_two_results() {- use super::super::tree::PseudoElementKind;-- let mut document = Document::new();- let marker = PseudoElementTarget::new(PseudoElementKind(2));- let rule = {- let mut builder = SelectorProgramBuilder::new();- let class = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- builder.push_entry(class);- let same = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- builder.push_entry_for_pseudo(same, Some(marker));- let compiled = document.programs.add(builder.finish());- let sheet = document.sheet();- let rule = document.program.append_rule(sheet, None, RuleKind::Style);- let mut version = document.program.rule_version(rule);- version.selector_program = Some(compiled);- document.program.replace_rule_version(rule, version);- rule- };-- let matches = document.run();- let for_item = matches.matches_for(document.nodes[1]);- assert_eq!(for_item.len(), 2, "the element and its pseudo are separate results");- assert!(for_item.iter().any(|entry| entry.pseudo_element.is_none()));- assert!(for_item.iter().any(|entry| entry.pseudo_element == Some(marker)));- assert!(for_item.iter().all(|entry| entry.rule == rule));- }-- #[test]- fn a_pseudo_element_target_adds_a_type_component_to_specificity() {- use super::super::tree::PseudoElementKind;-- let mut builder = SelectorProgramBuilder::new();- let class = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let element_entry = builder.push_entry(class);- builder.set_entry_specificity(- element_entry,- Specificity {- classes: 1,- ..Specificity::default()- },- );- let same = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let pseudo_entry = builder.push_entry_for_pseudo(same, Some(PseudoElementTarget::new(PseudoElementKind(1))));- builder.set_entry_specificity(- pseudo_entry,- Specificity {- classes: 1,- types: 1,- ..Specificity::default()- },- );- let program = builder.finish();-- assert_eq!(program.entries()[0].specificity.types, 0);- assert_eq!(program.entries()[1].specificity.types, 1);- assert_eq!(program.entries()[1].specificity.classes, 1);- }-- #[test]- fn a_disabled_sheet_contributes_no_matches() {- let mut document = Document::new();- document.add_rule(class_rule(CLASS_ITEM));- assert_eq!(document.run().len(), 2);-- let sheet = document.sheet();- document.program.set_sheet_enabled(sheet, false);- assert!(document.run().is_empty());- }-- #[test]- fn a_detached_sheet_contributes_no_matches() {- let mut document = Document::new();- document.add_rule(class_rule(CLASS_ITEM));- assert_eq!(document.run().len(), 2);-- let sheet = document.sheet();- document.program.detach_sheet(sheet, TreeScopeID::DOCUMENT);- assert!(document.run().is_empty());- }-- #[test]- fn a_non_style_rule_is_not_bucketed_for_element_matching() {- let mut document = Document::new();- let sheet = document.sheet();- let keyframes = document.program.append_rule(sheet, None, RuleKind::Keyframes);- let mut builder = SelectorProgramBuilder::new();- let any = builder.push_feature(FeatureTest::AnyElement);- builder.push_entry(any);- let compiled = document.programs.add(builder.finish());- let mut version = document.program.rule_version(keyframes);- version.selector_program = Some(compiled);- document.program.replace_rule_version(keyframes, version);-- assert!(- document.run().is_empty(),- "a keyframes rule reaches animations, not elements"- );- }-- #[test]- fn an_uncovered_node_aborts_the_pass_without_publishing_partial_output() {- let mut document = Document::new();- document.add_rule(class_rule(CLASS_ITEM));- // Extend the tree past what the fact batch covers.- let extra = document.tree.allocate_element();- document.tree.set_parent(extra, Some(document.nodes[0]));- document.tree.set_next_element_sibling(document.nodes[3], Some(extra));- document- .tree- .set_previous_element_sibling(extra, Some(document.nodes[3]));-- let dispatch = build_scope_dispatch(&document.program, &document.programs, TreeScopeID::DOCUMENT);- let interpreter = BatchMatcher::new(- &document.tree,- &document.facts,- &dispatch,- &document.programs,- &document.program,- );- let mut matches = RuleMatches::new();- assert_eq!(- interpreter.match_subtree(document.nodes[0], &mut matches, &document.counters),- Err(Incomplete::MissingFacts(extra))- );- assert!(matches.is_empty(), "an aborted pass publishes nothing");- }-- #[test]- fn attribute_rules_reach_candidates_through_the_attribute_name() {- use super::super::selector::AttributeCase;- use super::super::selector::AttributeOperator;- use super::super::selector::AttributeTest;-- let mut document = Document::new();- // Give the header a data attribute.- let mut facts = StyleNodeFacts::new();- facts.push_row(- document.nodes[0],- TAG_DIV,- StyleAtomID::NONE,- StateSet::default(),- &[CLASS_THEME],- &[],- );- facts.push_row(- document.nodes[1],- TAG_DIV,- StyleAtomID::NONE,- StateSet::default(),- &[CLASS_ITEM],- &[],- );- facts.push_row(- document.nodes[2],- TAG_SPAN,- ID_HEADER,- StateSet::default(),- &[],- &[AttributeFact {- name: StyleAtomID(30),- value: StyleAtomID(31),- }],- );- facts.push_row(- document.nodes[3],- TAG_DIV,- StyleAtomID::NONE,- StateSet::default(),- &[CLASS_ITEM],- &[],- );- document.facts = facts;-- let rule = document.add_rule(|builder| {- let attribute = builder.push_feature(FeatureTest::Attribute(AttributeTest {- fold_in_namespace: StyleAtomID::NONE,- folded: StyleAtomID(30),- any_namespace: false,- name: StyleAtomID(30),- operator: AttributeOperator::Exact,- value_atom: StyleAtomID(31),- value_offset: 0,- value_length: 0,- case: AttributeCase::Sensitive,- }));- builder.push_entry(attribute);- });-- let matches = document.run();- assert_eq!(document.matched_nodes(&matches, rule), vec![2]);- }-}diff --git a/Libraries/LibWeb/Rust/src/css/style/compiler.rs b/Libraries/LibWeb/Rust/src/css/style/compiler.rsindex 97d32a64248..b5dd9331dac 100644--- a/Libraries/LibWeb/Rust/src/css/style/compiler.rs+++ b/Libraries/LibWeb/Rust/src/css/style/compiler.rs@@ -4,129 +4,13 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! Compiling parsed selectors into StyleEngine programs.-//!-//! The parser already produces a compiled selector for the matching engine, so this is a Rust-to--//! Rust translation into the logical IR: the same selector, expressed as constraints on its-//! subject rather than as a list of compounds to walk.-//!-//! Compilation markers are bookkeeping only: they feed counters and do not change matching or-//! routing. The emitted IR carries the behavior, whether that is an exact never-match, an operator-//! handled elsewhere in the IR, or a conservative shape for something not implemented here. The-//! marker names which of those happened so counter data does not confuse an exact result with a-//! widened one.-//!-//! Names cross as atoms. A parsed selector already carries the one-word interned identity of every-//! name it mentions, and that identity is what the atom table is keyed by, so compiling a selector-//! copies no strings. Only attribute *values* tested by a substring or token operator become-//! literals, because those are the tests an integer comparison cannot answer.+//! What the style engine models of selectors beside their components: which pseudo-classes are+//! boolean element state facts, and where an `@scope` with no `<scope-start>` roots.+use super::input_types::StateFact;use super::tree::StyleNodeID;-use crate::css::selector::AttributeCaseType;-use crate::css::selector::AttributeSelector;-use crate::css::selector::Combinator;-use crate::css::selector::CompiledSelector;-use crate::css::selector::CompoundSelector;-use crate::css::selector::Direction;-use crate::css::selector::NamespaceType;-use crate::css::selector::PseudoClassSelector;use crate::css::selector::PseudoClassType;-use crate::css::selector::PseudoElementSelector;-use crate::css::selector::PseudoElementType;-use crate::css::selector::PseudoElementValue;-use crate::css::selector::SimpleSelector;-use crate::css::selector::search_text_match_filter_of_pseudo_class;-use super::atoms::synthetic_text_atom_key;-use super::fnv::fnv1a64;-use super::index::StyleAtomID;-use super::relative_selector::RelativeAxis;-use super::relative_selector::RelativeQuery;-use super::selector::AtomSpace;-use super::selector::AttributeCase;-use super::selector::AttributeOperator;-use super::selector::AttributeTest;-use super::selector::EngineAtoms;-use super::selector::FeatureTest;-use super::selector::NamespaceTest;-use super::selector::NthPosition;-use super::selector::QueryAtoms;-use super::selector::SelectorNodeID;-use super::selector::SelectorOp;-use super::selector::SelectorProgram;-use super::selector::SelectorProgramBuilder;-use super::selector::TagTest;-use super::selector::ValueStateTestKind;-use super::transaction::StateFact;-use super::tree::PseudoElementKind;-use super::tree::PseudoElementTarget;--/// The counter category associated with a compilation marker.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub enum CompilationMarkerReason {- /// A pseudo-class whose parsed value cannot match.- PseudoClass,- /// A name with no interned identity, so it has no atom to compare against.- UninternedName,- /// A nesting or invalid selector, which has no meaning outside its parse context.- Malformed,- /// A combinator with known never-match behavior.- Combinator,- /// A pseudo-element value that cannot match.- PseudoElement,- /// A relative selector with a selector list or more than one axis. This is the specification's- /// *complex* relative selector: exact evaluation, no retained witness, and routing that widens- /// rather than naming one inverse axis. It is a handled shape, not an unhandled one.- ComplexRelative,-}--impl CompilationMarkerReason {- /// The counter this reason reports through.- #[must_use]- pub fn counter(self) -> Option<super::instrumentation::Counter> {- use super::instrumentation::Counter;- Some(match self {- Self::PseudoClass => Counter::UnsupportedPseudoClass,- Self::UninternedName => Counter::UnsupportedUninternedName,- Self::Malformed => Counter::UnsupportedMalformed,- Self::Combinator => Counter::UnsupportedCombinator,- Self::PseudoElement => Counter::UnsupportedPseudoElement,- Self::ComplexRelative => return None,- })- }-}--/// How the emitted IR handles a marked selector construct.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub enum CompilationMarker {- /// The construct is known to match nothing and the IR says so exactly.- KnownNeverMatches(CompilationMarkerReason),- /// Another IR operator evaluates the construct exactly.- HandledByOtherIR(CompilationMarkerReason),-}--impl CompilationMarker {- /// The reason-specific counter this marker reports through.- #[must_use]- pub fn counter(self) -> Option<super::instrumentation::Counter> {- match self {- Self::KnownNeverMatches(reason) | Self::HandledByOtherIR(reason) => reason.counter(),- }- }-}--/// The outcome of compiling one selector.-pub struct CompiledEntry {- pub entry: usize,- /// Bookkeeping for a construct whose treatment should remain visible in counters.- pub marker: Option<CompilationMarker>,-}--/// The `@scope` rules a selector is compiled inside, outermost first.-///-/// Scopes nest, and an element is in scope only when it is in every one of them, so `levels` says-/// how many of `roots` and `limits` each enclosing scope contributed: without the boundaries the-/// roots of two levels read as alternatives rather than as constraints of their own./// Where an `@scope` with no `<scope-start>` roots.////// The specification's answer is the parent element of the sheet's owner node, which is an element@@ -140,1399 +24,6 @@ pub enum ImplicitScopeRoot {ContainingTree,}-#[derive(Default)]-pub struct ScopeChain<'a> {- pub roots: &'a [&'a CompiledSelector],- pub limits: &'a [&'a CompiledSelector],- pub levels: &'a [(u32, u32)],- /// Where each level roots when it wrote no `<scope-start>`, one per level and `None` where the- /// level wrote one.- pub implicit_roots: &'a [Option<ImplicitScopeRoot>],-}--/// The `@namespace` declarations in scope for the selectors of one sheet.-///-/// A prefix means whatever its sheet says it means, and an unprefixed type or universal selector-/// means the sheet's default namespace where one is declared. Both are CSSOM state, so they are-/// resolved to atoms by the caller and looked up here.-#[derive(Default)]-pub struct NamespaceScope {- /// The sheet's default namespace, or `None` when it declared none - in which case an- /// unprefixed name constrains no namespace at all.- pub default: Option<StyleAtomID>,- /// Each declared prefix and the namespace it names.- pub by_prefix: Vec<(StyleAtomID, StyleAtomID)>,-}--impl NamespaceScope {- /// A declared namespace name, as a constraint. The empty string is the namespace an element in- /// no namespace has, so declaring it names exactly those.- #[must_use]- fn test_for_uri(uri: StyleAtomID) -> NamespaceTest {- match uri == StyleAtomID::NONE {- true => NamespaceTest::None,- false => NamespaceTest::Named(uri),- }- }-- /// The constraint a qualified name places on its subject's namespace, or an error for a prefix the sheet never- /// declared.- fn test_for(- &self,- namespace_type: NamespaceType,- prefix: Option<StyleAtomID>,- ) -> Result<Option<NamespaceTest>, UndeclaredPrefix> {- Ok(match namespace_type {- // `*|x` names every namespace, so it constrains nothing.- NamespaceType::Any => None,- // `|x` names the absence of one.- NamespaceType::None => Some(NamespaceTest::None),- NamespaceType::Default => self.default.map(Self::test_for_uri),- NamespaceType::Named => prefix- .and_then(|prefix| self.by_prefix.iter().find(|(declared, _)| *declared == prefix))- .map(|&(_, uri)| Self::test_for_uri(uri))- .ok_or(UndeclaredPrefix)?- .into(),- })- }-}--/// https://drafts.csswg.org/css-namespaces/#css-qnames-/// A qualified name with a prefix that has not been previously declared as a namespace prefix is invalid. The parser-/// rejects such a selector, so one that reaches the compiler anyway matches nothing rather than every namespace.-struct UndeclaredPrefix;--/// Compiles parsed selectors into one program, interning names through the document's atom table.-pub struct SelectorCompiler<'a, A: AtomSpace = EngineAtoms> {- builder: SelectorProgramBuilder<A>,- /// The document-local atom for a name, optionally qualified by a namespace. A qualified name is- /// a name of its own: `[ns|x]` names an attribute that `[x]` does not, and one element can- /// carry both.- intern: &'a mut dyn FnMut(usize, Option<StyleAtomID>) -> StyleAtomID,- /// Whether the document matches id and class selectors ASCII case-insensitively, which a- /// quirks-mode one does. Both a selector's name and an element's are keyed by their lowercase- /// folding there, so the two meet however either was written.- fold_id_and_class_name_case: bool,- /// The HTML namespace, when this is an HTML document, and none otherwise. A handful of attribute- /// names compare their values ASCII case-insensitively on an HTML element in an HTML document- /// and case-sensitively anywhere else, so the answer is a fact about the subject.- html_element_namespace: StyleAtomID,- /// The `@namespace` declarations of the sheet these selectors belong to.- namespaces: NamespaceScope,- /// Whether the selector being compiled reaches across a shadow boundary, where the sheet's- /// default namespace does not follow it.- selector_escapes_its_namespace: bool,- /// Whether a scoping root is bound where the selector being compiled sits. `:scope` names that- /// root rather than the root of the tree, and only the evaluation knows which element it is.- scope_root_is_bound: bool,- /// Whether the selector being compiled names `:scope`. A scoped selector that does not is- /// relative to the root and so cannot match it; one that does says where it means to match.- selector_names_the_scope: bool,- /// Whether the compound being compiled names the shadow host. A `:has()` in such a compound is- /// anchored on the host and reads the tree the host opens; see- /// `RelativeQuery::match_in_shadow_tree`. It is a property of the whole compound rather than of- /// the order its simple selectors were written in, so `:has(.x):host` says the same as- /// `:host:has(.x)`.- compound_names_the_host: bool,- /// Whether the current compound is the subject of a selector nested in a logical pseudo-class.- /// A sheet's default namespace does not constrain that subject unless it writes a type or- /// universal selector of its own.- logical_pseudo_subject: Option<*const CompoundSelector>,- /// Whether the `::search-text` selector being compiled is compiled for the current match's- /// pseudo-element kind, which a rule naming neither `:current` nor `:not(:current)` styles too.- compiles_for_current_search_text_match: bool,-}--impl<'a> SelectorCompiler<'a> {- #[must_use]- pub fn new(- intern: &'a mut dyn FnMut(usize, Option<StyleAtomID>) -> StyleAtomID,- fold_id_and_class_name_case: bool,- html_element_namespace: StyleAtomID,- namespaces: NamespaceScope,- ) -> Self {- Self::with_atoms(intern, fold_id_and_class_name_case, html_element_namespace, namespaces)- }-}--impl<'a> SelectorCompiler<'a, QueryAtoms> {- /// Compile the selectors of a DOM query, whose names `intern` keys by the query's own atoms.- ///- /// https://dom.spec.whatwg.org/#scope-match-a-selectors-string- /// A query is matched with a scoping root, which `:scope` names, and so does `&`, which has no parent rule in a- /// query. No `@namespace` is in scope, so a query can name no namespace prefix.- #[must_use]- pub fn for_query(- intern: &'a mut dyn FnMut(usize, Option<StyleAtomID>) -> StyleAtomID,- html_element_namespace: StyleAtomID,- ) -> Self {- let mut compiler = Self::with_atoms(intern, false, html_element_namespace, NamespaceScope::default());- compiler.scope_root_is_bound = true;- compiler- }-- /// Compile one selector of the query.- pub fn compile_for_query(&mut self, selector: &CompiledSelector) -> CompiledEntry {- let entry = self.compile(selector);- // https://dom.spec.whatwg.org/#scope-match-a-selectors-string- // NB: A selector query matches elements, never pseudo-elements. `::slotted()` is represented- // as an operator on its assigned element for style matching, so it needs this explicit- // query rejection rather than the entry's ordinary pseudo-element target check.- if selector.compound_selectors.iter().any(|compound| {- compound- .simple_selectors- .iter()- .any(|simple| matches!(simple, SimpleSelector::PseudoElement(_)))- }) {- let never = self.builder.push_never();- self.builder.set_entry_root(entry.entry, never);- }- entry- }-}--impl<'a, A: AtomSpace> SelectorCompiler<'a, A> {- fn with_atoms(- intern: &'a mut dyn FnMut(usize, Option<StyleAtomID>) -> StyleAtomID,- fold_id_and_class_name_case: bool,- html_element_namespace: StyleAtomID,- namespaces: NamespaceScope,- ) -> Self {- Self {- builder: SelectorProgramBuilder::default(),- intern,- fold_id_and_class_name_case,- html_element_namespace,- namespaces,- selector_escapes_its_namespace: false,- scope_root_is_bound: false,- selector_names_the_scope: false,- compound_names_the_host: false,- logical_pseudo_subject: None,- compiles_for_current_search_text_match: false,- }- }-- #[must_use]- pub fn finish(self) -> SelectorProgram<A> {- self.builder.finish()- }-- /// Compile one complex selector as a top-level entry of the program.- /// Compile one complex selector, conjoined with the scope its rule sits in.- ///- /// A scoped rule matches only inside its scope, so the scope's start selector is a constraint on- /// the subject like any other: the subject is that element or a descendant of it. Expressing it- /// that way is what makes a class change that moves an element in or out of a scope route -- /// otherwise the scope's selectors appear in no compiled entry and reach nothing.- ///- /// The scope's `to` bound is not expressed. It can only narrow which elements match, so leaving- /// it out keeps the entry a superset, which is the safe direction for invalidation and is what- /// the exact evaluator settles afterwards.- pub(super) fn compile_in_scope(&mut self, selector: &CompiledSelector, scope: &ScopeChain<'_>) -> CompiledEntry {- let (scope_roots, scope_limits, scope_levels) = (scope.roots, scope.limits, scope.levels);- let implicit_root_of = |level: usize| scope.implicit_roots.get(level).copied().flatten();- if scope_levels.is_empty()- && scope_roots.is_empty()- && scope_limits.is_empty()- && scope.implicit_roots.is_empty()- {- return self.compile(selector);- }- let mut marker = None;-- // Scopes nest, and an element is in scope only when it is in every one of them, so each- // enclosing scope is a constraint of its own. Within one scope the roots are alternatives.- // An empty level list means one scope holding everything, which is what a caller with a- // single `@scope` passes.- let single_level = [(0, scope_roots.len(), 0, scope_limits.len())];- let nested_levels;- let levels: &[(usize, usize, usize, usize)] = if scope_levels.is_empty() {- &single_level- } else {- let mut spans = Vec::with_capacity(scope_levels.len());- let mut root_start = 0usize;- let mut limit_start = 0usize;- for &(root_count, limit_count) in scope_levels {- let root_end = (root_start + root_count as usize).min(scope_roots.len());- let limit_end = (limit_start + limit_count as usize).min(scope_limits.len());- spans.push((root_start, root_end, limit_start, limit_end));- root_start = root_end;- limit_start = limit_end;- }- nested_levels = spans;- &nested_levels- };-- // https://drafts.csswg.org/css-cascade-6/#scoped-rules- // The rule is relative to *one* scoping root, which the evaluation binds: `:scope` names- // that element, a limit excludes relative to it, and proximity counts to it. So the scopes- // wrap what the rule wrote rather than conjoining constraints onto it, innermost first, and- // `:scope` anywhere inside compiles to the binding.- let outer_bound = std::mem::replace(&mut self.scope_root_is_bound, true);- let outer_names_the_scope = std::mem::replace(&mut self.selector_names_the_scope, false);- let mut entry = self.compile(selector);- let selector_names_the_scope = self.selector_names_the_scope;- self.scope_root_is_bound = outer_bound;- self.selector_names_the_scope = outer_names_the_scope;-- let mut inner = self.builder.entry_root(entry.entry);- let mut innermost_root = None;- let mut scope_selectors = Vec::new();- for (level, &(root_start, root_end, limit_start, limit_end)) in levels.iter().enumerate().rev() {- let innermost = level + 1 == levels.len();- scope_selectors.clear();- scope_selectors.reserve(root_end - root_start + 1);- if let Some(implicit) = implicit_root_of(level) {- scope_selectors.push(self.push_implicit_scope_root(implicit));- }- for root_selector in &scope_roots[root_start..root_end] {- let compounds = &root_selector.compound_selectors;- if compounds.is_empty() {- marker.get_or_insert(CompilationMarker::KnownNeverMatches(CompilationMarkerReason::Malformed));- continue;- }- // A `<scope-start>` is written outside the scope it opens, so `:scope` in one names- // the scope enclosing it - which is bound while this level's candidates are tested.- // The outermost level has none unless this compile is itself inside a scope.- let bound = std::mem::replace(&mut self.scope_root_is_bound, level > 0 || outer_bound);- scope_selectors.push(self.compile_chain(compounds, compounds.len() - 1, &mut marker));- self.scope_root_is_bound = bound;- }- // An explicit `<scope-start>` whose selectors all failed parent substitution matches- // no roots. An omitted start is represented by an implicit root above.- if scope_selectors.is_empty() {- marker.get_or_insert(CompilationMarker::KnownNeverMatches(CompilationMarkerReason::Malformed));- inner = self.builder.push_never();- break;- }- let root = self.builder.push_any_of(&scope_selectors);-- // `:scope` inside a `<scope-end>` names the root of the scope that end belongs to,- // which is this level's own.- scope_selectors.clear();- scope_selectors.reserve(limit_end - limit_start);- let bound = std::mem::replace(&mut self.scope_root_is_bound, true);- for limit_selector in &scope_limits[limit_start..limit_end] {- let compounds = &limit_selector.compound_selectors;- if compounds.is_empty() {- marker.get_or_insert(CompilationMarker::KnownNeverMatches(CompilationMarkerReason::Malformed));- continue;- }- scope_selectors.push(self.compile_chain(compounds, compounds.len() - 1, &mut marker));- }- self.scope_root_is_bound = bound;- let limit = (!scope_selectors.is_empty()).then(|| self.builder.push_any_of(&scope_selectors));-- // A scoped selector carries an implied `:scope ` prefix unless it names `:scope`, so- // the subject is a strict descendant of the innermost root. An enclosing scope is- // satisfied by the subject being anywhere inside it, its root included.- inner = self.builder.push(SelectorOp::InScope {- root,- limit,- inner,- names_the_scope: !innermost || selector_names_the_scope,- });- if innermost_root.is_none() {- innermost_root = Some(root);- }- }- self.builder.set_entry_root(entry.entry, inner);- if let Some(scope_root) = innermost_root {- // Proximity is measured to the nearest scoping root, which is the innermost.- self.builder.set_entry_scope_root(entry.entry, scope_root);- }-- if marker.is_some() && entry.marker.is_none() {- entry.marker = marker;- }- entry- }-- /// The node an `@scope` with no `<scope-start>` roots at.- ///- /// A named element is one identity comparison. A sheet with no owner node roots at the shadow- /// host of the tree it is asked in, or at that tree's root when it is not a shadow tree, which- /// is `:host` and `:root` answering for whichever holds.- fn push_implicit_scope_root(&mut self, implicit: ImplicitScopeRoot) -> SelectorNodeID {- match implicit {- ImplicitScopeRoot::Node(node) => self.builder.push_is_node(node),- ImplicitScopeRoot::ContainingTree => {- let anything = self.builder.push_feature(FeatureTest::AnyElement);- let host = self.builder.push(SelectorOp::Host(anything));- let root = self.builder.push(SelectorOp::Root);- self.builder.push_any_of(&[host, root])- }- }- }-- fn compile(&mut self, selector: &CompiledSelector) -> CompiledEntry {- // `::slotted()` and `::part()` name an element in another tree, which the sheet's default- // namespace says nothing about.- self.selector_escapes_its_namespace = selector.compound_selectors.iter().any(|compound| {- compound.simple_selectors.iter().any(|simple| {- matches!(simple, SimpleSelector::PseudoElement(pseudo_element)- if matches!(- pseudo_element.pseudo_element,- PseudoElementType::Slotted | PseudoElementType::Part- ))- })- });- let compounds = &selector.compound_selectors;- if compounds.is_empty() {- let never = self.builder.push_never();- let entry = self.builder.push_entry(never);- return CompiledEntry {- entry,- marker: Some(CompilationMarker::KnownNeverMatches(CompilationMarkerReason::Malformed)),- };- }-- let mut marker = None;- let root = self.compile_chain(compounds, compounds.len() - 1, &mut marker);- let pseudo_element = selector- .target_pseudo_element- .map(|kind| {- if self.compiles_for_current_search_text_match {- PseudoElementType::SearchTextCurrent- } else {- kind- }- })- .map(|kind| PseudoElementTarget::new(PseudoElementKind(kind as u16)));- let entry = self.builder.push_entry_for_pseudo(root, pseudo_element);- self.builder.set_entry_specificity(entry, selector.specificity());-- CompiledEntry { entry, marker }- }-- /// Compile compounds `0..=index` with the subject at `index`.- ///- /// A compound's combinator relates it to the compound on its left, so walking leftwards from- /// the subject turns each one into a constraint on that subject.- /// Whether this compound is the `::part()` half of a selector.- fn names_a_part(compound: &CompoundSelector) -> bool {- compound.simple_selectors.iter().any(|simple| {- matches!(simple, SimpleSelector::PseudoElement(pseudo_element)- if pseudo_element.pseudo_element == PseudoElementType::Part)- })- }-- /// The kind of the element-backed pseudo-element this compound names, when it also writes- /// something after it.- fn backed_pseudo_element_with_pseudo_classes(compound: &CompoundSelector) -> Option<u16> {- let Some(SimpleSelector::PseudoElement(pseudo_element)) = compound.simple_selectors.first() else {- return None;- };- let kind = pseudo_element.pseudo_element as u16;- let backed_kinds = u16::from(super::bridge::FIRST_ELEMENT_REFERENCE_PSEUDO_ELEMENT_KIND)- ..=u16::from(super::bridge::LAST_ELEMENT_REFERENCE_PSEUDO_ELEMENT_KIND);- (backed_kinds.contains(&kind) && compound.simple_selectors.len() > 1).then_some(kind)- }-- fn names_slotted(compound: &CompoundSelector) -> bool {- compound.simple_selectors.iter().any(|simple| {- matches!(simple, SimpleSelector::PseudoElement(pseudo_element)- if pseudo_element.pseudo_element == PseudoElementType::Slotted)- })- }-- fn compile_chain(- &mut self,- compounds: &[CompoundSelector],- index: usize,- marker: &mut Option<CompilationMarker>,- ) -> SelectorNodeID {- self.compile_chain_anchored(compounds, index, marker, None)- }-- fn compile_chain_with_subject(- &mut self,- compounds: &[CompoundSelector],- index: usize,- marker: &mut Option<CompilationMarker>,- subject: *const CompoundSelector,- ) -> SelectorNodeID {- let outer_subject = self.logical_pseudo_subject.replace(subject);- let result = self.compile_chain(compounds, index, marker);- self.logical_pseudo_subject = outer_subject;- result- }-- /// The same, with `leftmost` conjoined onto the compound the chain starts at.- ///- /// A relative selector uses this to say where its chain started, which the constraints on the- /// witness cannot say on their own.- fn compile_chain_anchored(- &mut self,- compounds: &[CompoundSelector],- index: usize,- marker: &mut Option<CompilationMarker>,- leftmost: Option<SelectorNodeID>,- ) -> SelectorNodeID {- // `X::part(p)` reaches the engine as two compounds joined by the pseudo-element combinator,- // and unlike every other pseudo-element the two sides describe different elements: `X` is the- // shadow host and `::part(p)` is an element inside the tree it hosts. Conjoining them would- // ask the part element to carry the host's own features, so the host is compiled first and- // becomes the guard it belongs inside.- if index > 0- && compounds[index].combinator == Combinator::PseudoElement- && Self::names_a_part(&compounds[index])- {- let host = self.compile_chain_anchored(compounds, index - 1, marker, leftmost);- return self.compile_compound_hosted_by(&compounds[index], Some(host), marker);- }-- // `X::slotted(y)` is the same shape the other way round: `X` describes the slot and- // `::slotted(y)` the element assigned to it, which is the subject. Conjoining them would ask- // the assigned element to be a slot.- if index > 0- && compounds[index].combinator == Combinator::PseudoElement- && Self::names_slotted(&compounds[index])- {- let slot = self.compile_chain_anchored(compounds, index - 1, marker, leftmost);- let compound = self.compile_compound(&compounds[index], marker);- let step = self.builder.push(SelectorOp::AssignedSlot(slot));- return self.builder.push_compound(&[compound, step]);- }-- // `X::file-selector-button:hover` is the same shape again: the pseudo-classes written after- // an element-backed pseudo-element describe the element in `X`'s shadow tree that backs it,- // not `X`. Conjoining them onto `X` would match `:hover` wherever `X` is hovered, including- // over the rest of its shadow tree, so they become a step to the backing element.- if (index == 0 || compounds[index].combinator == Combinator::PseudoElement)- && let Some(kind) = Self::backed_pseudo_element_with_pseudo_classes(&compounds[index])- {- let inner = self.compile_compound(&compounds[index], marker);- let step = self.builder.push(SelectorOp::BackingElement { kind, inner });- let host = match index {- 0 => leftmost,- _ => Some(self.compile_chain_anchored(compounds, index - 1, marker, leftmost)),- };- return match host {- Some(host) => self.builder.push_compound(&[host, step]),- None => step,- };- }-- let compound = self.compile_compound(&compounds[index], marker);- if index == 0 {- return match leftmost {- Some(guard) => self.builder.push_compound(&[compound, guard]),- None => compound,- };- }-- let left = self.compile_chain_anchored(compounds, index - 1, marker, leftmost);- let constraint = match compounds[index].combinator {- Combinator::Descendant => SelectorOp::Ancestor(left),- Combinator::ImmediateChild => SelectorOp::Parent(left),- Combinator::NextSibling => SelectorOp::PreviousSibling(left),- Combinator::SubsequentSibling => SelectorOp::PrecedingSibling(left),- // A pseudo-element combinator is not a tree step: it moves from an element to a- // pseudo-element that element originates. The entry already carries the target, and- // both sides constrain the same originating element, so the two compounds simply- // conjoin.- Combinator::PseudoElement => return self.builder.push_compound(&[compound, left]),- // No shipping engine implements column combinator matching, so it matches nothing- // until the table-column relation exists here too.- Combinator::Column => {- marker.get_or_insert(CompilationMarker::KnownNeverMatches(- CompilationMarkerReason::Combinator,- ));- return self.builder.push_never();- }- // A leftward combinator of None on a non-leftmost compound is a malformed shape the- // parser should not produce.- Combinator::None => {- marker.get_or_insert(CompilationMarker::KnownNeverMatches(CompilationMarkerReason::Malformed));- return self.builder.push_never();- }- };- let step = self.builder.push(constraint);- self.builder.push_compound(&[compound, step])- }-- pub(super) fn compile_in_scope_for_current_search_text_match(- &mut self,- selector: &CompiledSelector,- scope: &ScopeChain<'_>,- ) -> CompiledEntry {- self.compiles_for_current_search_text_match = true;- let entry = self.compile_in_scope(selector, scope);- self.compiles_for_current_search_text_match = false;- entry- }-- fn compile_compound(- &mut self,- compound: &CompoundSelector,- marker: &mut Option<CompilationMarker>,- ) -> SelectorNodeID {- self.compile_compound_hosted_by(compound, None, marker)- }-- /// Compile one compound. `host` is the node describing the shadow host of a `::part()` compound- /// whose host was written as a compound of its own; without one the host is whatever else the- /// compound says, which is the shape `X::part(p)` takes when it arrives unsplit.- fn compile_compound_hosted_by(- &mut self,- compound: &CompoundSelector,- host: Option<SelectorNodeID>,- marker: &mut Option<CompilationMarker>,- ) -> SelectorNodeID {- // `X::part(p)` is one compound describing two elements: `X` is the shadow host and `::part(p)`- // is an element inside the tree it hosts. The subject is the part element, so the rest of- // the compound becomes a step to the host rather than a conjunct on the same node.- let part = compound.simple_selectors.iter().find_map(|simple| match simple {- SimpleSelector::PseudoElement(pseudo_element)- if pseudo_element.pseudo_element == PseudoElementType::Part =>- {- Some(pseudo_element)- }- _ => None,- });-- // A pseudo-class in a `::part()` compound constrains the part element, not the host: in- // `X::part(p):focus-within` it is the part that has focus within it. Only pseudo-classes may- // follow `::part()`, so which element a simple selector belongs to is decided by kind - the- // parsed compound does not keep the pseudo-element in source order. Compiling them onto the- // host leaves the part element reachable only through the host, so a state change on the part- // itself routes to a subject that cannot carry it.- let mut operands: Vec<SelectorNodeID> = Vec::with_capacity(compound.simple_selectors.len());- let mut on_the_part: Vec<SelectorNodeID> = Vec::new();- // Whether this compound names the host has to be known before any `:has()` in it compiles,- // and it is a property of the compound as a whole, so it is answered by looking rather than- // by relying on the order the simple selectors happen to be compiled in. An inner compound- // does not inherit it: `:host :is(.a:has(.x))` anchors that query on the `.a`.- let compound_names_the_host = compound.simple_selectors.iter().any(|simple| {- matches!(- simple,- // FIXME: `:host-context()` names the host too, and a `:has()` beside one reads- // the hosted tree for the same reason. The parser has no pseudo-class for- // it yet - it arrives as an invalid simple selector - so there is nothing- // to test here until it does.- SimpleSelector::PseudoClass(pseudo_class)- if pseudo_class.pseudo_class == PseudoClassType::Host- )- });- let outer_names_the_host = std::mem::replace(&mut self.compound_names_the_host, compound_names_the_host);- for simple in &compound.simple_selectors {- if let Some(operand) = self.compile_simple(simple, marker) {- match part.is_some() && matches!(simple, SimpleSelector::PseudoClass(_)) {- true => on_the_part.push(operand),- false => operands.push(operand),- }- }- }- self.compound_names_the_host = outer_names_the_host;-- // A compound with no type or universal selector written has one implied, and a default- // namespace constrains that one as well: in a sheet declaring one, `:link` names a link in- // that namespace rather than a link anywhere.- if let Some(default) = self.implied_default_namespace(compound, compound_names_the_host) {- operands.push(self.builder.push_feature(FeatureTest::Namespace(default)));- }-- if let Some(part) = part {- if let Some(written_host) = host {- operands.push(written_host);- }- let host = match operands.is_empty() {- true => self.builder.push_feature(FeatureTest::AnyElement),- false => self.builder.push_compound(&operands),- };- // The names go under the host op rather than beside it, so that one level of- // `exportparts` forwarding has to answer for both halves at once.- operands.clear();- for identity in &part.identifier_identities {- let atom = (self.intern)(identity.raw(), None);- operands.push(self.builder.push(SelectorOp::Part(atom)));- }- if operands.is_empty() {- marker.get_or_insert(CompilationMarker::KnownNeverMatches(- CompilationMarkerReason::PseudoElement,- ));- }- let parts = self.builder.push_compound(&operands);- operands.clear();- operands.push(self.builder.push(SelectorOp::ExposedToHost { host, parts }));- operands.extend(on_the_part);- return self.builder.push_compound(&operands);- }-- if operands.is_empty() {- return self.builder.push_feature(FeatureTest::AnyElement);- }- self.builder.push_compound(&operands)- }-- /// The identity an id or class selector is keyed by, which is its lowercase folding where the- /// document matches those selectors case-insensitively.- fn name_identity(&self, name: &crate::css::selector::NameSelector) -> Option<usize> {- if self.fold_id_and_class_name_case {- name.interned_lowercase_name_identity()- } else {- name.interned_name_identity()- }- }-- fn compile_simple(- &mut self,- simple: &SimpleSelector,- marker: &mut Option<CompilationMarker>,- ) -> Option<SelectorNodeID> {- match simple {- // A qualified name constrains two things: the namespace and the name. `*` constrains- // only the first, and only when its sheet gave it one to constrain.- SimpleSelector::Universal(name) => Some(match self.namespace_test(name) {- Ok(Some(test)) => self.builder.push_feature(FeatureTest::Namespace(test)),- Ok(None) if self.compound_names_the_host => self.builder.push_never(),- Ok(None) => self.builder.push_feature(FeatureTest::AnyElement),- Err(UndeclaredPrefix) => {- marker.get_or_insert(CompilationMarker::KnownNeverMatches(CompilationMarkerReason::Malformed));- self.builder.push_never()- }- }),- SimpleSelector::TagName(name) => {- // Tag names are compared against the element's own local name, which preserves- // case. An HTML element in an HTML document is compared with the lowercase form, so a- // selector written `DIV` reaches `<div>` - but `foreignobject` must not reach an SVG- // `foreignObject`, because every other element is compared with the written form.- // One test carrying both forms covers that.- // A name the document never interned is one no element carries, so the test is- // unsatisfiable rather than absent. Leaving it out would let `div` match every- // element in a document holding no `div`.- let Some(written) = name.interned_name_identity() else {- marker.get_or_insert(CompilationMarker::KnownNeverMatches(- CompilationMarkerReason::UninternedName,- ));- return Some(self.builder.push_never());- };- let written_atom = (self.intern)(written, None);- let folded_atom = match name.interned_lowercase_name_identity() {- Some(folded) if folded != written => (self.intern)(folded, None),- _ => written_atom,- };- let tag = self.builder.push_feature(FeatureTest::TagName(TagTest {- written: written_atom,- folded: folded_atom,- fold_in_namespace: self.html_element_namespace,- }));- Some(match self.namespace_test(name) {- Ok(Some(test)) => {- let namespace = self.builder.push_feature(FeatureTest::Namespace(test));- self.builder.push_compound(&[tag, namespace])- }- Ok(None) => tag,- Err(UndeclaredPrefix) => {- marker.get_or_insert(CompilationMarker::KnownNeverMatches(CompilationMarkerReason::Malformed));- self.builder.push_never()- }- })- }- SimpleSelector::Id(name) => match self.name_identity(name) {- Some(raw) => {- let atom = (self.intern)(raw, None);- Some(self.builder.push_feature(FeatureTest::Id(atom)))- }- None => {- marker.get_or_insert(CompilationMarker::KnownNeverMatches(- CompilationMarkerReason::UninternedName,- ));- Some(self.builder.push_never())- }- },- SimpleSelector::Class(name) => match self.name_identity(name) {- Some(raw) => {- let atom = (self.intern)(raw, None);- Some(self.builder.push_feature(FeatureTest::Class(atom)))- }- None => {- marker.get_or_insert(CompilationMarker::KnownNeverMatches(- CompilationMarkerReason::UninternedName,- ));- Some(self.builder.push_never())- }- },- SimpleSelector::Attribute(attribute) => Some(self.compile_attribute(attribute, marker)),- SimpleSelector::PseudoClass(pseudo_class) => self.compile_pseudo_class(pseudo_class, marker),- SimpleSelector::PseudoElement(pseudo_element) => self.compile_pseudo_element(pseudo_element, marker),- // https://drafts.csswg.org/css-nesting/#nest-selector- // A `&` that reaches matching has not been substituted for its parent rule's selector,- // and then it behaves as `:scope`: the scoping root where there is one, and the root of- // the tree where there is not. Compiling it to nothing at all left the compound with no- // constraint, which matches every element in the document.- SimpleSelector::Nesting => Some(match self.scope_root_is_bound {- true => self.builder.push(SelectorOp::ScopeRootInstance),- false => self.builder.push(SelectorOp::Scope),- }),- // A simple selector nothing can satisfy makes its whole compound unsatisfiable. Compiling- // it to nothing left the compound with no constraint at all, which matches every element- // in the document rather than none of them.- SimpleSelector::Invalid(_) => {- marker.get_or_insert(CompilationMarker::KnownNeverMatches(CompilationMarkerReason::Malformed));- Some(self.builder.push_never())- }- }- }-- /// Compile a pseudo-element simple selector.- ///- /// Most of them constrain nothing here: the entry's target is taken from the selector itself,- /// and the compound describes the originating element. `::slotted()` is different. It is not a- /// target at all - it styles the assigned element, which is the subject - and its argument is a- /// real constraint on that element. Leaving it out made `::slotted(input:disabled)` compile to- /// a compound with nothing in it, so a change to what it tests reached no element and the rule- /// was never re-evaluated.- fn compile_pseudo_element(- &mut self,- pseudo_element: &PseudoElementSelector,- marker: &mut Option<CompilationMarker>,- ) -> Option<SelectorNodeID> {- if pseudo_element.pseudo_element != PseudoElementType::Slotted {- return None;- }- // `::slotted()` is the subject, so an argument that cannot be read leaves the compound with- // nothing in it, which is every element rather than none.- let PseudoElementValue::CompoundSelector(argument) = &pseudo_element.value else {- marker.get_or_insert(CompilationMarker::KnownNeverMatches(- CompilationMarkerReason::PseudoElement,- ));- return Some(self.builder.push_never());- };- let compounds = &argument.compound_selectors;- if compounds.is_empty() {- marker.get_or_insert(CompilationMarker::KnownNeverMatches(CompilationMarkerReason::Malformed));- return Some(self.builder.push_never());- }- let inner = self.compile_chain(compounds, compounds.len() - 1, marker);- Some(self.builder.push(SelectorOp::Slotted(inner)))- }-- /// The constraint the sheet's default namespace places on a compound that writes no name.- ///- /// Returns nothing when the compound names a type or universal selector of its own, since that- /// name carries the constraint already, and when the sheet declared no default.- fn implied_default_namespace(- &self,- compound: &CompoundSelector,- compound_names_the_host: bool,- ) -> Option<NamespaceTest> {- if self.selector_escapes_its_namespace- || compound_names_the_host- || self.logical_pseudo_subject == Some(compound as *const CompoundSelector)- {- return None;- }- let names_an_element = compound- .simple_selectors- .iter()- .any(|simple| matches!(simple, SimpleSelector::Universal(_) | SimpleSelector::TagName(_)));- match names_an_element {- true => None,- false => self.namespaces.default.map(NamespaceScope::test_for_uri),- }- }-- /// The namespace constraint a qualified name places, resolved through its sheet.- fn namespace_test(- &mut self,- name: &crate::css::selector::QualifiedName,- ) -> Result<Option<NamespaceTest>, UndeclaredPrefix> {- let prefix = match name.namespace_type {- NamespaceType::Named => Some((self.intern)(name.namespace.raw(), None)),- _ => None,- };- self.namespaces.test_for(name.namespace_type, prefix)- }-- /// Every attribute selector compiles to a test, including one nothing can satisfy: a compound- /// that drops a simple selector constrains less than the selector says, which for a compound- /// means matching more.- fn compile_attribute(- &mut self,- attribute: &AttributeSelector,- marker: &mut Option<CompilationMarker>,- ) -> SelectorNodeID {- let Some(raw) = attribute.qualified_name.interned_name_identity() else {- marker.get_or_insert(CompilationMarker::KnownNeverMatches(- CompilationMarkerReason::UninternedName,- ));- return self.builder.push_never();- };- // Each of the three forms an attribute publishes answers one of the three questions a- // selector can ask. `[ns|x]` tests the qualified name and reaches only that namespace;- // `[*|x]` tests the any-namespace name, which every attribute publishes; `[x]` and `|x`- // test the bare local name, which only an attribute in no namespace publishes.- let namespace = match attribute.qualified_name.namespace_type {- NamespaceType::Any => Some(StyleAtomID::NONE),- // https://drafts.csswg.org/css-namespaces/#css-qnames- // A default namespace applies to type and universal selectors and to nothing else, so- // an attribute selector written without a prefix names an attribute in no namespace- // however the sheet declared its default.- NamespaceType::Default | NamespaceType::None => None,- NamespaceType::Named => match self.namespace_test(&attribute.qualified_name) {- Ok(Some(NamespaceTest::Named(namespace))) => Some(namespace),- Ok(Some(NamespaceTest::None) | None) => None,- Err(UndeclaredPrefix) => {- marker.get_or_insert(CompilationMarker::KnownNeverMatches(CompilationMarkerReason::Malformed));- return self.builder.push_never();- }- },- };- let name = (self.intern)(raw, namespace);-- let operator = AttributeOperator::from(attribute.match_type);- let case = match attribute.case_type {- AttributeCaseType::Insensitive => AttributeCase::Insensitive,- AttributeCaseType::Sensitive => AttributeCase::Sensitive,- // https://html.spec.whatwg.org/multipage/semantics-other.html#case-sensitivity-of-selectors- // Some attribute names compare their values ASCII case-insensitively, but only for an- // HTML element in an HTML document, so the subject decides which rule applies.- AttributeCaseType::Default => {- let names_a_legacy_attribute =- matches!(- attribute.qualified_name.namespace_type,- NamespaceType::Default | NamespaceType::None- ) && crate::css::selector::is_ascii_case_insensitive_html_attribute(&attribute.qualified_name.name);- match names_a_legacy_attribute && !self.html_element_namespace.is_none() {- true => AttributeCase::InsensitiveForNamespace(self.html_element_namespace),- false => AttributeCase::Sensitive,- }- }- };- let (value_offset, value_length) = self.builder.push_literal(&attribute.value);-- // An exact case-sensitive test is an identity question, and the DOM publishes each attribute- // value under the same text key, so both sides can answer it by comparing two integers -- // and the dispatch can reject a rule whose value the element does not hold without- // evaluating anything. Other value tests read the literal for their exact comparison, and so- // does every test against storage that keeps no value atoms.- let value_atom = match (operator, case) {- (AttributeOperator::Presence, _) => StyleAtomID::NONE,- (AttributeOperator::Exact, AttributeCase::Sensitive) if A::KEYS_ATTRIBUTE_VALUES => {- match attribute.value_identity.optional_raw() {- Some(identity) => (self.intern)(identity, None),- None => self.intern_text(&attribute.value),- }- }- _ => StyleAtomID::NONE,- };-- // https://html.spec.whatwg.org/multipage/semantics-other.html#case-sensitivity-of-selectors- // An attribute name is matched ASCII case-insensitively against an HTML element in an HTML- // document and case-sensitively everywhere else, so `[aB]` reaches an HTML element carrying- // `ab` while `[viewbox]` must not reach an SVG element carrying `viewBox`. Both forms are- // carried in one test, and the dispatch keys on the folded one - the form a subject offers- // whichever way it wrote its own name.- let folded = match attribute.qualified_name.interned_lowercase_name_identity() {- Some(lowercase) if lowercase != raw => (self.intern)(lowercase, namespace),- _ => name,- };- let fold_in_namespace = match folded == name {- true => StyleAtomID::NONE,- false => self.html_element_namespace,- };- self.builder.push_feature(FeatureTest::Attribute(AttributeTest {- name,- any_namespace: attribute.qualified_name.namespace_type == NamespaceType::Any,- folded,- fold_in_namespace,- operator,- value_atom,- value_offset,- value_length,- case,- }))- }-- /// Compile one pseudo-class.- ///- /// The match is exhaustive over every pseudo-class the parser can produce. That is deliberate:- /// a pseudo-class with no mapping compiles to something the engine cannot route, and a selector- /// that cannot be routed cannot be invalidated. Adding a pseudo-class to the parser therefore- /// fails to compile here until it has been given a meaning.- fn compile_pseudo_class(- &mut self,- pseudo_class: &PseudoClassSelector,- marker: &mut Option<CompilationMarker>,- ) -> Option<SelectorNodeID> {- use PseudoClassType as Pc;-- // Boolean facts, which is most of them.- if let Some(fact) = state_fact_for(pseudo_class.pseudo_class) {- return Some(self.builder.push(SelectorOp::State(fact)));- }-- match pseudo_class.pseudo_class {- // Logical combinators.- Pc::Is | Pc::Where => {- // https://drafts.csswg.org/selectors/#matches- // Both are forgiving, so an argument list whose every selector is invalid parses to- // an empty one - and an empty list matches nothing. Compiling it to no constraint- // left the compound matching every element instead.- let Some(any_of) = self.compile_argument_list(pseudo_class, marker) else {- return Some(self.builder.push_never());- };- if pseudo_class.pseudo_class == Pc::Where {- return Some(self.builder.push(SelectorOp::Where(any_of)));- }- Some(any_of)- }- Pc::Current => None,- Pc::Not => {- if search_text_match_filter_of_pseudo_class(pseudo_class).is_some() {- return None;- }- let any_of = self.compile_argument_list(pseudo_class, marker)?;- Some(self.builder.push(SelectorOp::Not(any_of)))- }- Pc::Has => self.compile_has(pseudo_class, marker),-- // Structural position.- Pc::FirstChild => Some(self.push_nth(0, 1, false, None, false)),- Pc::LastChild => Some(self.push_nth(0, 1, true, None, false)),- Pc::FirstOfType => Some(self.push_nth(0, 1, false, None, true)),- Pc::LastOfType => Some(self.push_nth(0, 1, true, None, true)),- // Being the only child is being both the first and the last, but it is one- // pseudo-class and contributes the specificity of one. The second half is wrapped so- // that conjoining the two does not count it twice.- Pc::OnlyChild => {- let first = self.push_nth(0, 1, false, None, false);- let last = self.push_nth(0, 1, true, None, false);- let last = self.builder.push(SelectorOp::Where(last));- Some(self.builder.push_compound(&[first, last]))- }- Pc::OnlyOfType => {- let first = self.push_nth(0, 1, false, None, true);- let last = self.push_nth(0, 1, true, None, true);- let last = self.builder.push(SelectorOp::Where(last));- Some(self.builder.push_compound(&[first, last]))- }- Pc::NthChild | Pc::NthLastChild => {- let of_selector = self.compile_nth_of(pseudo_class, marker);- let from_end = pseudo_class.pseudo_class == Pc::NthLastChild;- Some(self.push_nth(- pseudo_class.an_plus_b_pattern.step_size,- pseudo_class.an_plus_b_pattern.offset,- from_end,- of_selector,- false,- ))- }- Pc::NthOfType | Pc::NthLastOfType => {- let from_end = pseudo_class.pseudo_class == Pc::NthLastOfType;- Some(self.push_nth(- pseudo_class.an_plus_b_pattern.step_size,- pseudo_class.an_plus_b_pattern.offset,- from_end,- None,- true,- ))- }-- // Structural facts about the subject's place in its tree.- Pc::Root => Some(self.builder.push(SelectorOp::Root)),- Pc::Empty => Some(self.builder.push(SelectorOp::Empty)),- Pc::Scope => {- self.selector_names_the_scope = true;- // Inside an `@scope`, `:scope` names that scope's root, which is one element the- // evaluation binds rather than anything the selector can say. Outside one it names- // the root of the tree.- Some(match self.scope_root_is_bound {- true => self.builder.push(SelectorOp::ScopeRootInstance),- false => self.builder.push(SelectorOp::Scope),- })- }-- // Shadow encapsulation. `:host` with an argument constrains the host itself.- Pc::Host => {- let inner = self- .compile_argument_list(pseudo_class, marker)- .unwrap_or_else(|| self.builder.push_feature(FeatureTest::AnyElement));- Some(self.builder.push(SelectorOp::Host(inner)))- }-- // States whose test carries a value rather than a boolean.- Pc::Dir => {- // The keyword is interned as its own text, so the DOM side names the same atom- // without either side agreeing on a numbering.- let Some(direction) = pseudo_class.direction else {- marker.get_or_insert(CompilationMarker::KnownNeverMatches(- CompilationMarkerReason::PseudoClass,- ));- return Some(self.builder.push_never());- };- let keyword: &[u16] = match direction {- Direction::LeftToRight => &[b'l' as u16, b't' as u16, b'r' as u16],- Direction::RightToLeft => &[b'r' as u16, b't' as u16, b'l' as u16],- Direction::Other => &[b'a' as u16, b'u' as u16, b't' as u16, b'o' as u16],- };- let value = match pseudo_class.identifier_lowercase_identity.optional_raw() {- Some(identity) => (self.intern)(identity, None),- None => self.intern_ascii_lowercase_text(keyword),- };- Some(self.builder.push(SelectorOp::ValueState {- kind: ValueStateTestKind::Directionality,- value,- }))- }- Pc::Lang => {- // A language list is a disjunction of one test per range.- //- // A range is not an atom: `:lang(en)` matches `en-GB`, and a range may hold- // wildcards, so no single interned value says which elements a rule names. Every- // `:lang()` compiles to one key, so a resolved language moving reaches every rule- // that asks about one - bounded to the elements whose tag actually moved.- match pseudo_class.languages.is_empty() {- true => Some(self.builder.push_never()),- false => {- let (first, count) = self- .builder- .push_language_ranges(pseudo_class.languages.iter().map(|range| &range.value));- Some(self.builder.push(SelectorOp::Language { first, count }))- }- }- }- Pc::State => {- // The parser gives every state it reads an identity, and a custom state is only ever set- // by name, so one without names nothing an element can be in.- let Some(identity) = pseudo_class.identifier_identity.optional_raw() else {- marker.get_or_insert(CompilationMarker::KnownNeverMatches(- CompilationMarkerReason::PseudoClass,- ));- return Some(self.builder.push_never());- };- Some(self.builder.push(SelectorOp::ValueState {- kind: ValueStateTestKind::CustomState,- value: (self.intern)(identity, None),- }))- }- Pc::Heading => {- // A written heading is one of six, but its computed level counts the heading offset- // its ancestors declare and is clamped at nine. Bare `:heading` is any level an- // element can have, which is all nine rather than the six it can be written as.- let mut mask: u16 = 0;- for level in &pseudo_class.levels {- if (1..=9).contains(level) {- mask |= 1 << (level - 1);- }- }- if pseudo_class.levels.is_empty() {- mask = 0b1_1111_1111;- }- Some(self.builder.push(SelectorOp::Heading(mask)))- }-- // Everything remaining is a boolean fact, which `state_fact_for` already returned. The- // arm exists so that adding a pseudo-class to the parser fails to compile here.- Pc::Active- | Pc::AnyLink- | Pc::Autofill- | Pc::Buffering- | Pc::Checked- | Pc::Default- | Pc::Defined- | Pc::Disabled- | Pc::Enabled- | Pc::EvenLessGoodValue- | Pc::Focus- | Pc::FocusVisible- | Pc::FocusWithin- | Pc::Fullscreen- | Pc::HighValue- | Pc::Hover- | Pc::Indeterminate- | Pc::Invalid- | Pc::Link- | Pc::LocalLink- | Pc::LowValue- | Pc::Modal- | Pc::Muted- | Pc::Open- | Pc::OptimalValue- | Pc::Optional- | Pc::Paused- | Pc::PictureInPicture- | Pc::PlaceholderShown- | Pc::Playing- | Pc::PopoverOpen- | Pc::ReadOnly- | Pc::ReadWrite- | Pc::Required- | Pc::Seeking- | Pc::Stalled- | Pc::SuboptimalValue- | Pc::Target- | Pc::Unchecked- | Pc::UserInvalid- | Pc::UserValid- | Pc::Valid- | Pc::Visited- | Pc::VolumeLocked => unreachable!("boolean pseudo-classes are handled as state facts"),- }- }-- /// Intern a name the parser did not give an interned identity for, by its text.- ///- /// Language tags and custom state names arrive as text rather than as fly strings, so they are- /// keyed by content. The atom space is shared, so a text-keyed name and an identity-keyed one- /// never collide: text keys are offset out of the identity range.- /// The atom key of a case-insensitive name, so a selector and the DOM agree on it.- ///- /// Language subtags and `:dir()` keywords are both ASCII case-insensitive and neither arrives- /// with an interned identity, so both sides derive the same key from the text itself.- #[must_use]- pub fn ascii_lowercase_text_key(text: &[u16]) -> usize {- let hash = fnv1a64(text.iter().map(|unit| match *unit {- 0x41..=0x5a => *unit + 0x20,- other => other,- }));- synthetic_text_atom_key(hash)- }-- fn intern_ascii_lowercase_text(&mut self, text: &[u16]) -> StyleAtomID {- (self.intern)(Self::ascii_lowercase_text_key(text), None)- }-- fn intern_text(&mut self, text: &[u16]) -> StyleAtomID {- let hash = fnv1a64(text.iter().copied());- // Text keys live above the pointer range so they cannot alias an interned identity.- (self.intern)(synthetic_text_atom_key(hash), None)- }-- fn compile_argument_list(- &mut self,- pseudo_class: &PseudoClassSelector,- marker: &mut Option<CompilationMarker>,- ) -> Option<SelectorNodeID> {- // A branch that targets a pseudo-element cannot match the originating element, so it- // contributes nothing to the disjunction. Compiling it anyway would leave a compound- // with no feature left in it, and a disjunction with one such branch distinguishes- // nothing at all: `:is(button, ::file-selector-button):hover` would then be reachable- // from a hover on any element whatsoever.- let mut arguments = pseudo_class- .argument_selector_list- .iter()- .filter(|argument| !argument.compound_selectors.is_empty() && argument.target_pseudo_element.is_none());- let first = arguments.next()?;- let compounds = &first.compound_selectors;- let subject_index = compounds.len() - 1;- let subject = &raw const compounds[subject_index];- let first = self.compile_chain_with_subject(compounds, subject_index, marker, subject);- let Some(second) = arguments.next() else {- return Some(first);- };- let mut branches = Vec::with_capacity(pseudo_class.argument_selector_list.len());- branches.push(first);- for argument in std::iter::once(second).chain(arguments) {- let compounds = &argument.compound_selectors;- let subject_index = compounds.len() - 1;- let subject = &raw const compounds[subject_index];- branches.push(self.compile_chain_with_subject(compounds, subject_index, marker, subject));- }- Some(self.builder.push_any_of(&branches))- }-- fn compile_nth_of(- &mut self,- pseudo_class: &PseudoClassSelector,- marker: &mut Option<CompilationMarker>,- ) -> Option<SelectorNodeID> {- if pseudo_class.argument_selector_list.is_empty() {- return None;- }- // An `of` list whose every selector names nothing counts an empty sequence, which is not- // the same as counting every sibling - which is what leaving the filter out would do.- Some(- self.compile_argument_list(pseudo_class, marker)- .unwrap_or_else(|| self.builder.push_never()),- )- }-- /// `:has()` compiles to a relative query per argument. A selector list holds when any one of its- /// arguments does, so the queries are combined into a disjunction and each keeps its own axis- /// and driving feature: a list is routed as precisely as each of its alternatives is.- fn compile_has(- &mut self,- pseudo_class: &PseudoClassSelector,- marker: &mut Option<CompilationMarker>,- ) -> Option<SelectorNodeID> {- // A `:has()` asking about nothing holds for nothing.- if pseudo_class.argument_selector_list.is_empty() {- return Some(self.builder.push_never());- }-- if let [argument] = pseudo_class.argument_selector_list.as_ref() {- return self.compile_has_argument(argument, marker);- }-- let mut alternatives = Vec::with_capacity(pseudo_class.argument_selector_list.len());- for argument in &pseudo_class.argument_selector_list {- // An alternative that cannot be compiled cannot be dropped: the query holds when any one- // of them does, so leaving one out would answer a narrower question than the rule asks.- alternatives.push(self.compile_has_argument(argument, marker)?);- }- Some(self.builder.push_any_of(&alternatives))- }-- /// One relative selector: an axis leading from the anchor to the elements that can witness it,- /// and a compound each of them is tested against.- fn compile_has_argument(- &mut self,- argument: &CompiledSelector,- marker: &mut Option<CompilationMarker>,- ) -> Option<SelectorNodeID> {- let compounds = &argument.compound_selectors;- if compounds.is_empty() {- return None;- }- let leading = match compounds[0].combinator {- Combinator::Descendant | Combinator::None => RelativeAxis::Descendant,- Combinator::ImmediateChild => RelativeAxis::Child,- Combinator::NextSibling => RelativeAxis::NextSibling,- Combinator::SubsequentSibling => RelativeAxis::FollowingSibling,- // Neither relates one element to another: a column combinator relates table cells- // through a relation the IR has no operator for, and a pseudo-element combinator does- // not lead out of the anchor at all. Nothing witnesses such a query.- Combinator::Column | Combinator::PseudoElement => {- marker.get_or_insert(CompilationMarker::KnownNeverMatches(- CompilationMarkerReason::Combinator,- ));- return Some(self.builder.push_never());- }- };-- // A single compound is the exact shape: one axis leads from the anchor to the elements that- // can witness the query, and each of them is tested on the spot.- let simple = compounds.len() == 1;-- // `:has(+ div .test)` names a `.test` under the anchor's next sibling, not a next sibling- // that is itself a `.test`. That holds whenever every step after the leading one goes- // downwards; a step that goes sideways again reaches a witness beside the axis element.- let witness_is_below_the_axis = !simple- && matches!(leading, RelativeAxis::NextSibling | RelativeAxis::FollowingSibling)- && compounds[1..].iter().all(|compound| {- matches!(- compound.combinator,- Combinator::Descendant | Combinator::None | Combinator::ImmediateChild- )- });- let axis = match simple {- true => leading,- // AD-HOC: With more compounds the witness is no longer on the leading axis. Every step- // after a downward one stays inside the anchor's subtree, whichever direction- // it goes, so the descendant axis covers the witnesses. A leading sibling- // combinator leaves the subtree and has no axis that covers it.- false => match leading {- RelativeAxis::Descendant | RelativeAxis::Child => RelativeAxis::Descendant,- // A leading sibling combinator leaves the anchor's subtree, and the steps after it- // go down from there, so the witness is under one of the siblings rather than- // being one. Unless one of them goes sideways again: `:has(+ .a + .b)` reaches a- // witness that is a following sibling of the anchor and under no sibling at all, so- // the axis has to cover them.- RelativeAxis::NextSibling | RelativeAxis::FollowingSibling if !witness_is_below_the_axis => {- RelativeAxis::FollowingSiblingSubtree- }- RelativeAxis::NextSibling => RelativeAxis::NextSiblingSubtree,- RelativeAxis::FollowingSibling => RelativeAxis::FollowingSiblingSubtree,- RelativeAxis::NextSiblingSubtree | RelativeAxis::FollowingSiblingSubtree => leading,- },- };-- // An in-shadow-tree query walks its axis from the shadow root, and every sibling axis leaves- // that tree: the host's siblings are in the light DOM, which the sheet this query was- // written in cannot see. `:host:has(+ .x)` therefore names nothing at all, which is worth- // saying at compile time so no such query is ever evaluated or routed.- if self.compound_names_the_host && !matches!(axis, RelativeAxis::Descendant | RelativeAxis::Child) {- return Some(self.builder.push_never());- }-- // The chain is compiled as constraints on the witness, which cannot say where the chain- // started: `:has(.a .b)` would accept a `.b` whose `.a` is above the anchor, and- // `:has(+ div > .test)` a `.test` under any `div` at all. Ending the chain at the anchor- // itself is what ties it back down. A single compound needs none of this: the axis reaches- // exactly the elements the leading combinator names.- let leftmost = match simple {- true => None,- false => {- let anchor = self.builder.push(SelectorOp::RelativeAnchorInstance);- Some(self.builder.push(match compounds[0].combinator {- Combinator::Descendant | Combinator::None => SelectorOp::Ancestor(anchor),- Combinator::ImmediateChild => SelectorOp::Parent(anchor),- Combinator::NextSibling => SelectorOp::PreviousSibling(anchor),- Combinator::SubsequentSibling => SelectorOp::PrecedingSibling(anchor),- Combinator::Column | Combinator::PseudoElement => unreachable!("rejected above"),- }))- }- };-- let compound = self.compile_chain_anchored(compounds, compounds.len() - 1, marker, leftmost);- if !simple {- // A query with more than one compound retains no witness, so it is answered by the- // direct evaluator rather than by a replacement search.- marker.get_or_insert(CompilationMarker::HandledByOtherIR(- CompilationMarkerReason::ComplexRelative,- ));- }-- let driving_feature = self.driving_feature_of(compound);- Some(self.builder.push_relative_exists(RelativeQuery {- axis,- compound,- driving_feature,- simple,- witness_is_below_the_axis,- match_in_shadow_tree: self.compound_names_the_host,- }))- }-- /// The positive indexable feature a witness search can drive from, if the compound has one.- fn driving_feature_of(&self, compound: SelectorNodeID) -> Option<super::index::LocalFeatureKey> {- let program = self.builder.program();- let feature_of = |test: FeatureTest| match test {- FeatureTest::Class(class) => Some(super::index::LocalFeatureKey::Class(class)),- FeatureTest::Id(_) => Some(super::index::LocalFeatureKey::Id),- FeatureTest::Attribute(attribute) => Some(super::index::LocalFeatureKey::Attribute(attribute.folded)),- FeatureTest::TagName(_) => Some(super::index::LocalFeatureKey::TagName),- // Neither enumerates a candidate set: every element is in some namespace, so driving a- // witness search from one would be driving it from the whole document.- FeatureTest::AnyElement | FeatureTest::Namespace(_) => None,- };- match program.node(compound) {- SelectorOp::Feature(test) => feature_of(test),- SelectorOp::And { first, count } => {- program- .operands(first, count)- .iter()- .find_map(|&operand| match program.node(operand) {- SelectorOp::Feature(test) => feature_of(test),- _ => None,- })- }- _ => None,- }- }-- fn push_nth(- &mut self,- step: i32,- offset: i32,- from_end: bool,- of_selector: Option<SelectorNodeID>,- of_type: bool,- ) -> SelectorNodeID {- self.builder.push(SelectorOp::NthPosition(NthPosition {- step,- offset,- from_end,- of_selector,- of_type,- }))- }-}-// The pseudo-classes StyleEngine models as boolean element state facts.//// Returning `None` means the pseudo-class is an operator instead, not that it lacks a state fact.diff --git a/Libraries/LibWeb/Rust/src/css/style/component_matching.rs b/Libraries/LibWeb/Rust/src/css/style/component_matching.rsnew file mode 100644index 00000000000..299791af03f--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/component_matching.rs@@ -0,0 +1,1859 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Matching selectors by walking their components: the evaluator the rule index, invalidation, the exact matcher and+//! the DOM queries match by.+//!+//! A selector matches compound by compound from its subject leftwards, reading each component where it is in its+//! sheet's arena. What the document decides (quirks folding, the HTML namespace) comes from the match context, and+//! the `@scope` levels of the rule from its bound scope chain.++use super::StyleAtomID;+use super::index::{DispatchKey, dispatch_bloom_bit};+use super::selector::attribute_value_matches;+use super::selector_evaluation::{ElementFeatures, SelectorEvaluator, SelectorSubject, SelectorTree, StructuralRead};+use crate::css::selector::{+ AttributeCaseType, AttributeMatchType, AttributeSelector, Combinator, CompoundRef, NamespaceType,+ PseudoClassSelector, PseudoClassType, Selector, SelectorListView, SimpleSelector,+};+use crate::css::selector_arena::{IdOrClass, Nesting};+use smallvec::SmallVec;++type Answer<S> = Result<bool, <S as SelectorSubject>::Incomplete>;++/// What matching a selector needs to know of the document it matches in.+#[derive(Clone, Copy)]+pub(crate) struct MatchContext<'a> {+ /// The HTML namespace in an HTML document, where tag and attribute names fold, and none elsewhere.+ pub(crate) html_namespace: StyleAtomID,+ /// Whether ids and classes compare ASCII case-insensitively, as in a quirks-mode document, whose elements+ /// publish their folded forms.+ pub(crate) fold_ids_and_classes: bool,+ /// The `@namespace` declarations of the sheet the selectors are in.+ pub(crate) namespaces: crate::css::selector_arena::SheetNamespaces<'a>,+ /// Whether the selector names an element in another tree, with `::slotted()` or `::part()`, where the sheet's+ /// default namespace does not follow it.+ pub(crate) escapes_its_namespace: bool,+ /// Whether the selector being matched is an argument of a logical pseudo-class, whose subject the default+ /// namespace does not constrain unless it writes a name of its own.+ pub(crate) logical_subject: bool,+}++/// How a walk along a selector's compounds ended: matched, or else which elements a walk further right has to try+/// again from.+#[derive(Clone, Copy, PartialEq, Eq)]+enum Walk {+ Matched,+ /// No element of the walk left of a later sibling of the element tried can match either.+ RestartFromLaterSibling,+ /// Only an element further down, below a descendant combinator, can match.+ RestartFromDescendant,+ /// No element the walk can still reach matches.+ NotMatchedGlobally,+}++/// A positional pseudo-class, as the components say it.+#[derive(Clone, Copy)]+struct Position<'a> {+ step: i32,+ offset: i32,+ from_end: bool,+ of_type: bool,+ of: Option<SelectorListView<'a>>,+}++impl<S: SelectorSubject> SelectorEvaluator<S> {+ /// Whether `node` matches `selector`, walking its compounds from the subject leftwards.+ /// A selector targeting a pseudo-element matches the element it originates from: the compounds before it.+ pub(crate) fn matches_selector(+ &mut self,+ selector: Selector<'_>,+ node: S::Node,+ context: MatchContext<'_>,+ ) -> Answer<S> {+ // NB: The compounds are read from the subject leftwards where they lie in the arena: the compound a selector+ // ends in, as `::part()`, `::slotted()` or a pseudo-element, is the first one read, which the arena notes+ // most selectors end in none of.+ if selector.describes_its_subject() {+ return self.matches_from(selector, None, node, context);+ }+ let target = selector.first_compound();+ if targets_a_pseudo_element(&target) {+ let Some(left) = left_of(selector) else {+ return Ok(false);+ };+ // The pseudo-classes written after an element-backed pseudo-element describe the element backing it,+ // which stands in the originating element's shadow tree.+ match backed_pseudo_element_kind(&target) {+ Some(kind) => {+ let Some(backing) = self.subject.tree().backing_element_of(node, kind) else {+ return Ok(false);+ };+ for simple in target.simple_selectors.after_first().iter() {+ if !self.matches_simple_component(&simple, backing, context)? {+ return Ok(false);+ }+ }+ }+ // FIXME: The pseudo-classes written after a pseudo-element no element backs, which describe the+ // pseudo-element itself, but for the search text filters, which pick the entry.+ None if target+ .simple_selectors+ .after_first()+ .iter()+ .any(|simple| crate::css::selector_arena::search_text_match_filter(&simple).is_none()) =>+ {+ return Ok(false);+ }+ None => {}+ }+ return self.matches_chain_from(left, node, context);+ }+ self.matches_chain_from(selector, node, context)+ }++ /// As [`Self::matches_selector`], for the selector from `at` leftwards, once the compound of a pseudo-element it+ /// targets was matched.+ fn matches_chain_from(&mut self, at: Selector<'_>, node: S::Node, context: MatchContext<'_>) -> Answer<S> {+ let target = at.first_compound();+ let rest = left_of(at);+ if let Some(names) = part_names(&target) {+ return self.matches_part(rest, &target, names, node, context);+ }+ if let Some(argument) = slotted_argument(&target) {+ return self.matches_slotted(rest, argument, node, context);+ }+ self.matches_from(at, None, node, context)+ }++ /// Whether `node` is a part, named `names`, which a host the selector `rest` matches exposes, and matches the+ /// pseudo-classes written after `::part()`.+ ///+ /// https://drafts.csswg.org/css-shadow-parts-1/#part+ fn matches_part(+ &mut self,+ rest: Option<Selector<'_>>,+ part: &CompoundRef<'_>,+ names: &[StyleAtomID],+ node: S::Node,+ context: MatchContext<'_>,+ ) -> Answer<S> {+ for simple in part.simple_selectors.after_first().iter() {+ if !self.matches_simple_component(&simple, node, context)? {+ return Ok(false);+ }+ }+ // `::part()` reaches one level down: into a tree hosted by an element of the tree the rule itself is in. A+ // compound naming `:host` reaches the rule's own tree as well, which is where a part forwarded out of it+ // stands.+ let tree = self.subject.tree();+ let scope_host = self.bindings.scope_shadow_root.and_then(|root| tree.host_of(root));+ let mentions_the_host = rest.is_some_and(|rest| {+ rest.first_compound().simple_selectors.iter().any(|simple| {+ matches!(simple, SimpleSelector::PseudoClass(pseudo_class) if pseudo_class.pseudo_class == PseudoClassType::Host)+ })+ });+ for level_host in self.subject.part_exposure_hosts(node) {+ let reaches_a_hosted_tree = tree.shadow_host_of(level_host) == scope_host;+ let reaches_its_own_tree = Some(level_host) == scope_host && mentions_the_host;+ if !reaches_a_hosted_tree && !reaches_its_own_tree {+ continue;+ }+ let mut exposed = true;+ for &name in names {+ if !self.subject.exposes_part_to(node, name, level_host)? {+ exposed = false;+ break;+ }+ }+ if !exposed {+ continue;+ }+ let host_matches = match rest {+ Some(rest) => self.matches_from(rest, None, level_host, context)?,+ None => true,+ };+ if host_matches {+ return Ok(true);+ }+ }+ Ok(false)+ }++ /// Whether `node`, slotted, matches `argument`, and a slot it is assigned to through the tree whose selectors are+ /// matched matches the selector `rest`.+ ///+ /// https://drafts.csswg.org/css-scoping/#slotted-pseudo+ fn matches_slotted(+ &mut self,+ rest: Option<Selector<'_>>,+ argument: Selector<'_>,+ node: S::Node,+ context: MatchContext<'_>,+ ) -> Answer<S> {+ let tree = self.subject.tree();+ if tree.assigned_slot_of(node).is_none() || !self.matches_selector(argument, node, context)? {+ return Ok(false);+ }+ // The chain can pass through several trees; the slot the compounds describe is the one in the tree whose+ // selectors are matched.+ const MAX_REASSIGNMENTS: usize = 32;+ let mut current = node;+ for _ in 0..MAX_REASSIGNMENTS {+ let Some(slot) = tree.assigned_slot_of(current) else {+ return Ok(false);+ };+ let in_this_tree = self.bindings.scope_shadow_root.is_none_or(|root| {+ std::iter::successors(Some(slot), |&node| tree.live_parent(node)).any(|node| node == root)+ });+ if in_this_tree {+ let slot_matches = match rest {+ Some(rest) => self.matches_from(rest, None, slot, context)?,+ None => true,+ };+ if slot_matches {+ return Ok(true);+ }+ }+ current = slot;+ }+ Ok(false)+ }++ fn matches_scope_level(+ &mut self,+ scope: &super::bridge::BoundScopeChain,+ level: usize,+ selector: Selector<'_>,+ names_the_scope: bool,+ node: S::Node,+ context: MatchContext<'_>,+ ) -> Answer<S> {+ if level == scope.levels.len() {+ let matches = self.matches_selector(selector, node, context)?;+ if matches {+ self.bindings.matched_scope_root = self.bindings.scope_root_instance;+ }+ return Ok(matches);+ }+ let (roots, limits) = scope_level_ranges(scope, level);+ let innermost = level + 1 == scope.levels.len();+ // A scoped selector carries an implied `:scope ` prefix unless it names `:scope`, so the subject is a strict+ // descendant of the innermost root. An enclosing scope is satisfied by the subject being anywhere inside it.+ let inclusive = !innermost || names_the_scope;+ let enclosing_root = self.bindings.scope_root_instance;+ let scope_shadow_root = self.bindings.scope_shadow_root;+ let tree = self.subject.tree();+ let step = |candidate: Option<S::Node>| match candidate {+ Some(root) if Some(root) == scope_shadow_root => tree.host_of(root),+ candidate => candidate,+ };+ // A part stands inside a shadow tree, but an outer scope reaches it through the host exposing it, so scope+ // membership is measured from that host rather than from the part's parent chain.+ let part_hosts = match part_names(&selector.first_compound()) {+ Some(_) => self.subject.part_hosts_in_exposure_scope(node),+ None => None,+ };+ let starts: smallvec::SmallVec<[(Option<S::Node>, bool); 1]> = match &part_hosts {+ Some(hosts) => hosts+ .iter()+ .map(|&host| match inclusive {+ true => (Some(host), false),+ false => (tree.live_parent(host), false),+ })+ .collect(),+ None => smallvec::smallvec![(+ step(match inclusive {+ true => Some(node),+ false => tree.live_parent(node),+ }),+ true+ )],+ };+ for (start, steps_to_host) in starts {+ let mut candidate = start;+ while let Some(root) = candidate {+ if self.matches_scope_root(scope, level, roots.clone(), root, context)? {+ let outer = self.bindings.scope_root_instance.replace(root);+ let answer = (|| -> Answer<S> {+ if self.is_beyond_scope_limit(scope, limits.clone(), node, root, context)? {+ return Ok(false);+ }+ self.matches_scope_level(scope, level + 1, selector, names_the_scope, node, context)+ })();+ self.bindings.scope_root_instance = outer;+ if answer? {+ return Ok(true);+ }+ }+ if Some(root) == enclosing_root {+ break;+ }+ candidate = match steps_to_host {+ true => step(tree.live_parent(root)),+ false => tree.live_parent(root),+ };+ }+ }+ Ok(false)+ }++ /// Whether `candidate` roots a scope of `level`: its implicit root, or an element its `<scope-start>` matches,+ /// where `:scope` names the enclosing scope's root.+ fn matches_scope_root(+ &mut self,+ scope: &super::bridge::BoundScopeChain,+ level: usize,+ roots: std::ops::Range<usize>,+ candidate: S::Node,+ context: MatchContext<'_>,+ ) -> Answer<S> {+ if let Some(implicit) = scope.implicit_roots.get(level).copied().flatten() {+ let matches = match implicit {+ super::compiler::ImplicitScopeRoot::Node(named) => self.subject.is_node(candidate, named),+ super::compiler::ImplicitScopeRoot::ContainingTree => {+ self.subject.is_root(candidate)+ || self+ .bindings+ .scope_shadow_root+ .is_some_and(|root| self.subject.tree().shadow_root_of(candidate) == Some(root))+ }+ };+ if matches {+ return Ok(true);+ }+ }+ let anchor = self.bindings.scope_root_instance;+ for root in &scope.roots[roots] {+ let root = root.view();+ let leading = root.leftmost_compound().combinator;+ // Directly inside another `@scope`, a start that begins with a combinator is relative to its root.+ let matches = match leading {+ Combinator::None => self.matches_selector(root, candidate, context)?,+ Combinator::Descendant => {+ self.matches_with_leading(root, Combinator::None, None, candidate, context)?+ }+ _ => self.matches_with_leading(root, leading, anchor, candidate, context)?,+ };+ if matches {+ return Ok(true);+ }+ }+ Ok(false)+ }++ /// Whether `node`, or an element between it and the scoping root `root`, matches a `<scope-end>` of the level.+ fn is_beyond_scope_limit(+ &mut self,+ scope: &super::bridge::BoundScopeChain,+ limits: std::ops::Range<usize>,+ node: S::Node,+ root: S::Node,+ context: MatchContext<'_>,+ ) -> Answer<S> {+ if limits.is_empty() {+ return Ok(false);+ }+ let tree = self.subject.tree();+ let mut walked = Some(node);+ while let Some(current) = walked {+ for (limit, &names_the_root) in scope.limits[limits.clone()]+ .iter()+ .zip(&scope.limits_name_the_root[limits.clone()])+ {+ let limit = limit.view();+ let leading = limit.leftmost_compound().combinator;+ // https://drafts.csswg.org/css-cascade-6/#scope-syntax+ // A `<scope-end>` is relative to the scoping root: one that starts with a combinator, or names+ // neither `&` nor `:scope`, is read as though `:where(:scope)` came first.+ let matches = match (leading, names_the_root) {+ (Combinator::None, false) => {+ self.matches_with_leading(limit, Combinator::Descendant, Some(root), current, context)?+ }+ (Combinator::None | Combinator::Descendant, true) => {+ self.matches_with_leading(limit, Combinator::None, None, current, context)?+ }+ (leading, _) => self.matches_with_leading(limit, leading, Some(root), current, context)?,+ };+ if matches {+ return Ok(true);+ }+ }+ if current == root {+ break;+ }+ walked = tree.live_parent(current);+ }+ Ok(false)+ }++ /// Whether `node` matches `selector` with its leftmost compound related to `anchor` by `leading`, or standing+ /// alone for no combinator.+ fn matches_with_leading(+ &mut self,+ selector: Selector<'_>,+ leading: Combinator,+ anchor: Option<S::Node>,+ node: S::Node,+ context: MatchContext<'_>,+ ) -> Answer<S> {+ let outer = std::mem::replace(&mut self.bindings.relative_anchor, anchor);+ let answer = self.matches_from(selector, Some(leading), node, context);+ self.bindings.relative_anchor = outer;+ answer+ }++ /// Whether `node` matches any selector of `list`.+ fn matches_any(&mut self, list: SelectorListView<'_>, node: S::Node, context: MatchContext<'_>) -> Answer<S> {+ let context = MatchContext {+ logical_subject: true,+ ..context+ };+ for selector in list {+ // A pseudo-element is not an element, which a logical pseudo-class's argument describes.+ if !targets_a_pseudo_element(&selector.first_compound())+ && self.matches_selector(selector, node, context)?+ {+ return Ok(true);+ }+ }+ Ok(false)+ }++ /// Whether `node` matches the selector from `at`, its subject compound, leftwards, with the leftmost compound+ /// related to the anchor by `leading` where one is given rather than by the combinator written.+ fn matches_from(+ &mut self,+ at: Selector<'_>,+ leading: Option<Combinator>,+ node: S::Node,+ context: MatchContext<'_>,+ ) -> Answer<S> {+ Ok(self.walk_compound(at, true, leading, node, context)? == Walk::Matched)+ }++ /// As [`Self::walk_compound`] for a compound left of the subject's, which an element whose dispatch keys lack an id+ /// or class it tests for cannot match: the bits the arena noted for the compound tell before its components are read.+ fn walk_rejecting_on_bloom(+ &mut self,+ at: Selector<'_>,+ leading: Option<Combinator>,+ node: S::Node,+ context: MatchContext<'_>,+ ) -> Result<Walk, S::Incomplete> {+ if S::FILTERS_BY_REQUIRED_DISPATCH_BLOOM {+ let required = required_dispatch_bloom(at, context);+ if required != 0 && !self.subject.may_match_required(required, node) {+ return Ok(Walk::RestartFromLaterSibling);+ }+ }+ self.walk_compound(at, false, leading, node, context)+ }++ /// Whether `node` matches the first compound of `at`, the subject compound where `is_subject`, and what is left+ /// of it, or else which elements no further one tried left of the combinator right of it can match from either.+ fn walk_compound(+ &mut self,+ at: Selector<'_>,+ is_subject: bool,+ leading: Option<Combinator>,+ node: S::Node,+ context: MatchContext<'_>,+ ) -> Result<Walk, S::Incomplete> {+ let compound = at.first_compound();+ if !self.matches_compound_components(&compound, node, context)?+ || self.is_outside_the_default_namespace(&compound, is_subject, node, context)?+ {+ return Ok(Walk::RestartFromLaterSibling);+ }+ self.walk_left_of(at, leading, node, context)+ }++ /// Whether `node` is outside the default namespace that constrains `compound`, the subject compound where+ /// `is_subject`.+ fn is_outside_the_default_namespace(+ &mut self,+ compound: &CompoundRef<'_>,+ is_subject: bool,+ node: S::Node,+ context: MatchContext<'_>,+ ) -> Answer<S> {+ // A compound with no type or universal selector written has one implied, which a default namespace+ // constrains as well, except where the compound names the host, the selector reaches into another tree, or+ // the compound is the subject of a logical pseudo-class's argument.+ // The universal selector the parse implies before a compound that starts with a pseudo-element is not+ // written.+ let written = match compound.is_implicit_universal_anchor {+ true => compound.simple_selectors.after_first(),+ false => compound.simple_selectors,+ };+ Ok(match context.namespaces.default {+ Some(default)+ if !context.escapes_its_namespace+ && !(context.logical_subject && is_subject)+ && !written.iter().any(|simple| {+ matches!(simple, SimpleSelector::Universal(_) | SimpleSelector::TagName(_))+ || matches!(simple, SimpleSelector::PseudoClass(pseudo_class) if pseudo_class.pseudo_class == PseudoClassType::Host)+ }) =>+ {+ !self.is_in_namespace(default, node)?+ }+ _ => false,+ })+ }++ /// Whether `node` is in the namespace the qualified name `name` names in its sheet.+ ///+ /// https://drafts.csswg.org/css-namespaces/#css-qnames+ fn is_in_namespace_of(+ &mut self,+ name: &crate::css::selector::QualifiedName,+ node: S::Node,+ context: MatchContext<'_>,+ ) -> Answer<S> {+ let prefix = (name.namespace_type == NamespaceType::Named).then_some(name.namespace);+ match context.namespaces.test_for(name.namespace_type, prefix) {+ Ok(Some(namespace)) => self.is_in_namespace(namespace, node),+ Ok(None) => Ok(true),+ // A qualified name with a prefix that has not been declared is invalid, and matches nothing.+ Err(_) => Ok(false),+ }+ }++ /// Whether `node` is in `namespace`, none being the absence of one.+ fn is_in_namespace(&mut self, namespace: StyleAtomID, node: S::Node) -> Answer<S> {+ let row = self.subject.row(node)?;+ Ok(self.subject.features(row).namespace_is(namespace))+ }++ /// Whether what is left of the first compound of `at`, matched at `node`, matches: the compound left of it, or for+ /// the leftmost compound of a relative selector, the anchor of the `:has()` being answered.+ ///+ /// NB: A failure tells how far back a walk has to go, so that a walk up or back across elements does not try+ /// again what an inner walk already tried.+ fn walk_left_of(+ &mut self,+ at: Selector<'_>,+ leading: Option<Combinator>,+ node: S::Node,+ context: MatchContext<'_>,+ ) -> Result<Walk, S::Incomplete> {+ let (combinator, left_compounds) = match at.left() {+ Some((combinator, left)) if !left.is_relative_anchor() => (combinator, Some(left)),+ Some((combinator, _)) => (leading.unwrap_or(combinator), None),+ None => (leading.unwrap_or(Combinator::None), None),+ };+ if left_compounds.is_none() && combinator == Combinator::None {+ return Ok(Walk::Matched);+ }+ let tree = self.subject.tree();+ match combinator {+ Combinator::ImmediateChild => match self.parent_in_walk(node) {+ Some(parent) => Ok(match self.walk_left(left_compounds, leading, parent, false, context)? {+ walk @ (Walk::Matched | Walk::NotMatchedGlobally) => walk,+ _ => Walk::RestartFromDescendant,+ }),+ None => Ok(Walk::NotMatchedGlobally),+ },+ Combinator::Descendant => self.walk_up(left_compounds, leading, node, context),+ Combinator::NextSibling => {+ self.subject.note_structural_read(node, StructuralRead::PreviousSibling);+ match tree.previous_sibling(node) {+ Some(sibling) => self.walk_left(left_compounds, leading, sibling, false, context),+ None => Ok(Walk::RestartFromDescendant),+ }+ }+ Combinator::SubsequentSibling => {+ self.subject.note_structural_read(node, StructuralRead::EarlierSiblings);+ self.walk_back(left_compounds, leading, node, context)+ }+ // FIXME: Pseudo-element compounds and the column combinator.+ Combinator::PseudoElement | Combinator::Column | Combinator::None => Ok(Walk::NotMatchedGlobally),+ }+ }++ /// Test `candidate`, which a combinator reached, against the compounds left of it, `left_compounds`, or where+ /// there are none against what the selector is relative to.+ ///+ /// NB: A walk up has tested each ancestor against the bits the compound requires before trying it, which the+ /// compound need not test again where `bloom_checked`.+ #[inline(always)]+ fn walk_left(+ &mut self,+ left_compounds: Option<Selector<'_>>,+ leading: Option<Combinator>,+ candidate: S::Node,+ bloom_checked: bool,+ context: MatchContext<'_>,+ ) -> Result<Walk, S::Incomplete> {+ match left_compounds {+ // A relative selector outside a `:has()` is relative to the scoping root, as one in `@scope` is.+ None => Ok(+ match match self.bindings.relative_anchor {+ Some(anchor) => anchor == candidate,+ None => self.is_scoping_root(candidate),+ } {+ true => Walk::Matched,+ false => Walk::RestartFromLaterSibling,+ },+ ),+ Some(left) if bloom_checked => self.walk_compound(left, false, leading, candidate, context),+ Some(left) => self.walk_rejecting_on_bloom(left, leading, candidate, context),+ }+ }++ /// The parent a combinator reaches from `node`.+ ///+ /// https://drafts.csswg.org/css-scoping/#host-element-in-tree+ /// In the context of its shadow tree, the shadow host is the parent of the tree's root elements. Nothing outside+ /// the tree whose selectors are matched is above its host.+ #[inline(always)]+ fn parent_in_walk(&self, node: S::Node) -> Option<S::Node> {+ let tree = self.subject.tree();+ let scope_shadow_root = self.bindings.scope_shadow_root;+ match tree.parent(node) {+ _ if scope_shadow_root.is_some() && tree.shadow_root_of(node) == scope_shadow_root => None,+ Some(parent) if Some(parent) == scope_shadow_root => tree.host_of(parent),+ parent => parent,+ }+ }++ /// Where what this walk from `left` finds for an element is remembered: it is what it finds for every element it+ /// passed on the way, for a subject that remembers it, while no `:has()` or `@scope` start binds the walk.+ #[inline(always)]+ fn remembered_walk(&mut self, left: Option<Selector<'_>>, leading: Option<Combinator>) -> Option<S::WalkAnswers> {+ let left = left?;+ if leading.is_some() || self.bindings.relative_anchor.is_some() || self.bindings.matching_host_argument {+ return None;+ }+ self.subject.walk_answers(left.key(), &self.bindings)+ }++ /// Test the ancestors of `node` against `left_compounds`, across a descendant combinator.+ fn walk_up(+ &mut self,+ left_compounds: Option<Selector<'_>>,+ leading: Option<Combinator>,+ node: S::Node,+ context: MatchContext<'_>,+ ) -> Result<Walk, S::Incomplete> {+ // An ancestor whose dispatch keys lack an id or class the compound left of the combinator tests for+ // cannot match it.+ let required = match left_compounds {+ Some(left) if S::FILTERS_BY_REQUIRED_DISPATCH_BLOOM => required_dispatch_bloom(left, context),+ _ => 0,+ };+ let remembered = match S::REMEMBERS_ANCESTOR_ANSWERS {+ true => self.remembered_walk(left_compounds, leading),+ false => None,+ };+ let mut passed: SmallVec<[S::Node; 16]> = SmallVec::new();+ let mut found = Walk::NotMatchedGlobally;+ let mut ancestor = self.parent_in_walk(node);+ while let Some(current) = ancestor {+ if let Some(answers) = remembered {+ if let Some(answer) = self.subject.walk_answer(answers, current) {+ found = match answer {+ true => Walk::Matched,+ false => Walk::NotMatchedGlobally,+ };+ break;+ }+ passed.push(current);+ }+ if (required == 0 || self.subject.may_match_required(required, current))+ && let walk @ (Walk::Matched | Walk::NotMatchedGlobally) =+ self.walk_left(left_compounds, leading, current, required != 0, context)?+ {+ found = walk;+ break;+ }+ ancestor = self.parent_in_walk(current);+ }+ if let Some(answers) = remembered {+ self.subject+ .record_walk_answers(answers, &passed, found == Walk::Matched);+ }+ Ok(found)+ }++ /// Test the earlier siblings of `node` against `left_compounds`, across a subsequent-sibling combinator.+ fn walk_back(+ &mut self,+ left_compounds: Option<Selector<'_>>,+ leading: Option<Combinator>,+ node: S::Node,+ context: MatchContext<'_>,+ ) -> Result<Walk, S::Incomplete> {+ let tree = self.subject.tree();+ let remembered = match S::REMEMBERS_SIBLING_ANSWERS {+ true => self.remembered_walk(left_compounds, leading),+ false => None,+ };+ let mut passed: SmallVec<[S::Node; 16]> = SmallVec::new();+ let mut sibling = tree.previous_sibling(node);+ let found = loop {+ let Some(current) = sibling else {+ break false;+ };+ if let Some(answers) = remembered {+ if let Some(answer) = self.subject.walk_answer(answers, current) {+ break answer;+ }+ passed.push(current);+ }+ match self.walk_left(left_compounds, leading, current, false, context)? {+ Walk::Matched => break true,+ // A walk that gave up on the subject says nothing of the siblings left.+ walk @ (Walk::NotMatchedGlobally | Walk::RestartFromDescendant) => return Ok(walk),+ Walk::RestartFromLaterSibling => {}+ }+ sibling = tree.previous_sibling(current);+ };+ if let Some(answers) = remembered {+ self.subject.record_walk_answers(answers, &passed, found);+ }+ Ok(match found {+ true => Walk::Matched,+ false => Walk::RestartFromDescendant,+ })+ }++ /// Whether an element relative to `anchor` matches a selector of `list`, the argument of a `:has()`. The+ /// candidates are reached from `within`: the anchor, or the shadow root of the host a `:host:has()` names.+ ///+ /// https://drafts.csswg.org/selectors/#relational+ fn matches_relative(+ &mut self,+ list: SelectorListView<'_>,+ anchor: S::Node,+ within: S::Node,+ context: MatchContext<'_>,+ ) -> Answer<S> {+ let key = list.identity();+ if let Some(key) = key+ && let Some(answer) = self.subject.relative_answer_of(key, anchor, &self.bindings)+ {+ return Ok(answer);+ }+ let answer = (|| {+ for selector in list {+ if self.matches_relative_selector(selector, anchor, within, context)? {+ return Ok(true);+ }+ }+ Ok(false)+ })();+ // A walk that ended incomplete proved nothing either way.+ if let Some(key) = key+ && let Ok(answer) = answer+ {+ self.subject+ .record_relative_answer_of(key, anchor, &self.bindings, answer);+ }+ answer+ }++ /// Whether an element relative to `anchor` matches `selector`, a relative selector of the argument of a `:has()`,+ /// reached from `within` as [`Self::matches_relative`] reaches it.+ fn matches_relative_selector(+ &mut self,+ selector: Selector<'_>,+ anchor: S::Node,+ within: S::Node,+ context: MatchContext<'_>,+ ) -> Answer<S> {+ if selector.is_relative_anchor() {+ return Ok(false);+ }+ let context = MatchContext {+ logical_subject: false,+ ..context+ };+ let outer = self.bindings.relative_anchor.replace(anchor);+ let outer_argument = std::mem::replace(&mut self.bindings.matching_relative_argument, true);+ let (axis, below_the_axis) = relative_axis(selector);+ let tree = self.subject.tree();+ let mut matched = Ok(false);+ // The anchor stands outside the tree a `:host:has()` reads, whose root it walks from.+ let axis = match (within == anchor, axis) {+ (false, _) => super::relative_selector::RelativeAxis::Descendant,+ (true, axis) => axis,+ };+ super::selector_evaluation::walk_relative_axis(tree, axis, below_the_axis, within, |candidate| {+ match self.matches_from(selector, None, candidate, context) {+ Ok(true) => {+ matched = Ok(true);+ false+ }+ Ok(false) => true,+ Err(incomplete) => {+ matched = Err(incomplete);+ false+ }+ }+ });+ self.bindings.relative_anchor = outer;+ self.bindings.matching_relative_argument = outer_argument;+ matched+ }++ fn matches_compound_components(+ &mut self,+ compound: &CompoundRef<'_>,+ node: S::Node,+ context: MatchContext<'_>,+ ) -> Answer<S> {+ // https://drafts.csswg.org/css-scoping/#host-element-in-tree+ // In the context of its shadow tree, the shadow host is featureless: only `:host` and the like match it.+ // FIXME: `:host-context()`, which makes a compound match it.+ if let Some(shadow_root) = self.bindings.scope_shadow_root+ && self.subject.tree().shadow_root_of(node) == Some(shadow_root)+ && !self.bindings.matching_host_argument+ {+ return self.matches_featureless_host_components(compound, node, context);+ }+ let answer = self.test_components(compound.simple_selectors, node, context, false, |_| DecodedTest::Run)?;+ Ok(answer == Some(true))+ }++ /// Test `simple_selectors` of `node`, the names and states of a compound first, and what decodes its component+ /// after them, which `decided` can answer for instead: they reject most elements for less. Answers false at the+ /// first test that fails. Where `goes_on_unknown`, a test that cannot tell does not end the walk, as a later one+ /// may fail, and the answer is none unless one did; a failure to tell is the answer otherwise.+ #[inline(always)]+ fn test_components(+ &mut self,+ simple_selectors: crate::css::selector_arena::SimpleSelectors<'_>,+ node: S::Node,+ context: MatchContext<'_>,+ goes_on_unknown: bool,+ decided: impl Fn(&SimpleSelector<'_>) -> DecodedTest,+ ) -> Result<Option<bool>, S::Incomplete> {+ let mut known = true;+ // NB: The element's facts are fetched once for the names of the compound.+ let mut row: Option<S::Row> = None;+ let mut row_of = |evaluator: &mut Self| -> Result<S::Row, S::Incomplete> {+ if let Some(row) = row {+ return Ok(row);+ }+ let fetched = evaluator.subject.row(node)?;+ row = Some(fetched);+ Ok(fetched)+ };+ let mut deferred: SmallVec<[crate::css::selector_arena::SimpleView<'_>; 2]> = SmallVec::new();+ for view in simple_selectors.views() {+ let answer = match view {+ crate::css::selector_arena::SimpleView::Id(name) => {+ row_of(self).map(|row| self.has_id_in(row, name, context))+ }+ crate::css::selector_arena::SimpleView::Class(name) => {+ row_of(self).map(|row| self.has_class_in(row, name, context))+ }+ crate::css::selector_arena::SimpleView::TagName(name) => {+ match self.is_in_namespace_of(&name, node, context) {+ Ok(true) => row_of(self).map(|row| self.has_local_name_in(row, &name, context)),+ other => other,+ }+ }+ crate::css::selector_arena::SimpleView::PseudoClass {+ kind,+ is_search_text_filter,+ ..+ } if is_bare_pseudo_class(kind, is_search_text_filter) => {+ self.matches_bare_pseudo_class(kind, node, context)+ }+ other => {+ deferred.push(other);+ continue;+ }+ };+ match answer {+ Ok(true) => {}+ Ok(false) => return Ok(Some(false)),+ Err(incomplete) if !goes_on_unknown => return Err(incomplete),+ Err(_) => known = false,+ }+ }+ for view in deferred {+ let simple = &view.decode();+ match decided(simple) {+ DecodedTest::Run => {}+ DecodedTest::Holds => continue,+ DecodedTest::Unknown => {+ known = false;+ continue;+ }+ }+ match self.matches_simple_component(simple, node, context) {+ Ok(true) => {}+ Ok(false) => return Ok(Some(false)),+ Err(incomplete) if !goes_on_unknown => return Err(incomplete),+ Err(_) => known = false,+ }+ }+ Ok(known.then_some(true))+ }++ #[inline]+ fn has_tag_name(+ &mut self,+ name: &crate::css::selector::QualifiedName,+ node: S::Node,+ context: MatchContext<'_>,+ ) -> Answer<S> {+ if !self.is_in_namespace_of(name, node, context)? {+ return Ok(false);+ }+ let row = self.subject.row(node)?;+ Ok(self.has_local_name_in(row, name, context))+ }++ /// Whether the element whose facts `row` holds has the local name of the type selector `name`.+ #[inline]+ fn has_local_name_in(+ &self,+ row: S::Row,+ name: &crate::css::selector::QualifiedName,+ context: MatchContext<'_>,+ ) -> bool {+ let features = self.subject.features(row);+ // https://html.spec.whatwg.org/multipage/semantics-other.html#case-sensitivity-of-selectors+ let folds = !name.name_is_ascii_lowercase+ && !context.html_namespace.is_none()+ && features.namespace_is(context.html_namespace);+ let local = match folds {+ true => crate::css::style::process_atoms().ascii_lowercase(name.name),+ false => name.name,+ };+ features.local_name_is(local)+ }++ /// https://dom.spec.whatwg.org/#concept-id+ /// A quirks-mode document matches ids and classes ASCII case-insensitively.+ #[inline]+ fn has_id_in(&self, row: S::Row, name: crate::css::selector::NameSelector, context: MatchContext<'_>) -> bool {+ let id = match context.fold_ids_and_classes && !name.is_ascii_lowercase {+ true => crate::css::style::process_atoms().ascii_lowercase(name.name),+ false => name.name,+ };+ self.subject.features(row).has_id(id)+ }++ #[inline]+ fn has_class_in(&self, row: S::Row, name: crate::css::selector::NameSelector, context: MatchContext<'_>) -> bool {+ let class = match context.fold_ids_and_classes && !name.is_ascii_lowercase {+ true => crate::css::style::process_atoms().ascii_lowercase(name.name),+ false => name.name,+ };+ self.subject.features(row).has_class(class)+ }++ fn matches_simple_component(+ &mut self,+ simple: &SimpleSelector<'_>,+ node: S::Node,+ context: MatchContext<'_>,+ ) -> Answer<S> {+ match simple {+ SimpleSelector::Universal(name) => self.is_in_namespace_of(name, node, context),+ SimpleSelector::TagName(name) => self.has_tag_name(name, node, context),+ SimpleSelector::Id(name) => {+ let row = self.subject.row(node)?;+ Ok(self.has_id_in(row, *name, context))+ }+ SimpleSelector::Class(name) => {+ let row = self.subject.row(node)?;+ Ok(self.has_class_in(row, *name, context))+ }+ SimpleSelector::Attribute(attribute) => self.matches_attribute_component(attribute, node, context),+ SimpleSelector::PseudoClass(pseudo_class) => {+ self.matches_pseudo_class_component(pseudo_class, node, context)+ }+ // https://drafts.csswg.org/css-nesting/#nest-selector+ SimpleSelector::Nesting(Nesting::Rule(parent)) => self.matches_any(*parent, node, context),+ SimpleSelector::Nesting(Nesting::Root | Nesting::Scope) => Ok(self.is_scoping_root(node)),+ SimpleSelector::Nesting(Nesting::Unbound) => {+ unreachable!("placing a rule binds its `&` before it is matched")+ }+ // FIXME: Pseudo-elements.+ SimpleSelector::PseudoElement(_) => Ok(false),+ SimpleSelector::Invalid(_) => Ok(false),+ }+ }++ /// Whether the shadow host `node`, featureless in the tree whose selectors are matched, matches `compound`:+ /// every simple selector in it is a `:host` its argument matches.+ ///+ /// https://drafts.csswg.org/css-scoping/#host-selector+ fn matches_featureless_host_components(+ &mut self,+ compound: &CompoundRef<'_>,+ node: S::Node,+ context: MatchContext<'_>,+ ) -> Answer<S> {+ let mut names_the_host = false;+ for simple in compound.simple_selectors.iter() {+ let simple = &simple;+ // A logical pseudo-class or a `&` reaching the host matches it where an argument naming the host does.+ let arguments = match simple {+ SimpleSelector::PseudoClass(pseudo_class)+ if matches!(pseudo_class.pseudo_class, PseudoClassType::Is | PseudoClassType::Where) =>+ {+ Some(pseudo_class.argument_selector_list)+ }+ SimpleSelector::Nesting(Nesting::Rule(parent)) => Some(*parent),+ // The host can be the scoping root, which `:scope` and a `&` naming it name.+ SimpleSelector::PseudoClass(pseudo_class) if pseudo_class.pseudo_class == PseudoClassType::Scope => {+ if !self.is_scoping_root(node) {+ return Ok(false);+ }+ names_the_host = true;+ continue;+ }+ SimpleSelector::Nesting(Nesting::Root | Nesting::Scope) => {+ if !self.is_scoping_root(node) {+ return Ok(false);+ }+ names_the_host = true;+ continue;+ }+ _ => None,+ };+ if let Some(arguments) = arguments {+ if !self.matches_any(arguments, node, context)? {+ return Ok(false);+ }+ names_the_host = true;+ continue;+ }+ let SimpleSelector::PseudoClass(pseudo_class) = simple else {+ return Ok(false);+ };+ // A `:has()` beside `:host` is anchored on the host and reads the tree the host opens.+ if pseudo_class.pseudo_class == PseudoClassType::Has {+ let Some(shadow_root) = self.subject.tree().shadow_root_of(node) else {+ return Ok(false);+ };+ if !self.matches_relative(pseudo_class.argument_selector_list, node, shadow_root, context)? {+ return Ok(false);+ }+ continue;+ }+ if pseudo_class.pseudo_class != PseudoClassType::Host {+ return Ok(false);+ }+ names_the_host = true;+ if pseudo_class.argument_selector_list.is_empty() {+ continue;+ }+ let outer = std::mem::replace(&mut self.bindings.matching_host_argument, true);+ let matches = self.matches_any(pseudo_class.argument_selector_list, node, context);+ self.bindings.matching_host_argument = outer;+ if !matches? {+ return Ok(false);+ }+ }+ Ok(names_the_host)+ }++ /// Whether `node` is what `:scope` names: the bound scoping root, or else the root of its tree.+ fn is_scoping_root(&self, node: S::Node) -> bool {+ match self.bindings.scope_root_instance {+ Some(root) => root == node,+ None => self.subject.tree().live_parent(node).is_none(),+ }+ }++ fn matches_attribute_component(+ &mut self,+ attribute: &AttributeSelector<'_>,+ node: S::Node,+ context: MatchContext<'_>,+ ) -> Answer<S> {+ let atoms = crate::css::style::process_atoms();+ let row = self.subject.row(node)?;+ self.subject.read_attributes(row);+ let features = self.subject.features(row);+ let html_element = !context.html_namespace.is_none() && features.namespace_is(context.html_namespace);+ let written = attribute.qualified_name.name;+ // https://html.spec.whatwg.org/multipage/semantics-other.html#case-sensitivity-of-selectors+ // An attribute name is matched ASCII case-insensitively against an HTML element in an HTML document.+ let name = match html_element && !attribute.qualified_name.name_is_ascii_lowercase {+ true => atoms.ascii_lowercase(written),+ false => written,+ };+ // `[ns|x]` tests the name qualified by the namespace the prefix names, which only an attribute in that+ // namespace publishes.+ let qualified;+ let name = match attribute.qualified_name.namespace_type {+ NamespaceType::Named => {+ match context+ .namespaces+ .test_for(NamespaceType::Named, Some(attribute.qualified_name.namespace))+ {+ Ok(Some(namespace)) if !namespace.is_none() => {+ qualified = crate::css::style::AtomLease::acquire_qualified(atoms, namespace, name);+ qualified.atom()+ }+ Ok(_) => name,+ Err(_) => return Ok(false),+ }+ }+ // `[*|x]` tests the any-namespace name every attribute publishes, qualified by no namespace.+ NamespaceType::Any => {+ qualified = crate::css::style::AtomLease::acquire_qualified(atoms, StyleAtomID::NONE, name);+ qualified.atom()+ }+ _ => name,+ };+ let any_namespace = attribute.qualified_name.namespace_type == NamespaceType::Any;+ let operator = attribute.match_type;+ let insensitive = match attribute.case_type {+ AttributeCaseType::Insensitive => true,+ AttributeCaseType::Sensitive => false,+ AttributeCaseType::Default => html_element && attribute.names_a_legacy_case_insensitive_attribute,+ };+ // NB: Presence reads no value, which the values' subject would be asked for.+ if operator == AttributeMatchType::HasAttribute {+ return Ok(features.attributes_named(name, any_namespace).next().is_some());+ }+ let found: smallvec::SmallVec<[S::Attribute; 2]> = features.attributes_named(name, any_namespace).collect();+ Ok(found.into_iter().any(|found| {+ if operator == AttributeMatchType::ExactValue && !insensitive && !attribute.value_identity.is_none() {+ let value = self.subject.attribute_value_atom(found);+ if !value.is_none() {+ return value == attribute.value_identity;+ }+ }+ match self.subject.attribute_value_text(found) {+ Some(crate::css::css_tokenizer::TokenizerInput::Latin1(value)) => {+ attribute_value_matches(operator, value, attribute.value, insensitive)+ }+ Some(crate::css::css_tokenizer::TokenizerInput::Utf16(value)) => {+ attribute_value_matches(operator, value, attribute.value, insensitive)+ }+ None => false,+ }+ }))+ }++ fn matches_pseudo_class_component(+ &mut self,+ pseudo_class: &PseudoClassSelector<'_>,+ node: S::Node,+ context: MatchContext<'_>,+ ) -> Answer<S> {+ use PseudoClassType as Pc;+ let is_search_text_filter = pseudo_class.pseudo_class == Pc::Not+ && crate::css::selector::search_text_match_filter_of_pseudo_class(pseudo_class).is_some();+ if is_bare_pseudo_class(pseudo_class.pseudo_class, is_search_text_filter) {+ return self.matches_bare_pseudo_class(pseudo_class.pseudo_class, node, context);+ }+ let position = |step, offset, from_end, of_type, of| Position {+ step,+ offset,+ from_end,+ of_type,+ of,+ };+ let pattern = pseudo_class.an_plus_b_pattern;+ let arguments = pseudo_class.argument_selector_list;+ match pseudo_class.pseudo_class {+ // https://drafts.csswg.org/selectors/#matches+ // An argument list whose every selector is invalid parses to an empty one, which matches nothing.+ Pc::Is | Pc::Where => self.matches_any(arguments, node, context),+ Pc::Not => Ok(!self.matches_any(arguments, node, context)?),+ Pc::Scope => Ok(self.is_scoping_root(node)),+ Pc::NthChild | Pc::NthLastChild => {+ let of = (!arguments.is_empty()).then_some(arguments);+ let from_end = pseudo_class.pseudo_class == Pc::NthLastChild;+ self.matches_position(+ position(pattern.step_size, pattern.offset, from_end, false, of),+ node,+ context,+ )+ }+ Pc::NthOfType | Pc::NthLastOfType => {+ let from_end = pseudo_class.pseudo_class == Pc::NthLastOfType;+ self.matches_position(+ position(pattern.step_size, pattern.offset, from_end, true, None),+ node,+ context,+ )+ }+ Pc::Lang => {+ let row = self.subject.row(node)?;+ let mut ranges = pseudo_class.languages.iter().map(|range| range.value);+ // An element with no resolved language matches no range at all, not even `*`.+ Ok(match self.subject.language_tag(row) {+ crate::css::css_tokenizer::TokenizerInput::Latin1(tag) => {+ !tag.is_empty()+ && ranges.any(|range| crate::css::selector::language_range_matches_tag(range, tag))+ }+ crate::css::css_tokenizer::TokenizerInput::Utf16(tag) => {+ !tag.is_empty()+ && ranges.any(|range| crate::css::selector::language_range_matches_tag(range, tag))+ }+ })+ }+ Pc::Dir => {+ // NB: The arena holds the keyword in ASCII lowercase, as the directionality is compared.+ let keyword = pseudo_class.identifier_identity;+ if keyword.is_none() {+ return Ok(false);+ }+ let row = self.subject.row(node)?;+ Ok(self.subject.directionality_is(row, keyword))+ }+ Pc::State => {+ let row = self.subject.row(node)?;+ Ok(!pseudo_class.identifier_identity.is_none()+ && self.subject.has_custom_state(row, pseudo_class.identifier_identity))+ }+ Pc::Heading => {+ let row = self.subject.row(node)?;+ let level = self.subject.heading_level(row);+ Ok((1..=9).contains(&level)+ && (pseudo_class.levels.is_empty() || pseudo_class.levels.contains(&i64::from(level))))+ }+ // A `:host` reaches no element but the shadow host, which the compound walk answers for.+ Pc::Host => Ok(false),+ // https://drafts.csswg.org/selectors/#relational+ // A `:has()` does not nest, not even through a `&` naming a rule whose selectors have one.+ Pc::Has if self.bindings.matching_relative_argument => Ok(false),+ Pc::Has => self.matches_relative(arguments, node, node, context),+ // A search text filter picks the kind of search text match a `::search-text` styles, which the entry+ // carries, and constrains no element.+ _ => Ok(false),+ }+ }++ /// Whether `node` matches a pseudo-class of the kind `kind` taking no argument, which+ /// [`is_bare_pseudo_class`] says it is, read from its kind alone.+ fn matches_bare_pseudo_class(+ &mut self,+ kind: PseudoClassType,+ node: S::Node,+ context: MatchContext<'_>,+ ) -> Answer<S> {+ use PseudoClassType as Pc;+ if let Some(fact) = super::compiler::state_fact_for(kind) {+ let row = self.subject.row(node)?;+ return Ok(self.subject.has_state(row, fact));+ }+ let first = |from_end, of_type| Position {+ step: 0,+ offset: 1,+ from_end,+ of_type,+ of: None,+ };+ match kind {+ // A search text filter picks the kind of search text match a `::search-text` styles, which the entry+ // carries, and constrains no element.+ Pc::Not | Pc::Current => Ok(true),+ Pc::Root => Ok(self.subject.is_root(node)),+ Pc::Empty => {+ self.subject.note_structural_read(node, StructuralRead::Emptiness);+ self.subject.is_empty(node)+ }+ Pc::FirstChild => self.matches_position(first(false, false), node, context),+ Pc::LastChild => self.matches_position(first(true, false), node, context),+ Pc::FirstOfType => self.matches_position(first(false, true), node, context),+ Pc::LastOfType => self.matches_position(first(true, true), node, context),+ Pc::OnlyChild => Ok(self.matches_position(first(false, false), node, context)?+ && self.matches_position(first(true, false), node, context)?),+ Pc::OnlyOfType => Ok(self.matches_position(first(false, true), node, context)?+ && self.matches_position(first(true, true), node, context)?),+ _ => unreachable!("a pseudo-class taking an argument is matched decoded"),+ }+ }++ /// Whether `node` sits at a position `position` names among its inclusive siblings.+ ///+ /// https://drafts.csswg.org/selectors/#child-index+ fn matches_position(&mut self, position: Position<'_>, node: S::Node, context: MatchContext<'_>) -> Answer<S> {+ self.subject.note_structural_read(+ node,+ StructuralRead::Position {+ from_end: position.from_end,+ of_type: position.of_type,+ beyond_edge: position.step != 0 || position.offset != 1 || position.of.is_some(),+ },+ );+ if position.of.is_none() {+ let remembered = super::selector::NthPosition {+ step: position.step,+ offset: position.offset,+ from_end: position.from_end,+ of_type: position.of_type,+ };+ if let Some(index) = self.subject.sibling_index(remembered, node)? {+ return Ok(super::selector::matches_an_plus_b(+ position.step,+ position.offset,+ index,+ ));+ }+ }+ if let Some(of) = position.of+ && !self.matches_any(of, node, context)?+ {+ return Ok(false);+ }+ // An index among the siblings `of S` matches is remembered by the list, as each sibling is counted once.+ let of_key = match self.bindings.matching_host_argument {+ false => position.of.and_then(SelectorListView::identity),+ true => None,+ };+ if let Some(key) = of_key+ && self.subject.remembers_of_indices()+ && let Some(index) = self.of_index(key, position, node, context)?+ {+ return Ok(super::selector::matches_an_plus_b(+ position.step,+ position.offset,+ index,+ ));+ }+ let subject_row = match position.of_type {+ true => Some(self.subject.row(node)?),+ false => None,+ };+ let tree = self.subject.tree();+ let mut index: i64 = 1;+ let mut current = match position.from_end {+ true => tree.next_sibling(node),+ false => tree.previous_sibling(node),+ };+ while let Some(sibling) = current {+ let counts = match (subject_row, position.of) {+ (Some(row), _) => {+ let sibling_row = self.subject.row(sibling)?;+ self.subject.same_type(row, sibling_row)+ }+ (None, Some(of)) => self.matches_any(of, sibling, context)?,+ (None, None) => true,+ };+ // A matching sibling with its index remembered counts every matching sibling beyond it.+ if counts+ && let Some(key) = of_key+ && let Some(remembered) = self.subject.of_index_of(key, position.from_end, sibling)+ {+ index += remembered;+ break;+ }+ index += i64::from(counts);+ // A test with no step names one position, which no sibling further away can bring the count back to.+ if position.step == 0 && index > i64::from(position.offset) {+ if position.of_type {+ self.subject.row(node)?;+ }+ return Ok(false);+ }+ current = match position.from_end {+ true => tree.next_sibling(sibling),+ false => tree.previous_sibling(sibling),+ };+ }+ // NB: A compound reads its element's names once, and the subject may hold the sibling it read last instead.+ if position.of_type {+ self.subject.row(node)?;+ }+ if let Some(key) = of_key {+ self.subject.record_of_index(key, position.from_end, node, index);+ }+ Ok(super::selector::matches_an_plus_b(+ position.step,+ position.offset,+ index,+ ))+ }++ /// The index of `node`, which matches the `of S` list `key` names, among its inclusive siblings that match it,+ /// counted from the end: one less than that of the nearest earlier sibling matching it, when that is remembered.+ /// None for a count from the start, which the walk back finds.+ fn of_index(+ &mut self,+ key: super::selector_evaluation::SelectorListKey,+ position: Position<'_>,+ node: S::Node,+ context: MatchContext<'_>,+ ) -> Result<Option<i64>, S::Incomplete> {+ let Some(of) = position.of.filter(|_| position.from_end) else {+ return Ok(None);+ };+ let tree = self.subject.tree();+ let mut sibling = tree.previous_sibling(node);+ while let Some(current) = sibling {+ if self.matches_any(of, current, context)? {+ let index = self.subject.of_index_of(key, true, current).map(|later| later - 1);+ if let Some(index) = index {+ self.subject.record_of_index(key, true, node, index);+ }+ return Ok(index);+ }+ sibling = tree.previous_sibling(current);+ }+ Ok(None)+ }+}++/// Whether a pseudo-class of the kind `kind` is answered from its kind alone, with no argument to decode: a state, a+/// structural test of the first or last position, `:root`, `:empty`, or a `:not()` that only filters search text.+fn is_bare_pseudo_class(kind: PseudoClassType, is_search_text_filter: bool) -> bool {+ use PseudoClassType as Pc;+ super::compiler::state_fact_for(kind).is_some()+ || matches!(+ kind,+ Pc::Current+ | Pc::Root+ | Pc::Empty+ | Pc::FirstChild+ | Pc::LastChild+ | Pc::FirstOfType+ | Pc::LastOfType+ | Pc::OnlyChild+ | Pc::OnlyOfType+ )+ || (kind == Pc::Not && is_search_text_filter)+}++/// What a caller of a compound's tests says of one that decodes its component.+enum DecodedTest {+ /// It is tested.+ Run,+ /// It is taken to hold.+ Holds,+ /// It cannot be told, so neither can the compound's answer, unless another test fails.+ Unknown,+}++/// The dispatch bloom bits an element has to carry to match the first compound of `compound`: those of the ids and+/// classes it tests for.+fn required_dispatch_bloom(compound: Selector<'_>, context: MatchContext<'_>) -> u64 {+ // NB: The arena notes the bits of the names as written, which a document folding ids and classes folds first.+ if !context.fold_ids_and_classes {+ return compound.required_dispatch_bloom();+ }+ let folded = |name: crate::css::selector::NameSelector| match name.is_ascii_lowercase {+ true => name.name,+ false => crate::css::style::process_atoms().ascii_lowercase(name.name),+ };+ compound.ids_and_classes().fold(0, |bloom, name| match name {+ IdOrClass::Class(name) => bloom | dispatch_bloom_bit(DispatchKey::Class(folded(name))),+ IdOrClass::Id(name) => bloom | dispatch_bloom_bit(DispatchKey::Id(folded(name))),+ })+}++/// The axis from the anchor the subject of the relative selector `selector` is found on, and whether the subject+/// stands strictly below the elements the axis reaches.+pub(crate) fn relative_axis(selector: Selector<'_>) -> (super::relative_selector::RelativeAxis, bool) {+ use super::relative_selector::RelativeAxis;+ let descends = |combinator: Combinator| matches!(combinator, Combinator::Descendant | Combinator::ImmediateChild);+ // NB: Read from the subject leftwards, each compound's combinator relates it to the compound left of it: the+ // leftmost one's is the leading combinator, and the one read right before it is the first written after it.+ let mut first_later = None;+ let mut later_descends = false;+ let mut current = selector;+ let leading = loop {+ let combinator = current.first_compound().combinator;+ match current.left() {+ Some((_, left)) if !left.is_relative_anchor() => {+ later_descends |= descends(combinator);+ first_later = Some(combinator);+ current = left;+ }+ _ => break combinator,+ }+ };+ match leading {+ Combinator::ImmediateChild if !later_descends => (RelativeAxis::Child, false),+ Combinator::NextSibling if first_later.is_none() => (RelativeAxis::NextSibling, false),+ Combinator::NextSibling if first_later.is_some_and(descends) => (RelativeAxis::NextSiblingSubtree, true),+ Combinator::NextSibling | Combinator::SubsequentSibling => match later_descends {+ false => (RelativeAxis::FollowingSibling, false),+ true => (RelativeAxis::FollowingSiblingSubtree, true),+ },+ _ => (RelativeAxis::Descendant, false),+ }+}++/// The ranges of `scope.roots` and `scope.limits` that level `level` wrote.+fn scope_level_ranges(+ scope: &super::bridge::BoundScopeChain,+ level: usize,+) -> (std::ops::Range<usize>, std::ops::Range<usize>) {+ let (mut root_start, mut limit_start) = (0usize, 0usize);+ for (index, &(root_count, limit_count)) in scope.levels.iter().enumerate() {+ let root_end = (root_start + root_count as usize).min(scope.roots.len());+ let limit_end = (limit_start + limit_count as usize).min(scope.limits.len());+ if index == level {+ return (root_start..root_end, limit_start..limit_end);+ }+ root_start = root_end;+ limit_start = limit_end;+ }+ (0..0, 0..0)+}++/// The selector left of the first compound of `selector`, or none where that compound is the leftmost one written.+fn left_of(selector: Selector<'_>) -> Option<Selector<'_>> {+ selector+ .left()+ .map(|(_, left)| left)+ .filter(|left| !left.is_relative_anchor())+}++/// Whether a selector whose first compound in matching order, the one it ends in, is `last` targets a+/// pseudo-element: that compound is one after a pseudo-element combinator, other than `::part()` or `::slotted()`.+fn targets_a_pseudo_element(last: &CompoundRef<'_>) -> bool {+ last.combinator == Combinator::PseudoElement+ && matches!(+ compound_target(last),+ CompoundTarget::Transparent | CompoundTarget::Backed { .. }+ )+}++/// What the pseudo-element a compound starts with, if any, makes the compound describe.+pub(crate) enum CompoundTarget<'a> {+ /// The compound starts with none, and describes the element.+ Element,+ /// A pseudo-element no element stands for, of the element the compound left of it describes.+ Transparent,+ /// An element-backed pseudo-element, with pseudo-classes written after it that describe its element.+ Backed { kind: u16 },+ /// `::part()`, whose names the element exposed.+ Part { names: &'a [StyleAtomID] },+ /// `::slotted()`, whose argument, if it has one, describes the element.+ Slotted { argument: Option<Selector<'a>> },+}++/// See [`CompoundTarget`].+pub(crate) fn compound_target<'a>(compound: &CompoundRef<'a>) -> CompoundTarget<'a> {+ use crate::css::selector::{PseudoElementType, PseudoElementValue};+ let Some(SimpleSelector::PseudoElement(pseudo_element)) = compound.simple_selectors.first() else {+ return CompoundTarget::Element;+ };+ match pseudo_element.pseudo_element {+ PseudoElementType::Part => CompoundTarget::Part {+ names: pseudo_element.identifier_identities,+ },+ PseudoElementType::Slotted => CompoundTarget::Slotted {+ argument: match pseudo_element.value {+ PseudoElementValue::CompoundSelector(argument) => Some(argument),+ _ => None,+ },+ },+ other => {+ let kind = other as u16;+ let backed_kinds = u16::from(super::bridge::FIRST_ELEMENT_REFERENCE_PSEUDO_ELEMENT_KIND)+ ..=u16::from(super::bridge::LAST_ELEMENT_REFERENCE_PSEUDO_ELEMENT_KIND);+ match backed_kinds.contains(&kind) && !compound.simple_selectors.after_first().is_empty() {+ true => CompoundTarget::Backed { kind },+ false => CompoundTarget::Transparent,+ }+ }+ }+}++/// The kind of the element-backed pseudo-element a compound names, when it also writes pseudo-classes after it.+pub(crate) fn backed_pseudo_element_kind(compound: &CompoundRef<'_>) -> Option<u16> {+ match compound_target(compound) {+ CompoundTarget::Backed { kind } => Some(kind),+ _ => None,+ }+}++/// The names of a compound that starts with `::part()` and goes on with pseudo-classes only.+fn part_names<'a>(compound: &CompoundRef<'a>) -> Option<&'a [StyleAtomID]> {+ if compound.combinator != Combinator::PseudoElement {+ return None;+ }+ let CompoundTarget::Part { names } = compound_target(compound) else {+ return None;+ };+ compound+ .simple_selectors+ .after_first()+ .iter()+ .all(|simple| matches!(simple, SimpleSelector::PseudoClass(_)))+ .then_some(names)+}++/// The argument of a compound that is `::slotted()` alone, after the compounds naming the slot.+fn slotted_argument<'a>(compound: &CompoundRef<'a>) -> Option<Selector<'a>> {+ if compound.combinator != Combinator::PseudoElement || compound.simple_selectors.len() != 1 {+ return None;+ }+ match compound_target(compound) {+ CompoundTarget::Slotted { argument } => argument,+ _ => None,+ }+}++/// An indexed entry's selector, and what the rule it is of says about matching it.+#[derive(Clone, Copy)]+pub(crate) struct EntrySelector<'a> {+ pub(crate) selector: Selector<'a>,+ scope: Option<&'a super::bridge::BoundScopeChain>,+}++impl<'a> EntrySelector<'a> {+ /// The selector of an entry whose rule is inside the `@scope` levels `scope`, if any.+ pub(crate) fn new(selector: Selector<'a>, scope: Option<&'a super::bridge::BoundScopeChain>) -> Self {+ Self { selector, scope }+ }++ /// The selector of an entry whose rule is inside no `@scope`.+ pub(crate) fn unscoped(selector: Selector<'a>) -> Self {+ Self { selector, scope: None }+ }++ /// The `@scope` levels of the entry's rule, outermost first, or none outside any.+ pub(crate) fn scope(self) -> Option<&'a super::bridge::BoundScopeChain> {+ self.scope+ }++ /// What matching the selector in a document `document` describes needs to know.+ fn context(self, document: DocumentMatching) -> MatchContext<'a> {+ // NB: Only a default namespace is escaped, which few sheets declare.+ let escapes_its_namespace =+ self.selector.namespaces().default.is_some() && self.selector.escapes_its_namespace();+ MatchContext {+ html_namespace: document.html_namespace,+ fold_ids_and_classes: document.fold_ids_and_classes,+ namespaces: self.selector.namespaces(),+ escapes_its_namespace,+ logical_subject: false,+ }+ }+}++/// Whether the pseudo-class `kind` tests a state of the element.+pub(crate) fn names_a_state(kind: PseudoClassType) -> bool {+ super::compiler::state_fact_for(kind).is_some()+}++/// The state of the element the pseudo-class `kind` tests, where it tests one.+pub(crate) fn state_tested_by(kind: PseudoClassType) -> Option<super::input_types::StateFact> {+ super::compiler::state_fact_for(kind)+}++/// Whether `simple` holds a `:has()`, in itself or in a list it takes.+pub(crate) fn mentions_relative(simple: &SimpleSelector<'_>) -> bool {+ mentions(+ simple,+ &|simple| matches!(simple, SimpleSelector::PseudoClass(pseudo_class) if pseudo_class.pseudo_class == PseudoClassType::Has),+ )+}++/// Whether `simple` reads the scoping root, which an element's own facts do not tell: `:scope`, or a `&` naming it.+pub(crate) fn reads_the_scope_root(simple: &SimpleSelector<'_>) -> bool {+ mentions(simple, &|simple| match simple {+ SimpleSelector::PseudoClass(pseudo_class) => pseudo_class.pseudo_class == PseudoClassType::Scope,+ SimpleSelector::Nesting(Nesting::Root | Nesting::Scope) => true,+ _ => false,+ })+}++/// Whether `simple`, or a simple selector of a list it takes, is one `wanted` holds for.+pub(crate) fn mentions(simple: &SimpleSelector<'_>, wanted: &impl Fn(&SimpleSelector<'_>) -> bool) -> bool {+ if wanted(simple) {+ return true;+ }+ let in_selector = |selector: Selector<'_>| {+ selector+ .compounds()+ .any(|compound| compound.simple_selectors.iter().any(|simple| mentions(&simple, wanted)))+ };+ simple.nested().any(in_selector)+}++/// What matching in a document needs to know of it.+#[derive(Clone, Copy)]+pub(crate) struct DocumentMatching {+ /// The HTML namespace in an HTML document, and none in any other.+ pub(crate) html_namespace: StyleAtomID,+ /// Whether ids and classes compare ASCII case-insensitively, as in a quirks-mode document.+ pub(crate) fold_ids_and_classes: bool,+}++impl<S: SelectorSubject> SelectorEvaluator<S> {+ /// Whether `node` matches the selector of an entry, inside the `@scope` levels of its rule.+ pub(crate) fn matches_entry_selector(+ &mut self,+ entry: EntrySelector<'_>,+ node: S::Node,+ document: DocumentMatching,+ ) -> Answer<S> {+ let context = entry.context(document);+ self.bindings.matched_scope_root = None;+ match entry.scope {+ Some(scope) => {+ let names_the_scope = entry.selector.names_the_scope();+ self.matches_scope_level(scope, 0, entry.selector, names_the_scope, node, context)+ }+ None => self.matches_selector(entry.selector, node, context),+ }+ }++ /// Whether `node`, known to match the subject compound of the unscoped selector of `entry`, matches what is left+ /// of it.+ pub(crate) fn matches_left_of_subject(+ &mut self,+ entry: EntrySelector<'_>,+ node: S::Node,+ document: DocumentMatching,+ ) -> Answer<S> {+ let context = entry.context(document);+ self.bindings.matched_scope_root = None;+ Ok(self.walk_left_of(entry.selector, None, node, context)? == Walk::Matched)+ }++ /// Whether `node` matches the first compound of `compound`, a compound of the selector of `entry` or of one+ /// nested in it, on its own: whatever the elements its combinators reach match. None where that cannot be told+ /// from the element alone: the compound reads the scoping root, or what the subject does not know.+ ///+ /// Where `around_relative`, the `:has()` of the compound are taken to match. The argument of a `::slotted()`+ /// describes the element, and the pseudo-classes after an element-backed pseudo-element the element backing it.+ pub(crate) fn matches_compound_alone(+ &mut self,+ entry: EntrySelector<'_>,+ compound: Selector<'_>,+ node: S::Node,+ document: DocumentMatching,+ around_relative: bool,+ ) -> Option<bool> {+ if compound.is_relative_anchor() {+ return None;+ }+ let context = entry.context(document);+ let first = compound.first_compound();+ // NB: Only a compound starting with a pseudo-element, which the first component's kind tells+ // without decoding it, describes another element than its own.+ let may_lead_with_a_pseudo_element = matches!(+ first.simple_selectors.views().next(),+ Some(crate::css::selector_arena::SimpleView::Other(_))+ );+ let simple_selectors = match may_lead_with_a_pseudo_element.then(|| compound_target(&first)) {+ Some(CompoundTarget::Slotted {+ argument: Some(argument),+ }) => argument.first_compound().simple_selectors,+ // NB: Whether the host the rule names is exposed the part is left to the restyle.+ Some(CompoundTarget::Part { names }) => {+ let row = self.subject.row(node).ok()?;+ if !names.iter().all(|&part| self.subject.has_part(row, part)) {+ return Some(false);+ }+ first.simple_selectors.after_first()+ }+ Some(CompoundTarget::Backed { .. }) => first.simple_selectors.after_first(),+ Some(CompoundTarget::Transparent | CompoundTarget::Slotted { argument: None }) => return Some(true),+ Some(CompoundTarget::Element) | None => first.simple_selectors,+ };+ if let Some(shadow_root) = self.bindings.scope_shadow_root+ && self.subject.tree().shadow_root_of(node) == Some(shadow_root)+ && !self.bindings.matching_host_argument+ {+ if simple_selectors.iter().any(|simple| reads_the_scope_root(&simple)) {+ return None;+ }+ return self.matches_featureless_host_components(&first, node, context).ok();+ }+ let known = match self.test_components(simple_selectors, node, context, true, |simple| match () {+ _ if around_relative && mentions_relative(simple) => DecodedTest::Holds,+ _ if reads_the_scope_root(simple) => DecodedTest::Unknown,+ _ => DecodedTest::Run,+ }) {+ Ok(Some(false)) => return Some(false),+ Ok(Some(true)) => true,+ Ok(None) | Err(_) => false,+ };+ let compound = CompoundRef {+ simple_selectors,+ ..first+ };+ match self.is_outside_the_default_namespace(&compound, false, node, context) {+ Ok(true) => Some(false),+ Ok(false) => known.then_some(true),+ Err(_) => None,+ }+ }++ /// Whether an element relative to `anchor` matches `argument`, a relative selector of a `:has()` in the selector+ /// of `entry`, walking the shadow tree `anchor` hosts where `in_shadow_tree`.+ pub(crate) fn matches_relative_query(+ &mut self,+ entry: EntrySelector<'_>,+ argument: Selector<'_>,+ in_shadow_tree: bool,+ anchor: S::Node,+ document: DocumentMatching,+ ) -> Answer<S> {+ let context = entry.context(document);+ let within = match in_shadow_tree {+ true => match self.subject.tree().shadow_root_of(anchor) {+ Some(shadow_root) => shadow_root,+ None => return Ok(false),+ },+ false => anchor,+ };+ self.matches_relative_selector(argument, anchor, within, context)+ }++ /// How far `node`, which the last entry asked for matched, is from the scoping root of the scope it matched in:+ /// the hops up to it, or infinitely far for an entry no `@scope` constrains.+ ///+ /// https://drafts.csswg.org/css-cascade-6/#cascade-proximity+ pub(crate) fn scope_proximity_of_match(&self, node: S::Node) -> u32 {+ let Some(root) = self.bindings.matched_scope_root else {+ return u32::MAX;+ };+ let tree = self.subject.tree();+ let mut proximity = 0;+ let mut candidate = Some(node);+ while let Some(current) = candidate {+ if current == root {+ return proximity;+ }+ proximity += 1;+ candidate = tree+ .live_parent(current)+ .map(|parent| tree.host_of(parent).unwrap_or(parent));+ }+ u32::MAX+ }+}++/// https://drafts.csswg.org/css-namespaces/#css-qnames+/// A qualified name with a prefix that has not been previously declared as a namespace prefix is invalid. The parser+/// rejects such a selector, so one that reaches matching anyway matches nothing rather than every namespace.+pub(crate) struct UndeclaredPrefix;++impl crate::css::selector_arena::SheetNamespaces<'_> {+ /// The namespace a qualified name constrains its subject to, none being the absence of one, where it constrains+ /// it at all, or an error for a prefix the sheet never declared. The empty string is the namespace an element in no+ /// namespace has, so declaring it names exactly those.+ pub(crate) fn test_for(+ self,+ namespace_type: NamespaceType,+ prefix: Option<StyleAtomID>,+ ) -> Result<Option<StyleAtomID>, UndeclaredPrefix> {+ Ok(match namespace_type {+ // `*|x` names every namespace, so it constrains nothing.+ NamespaceType::Any => None,+ // `|x` names the absence of one.+ NamespaceType::None => Some(StyleAtomID::NONE),+ NamespaceType::Default => self.default,+ NamespaceType::Named => prefix+ .and_then(|prefix| self.namespace_of(prefix))+ .ok_or(UndeclaredPrefix)?+ .into(),+ })+ }+}diff --git a/Libraries/LibWeb/Rust/src/css/style/container_queries.rs b/Libraries/LibWeb/Rust/src/css/style/container_queries.rsindex e7a0cb91af0..2724d972604 100644--- a/Libraries/LibWeb/Rust/src/css/style/container_queries.rs+++ b/Libraries/LibWeb/Rust/src/css/style/container_queries.rs@@ -11,14 +11,12 @@ use super::bridge::FfiContainerEffectKind;use super::tree::StyleNodeID;use super::*;use crate::css::computed_longhand_table::FONT_METRICS_DEPEND_ON_VIEWPORT_METRICS;-use crate::css::custom_properties::StyleQueryDependencies;use crate::css::parser::query_parser::{CONTAINER_QUERY_HAS_UNKNOWN_FEATURE, CONTAINER_QUERY_REQUIRES_BLOCK_SIZE, CONTAINER_QUERY_REQUIRES_HEIGHT,CONTAINER_QUERY_REQUIRES_INLINE_SIZE, CONTAINER_QUERY_REQUIRES_SCROLL_STATE, CONTAINER_QUERY_REQUIRES_STYLE,- CONTAINER_QUERY_REQUIRES_WIDTH, FfiContainerFacts, FfiQueryHandle, MatchResult, SCROLL_STATE_SIDE_BOTTOM,+ CONTAINER_QUERY_REQUIRES_WIDTH, ContainerFacts, FfiQueryHandle, MatchResult, SCROLL_STATE_SIDE_BOTTOM,SCROLL_STATE_SIDE_LEFT, SCROLL_STATE_SIDE_RIGHT, SCROLL_STATE_SIDE_TOP,};-use smallvec::SmallVec;/// What a rule's container conditions say for one subject: whether they hold, whether they ask/// about a container's size, scroll state or style, and what the evaluation read of the@@ -28,25 +26,12 @@ pub(crate) struct ContainerVerdict {pub(crate) matches: bool,pub(crate) depends_on_size: bool,pub(crate) depends_on_style: bool,+ /// Whether a query was evaluated, whose lengths may be relative to the root element's font.+ pub(crate) reads_root_font: bool,+ /// The containers a query was evaluated against, whose first available font's metrics the+ /// query's `ex`, `cap`, `ch` and `lh` lengths resolve against.+ pub(crate) font_metric_containers: Vec<StyleNodeID>,pub(crate) effects: Vec<(StyleNodeID, FfiContainerEffectKind)>,- /// The custom properties the conditions' `style()` features read of the containers, which- /// the host records as the subject's style query references.- pub(crate) style_query_references: Option<Box<StyleQueryDependencies>>,-}--/// What a gated rule's container conditions said for a node's element, or for one of its-/// pseudo-elements, when the node's winners were published: they hold its declarations exactly-/// where the conditions held.-#[derive(Clone, Copy, Debug, PartialEq)]-pub(super) struct PublishedContainerVerdict {- pub(super) rule: RuleID,- /// Whether the rule targets a pseudo-element, whose conditions ask about the originating- /// element first.- pub(super) pseudo: bool,- /// Whether its conditions held, `None` where the engine could not decide them: the winners- /// hold its declarations exactly where it held, and an undecided one leaves the node to the- /// host.- pub(super) held: Option<bool>,}impl ContainerVerdict {@@ -54,13 +39,13 @@ impl ContainerVerdict {pub(crate) fn add_reads(&mut self, other: ContainerVerdict) {self.depends_on_size |= other.depends_on_size;self.depends_on_style |= other.depends_on_style;- self.effects.extend(other.effects);- if let Some(references) = other.style_query_references {- match &mut self.style_query_references {- Some(noted) => noted.extend(&references),- noted => *noted = Some(references),+ self.reads_root_font |= other.reads_root_font;+ for container in other.font_metric_containers {+ if !self.font_metric_containers.contains(&container) {+ self.font_metric_containers.push(container);}}+ self.effects.extend(other.effects);}}@@ -111,6 +96,79 @@ impl ContainerUnitBases {}}+/// Where container queries and container-relative lengths read what the elements above their+/// subject are as query containers: the records the host installed, or a style pass's records,+/// falling back to the installed ones for the elements the pass did not compute.+pub(in crate::css::style) trait ContainerRecords {+ /// Whether, and as what, an element is a query container.+ fn query_row(&self, node: StyleNodeID) -> Option<tree::ContainerQueryInputs<'_>>;++ /// What an element that is no query container is as the style container every element is,+ /// which a query asking only about style asks about. `None` where the element holds no style+ /// yet.+ fn any_element_row(&self, node: StyleNodeID) -> Option<tree::ContainerQueryInputs<'_>>;++ /// The style of a container `row` describes, which a query's lengths and colors compute as.+ fn record_view(+ &self,+ node: StyleNodeID,+ row: tree::ContainerQueryInputs<'_>,+ ) -> Option<computed::StyleRecordView<'_>>;++ /// The custom properties of a container `row` describes, which a `style()` feature reads, or+ /// `None` where they are not known.+ fn custom_store(+ &self,+ node: StyleNodeID,+ row: tree::ContainerQueryInputs<'_>,+ ) -> Option<Option<&crate::css::custom_properties::CustomPropertyStore>>;++ /// The font a `rem` in a query resolves against where it is not the one the document's inputs+ /// say: the font of the document element as the records hold it.+ fn root_font(&self) -> Option<super::pipeline::compute::RootFontInputs> {+ None+ }+}++impl ContainerRecords for RetainedState {+ fn query_row(&self, node: StyleNodeID) -> Option<tree::ContainerQueryInputs<'_>> {+ self.container_query_inputs(node)+ }++ /// One holding no record yet is one the host styles in this update, which decides it. One+ /// this batch settled is read as the host will leave it, as a query container is.+ fn any_element_row(&self, node: StyleNodeID) -> Option<tree::ContainerQueryInputs<'_>> {+ self.container_query_input_row(node, self.container_style_record(node)?, true)+ }++ fn record_view(+ &self,+ _node: StyleNodeID,+ row: tree::ContainerQueryInputs<'_>,+ ) -> Option<computed::StyleRecordView<'_>> {+ self.computed_group_sets.style_record_view(row.style_record)+ }++ /// The environment the element's animations sample where they do, else its record's.+ fn custom_store(+ &self,+ node: StyleNodeID,+ row: tree::ContainerQueryInputs<'_>,+ ) -> Option<Option<&crate::css::custom_properties::CustomPropertyStore>> {+ let environment = match self.element_custom_property_data.get(&node) {+ Some(held) if held.sampled_over.is_some() => held.identity,+ _ => self+ .computed_group_sets+ .style_record_custom_property_environment(row.style_record)+ .unwrap_or_default(),+ };+ match environment {+ 0 => Some(None),+ identity => Some(Some(&**self.custom_property_environments.store(identity)?)),+ }+ }+}+/// What a `style()` feature reads of the container it asks about: the custom-property/// environment of its record, and lengths and colors as the record computes them.struct RetainedContainerStyleContext<'a> {@@ -123,7 +181,7 @@ struct RetainedContainerStyleContext<'a> {}/// Whether one of the container conditions asks a `style()` question.-fn conditions_ask_container_style(+pub(super) fn conditions_ask_container_style(containers: &[std::sync::Arc<crate::css::container_conditions::ContainerConditionsData>],) -> bool {containers.iter().any(|conditions| {@@ -136,14 +194,6 @@ fn conditions_ask_container_style(})}-/// Which of a node's container verdicts a check covers. The verdicts of its pseudo-elements ask-/// about the element's own record first, so they are decided once that record is settled.-#[derive(Clone, Copy, PartialEq, Eq)]-pub(super) enum VerdictTargets {- Element,- ElementAndPseudoElements,-}-impl RetainedState {/// What lengths resolve against as a record computes them, as the host takes them from an/// element's computed style: the record's font metrics and writing mode, the root's font@@ -151,27 +201,27 @@ impl RetainedState {/// against. `None` for a record without a font.pub(super) fn record_length_resolution_context(&self,- view: &computed::StyleRecordView<'_>,+ payloads: &crate::css::computed_values::StyleGroups,+ dependency_flags: u8,) -> Option<crate::css::style_compute::FfiLengthResolutionContext> {let document = &self.document_style_computation_inputs;let font = unsafe {- view.payloads[crate::css::computed_value_types::STYLE_GROUP_INDEX_FONT]+ payloads[crate::css::table_group_builder::group_index::FONT].cast::<crate::css::computed_value_types::FontValues>().as_ref()}?;- let values = crate::css::computed_value_views::ComputedValuesView::new(- crate::css::host_shared::SharedPayload::as_pointer_slice(view.payloads),- );+ let values = crate::css::computed_value_views::ComputedValuesView::of(payloads);+ let first_available = font.first_available_font_metrics();Some(crate::css::style_compute::FfiLengthResolutionContext {viewport_width: document.viewport_width,viewport_height: document.viewport_height,font_metrics: crate::css::style_compute::FfiFontMetrics {font_size: font.font_size.to_double(),- x_height: super::publication::drive_font_metric(font.font_x_height),+ x_height: super::pipeline::drive::drive_font_metric(first_available.x_height),// The C++ metrics approximate the cap height with the ascent.- cap_height: super::publication::drive_font_metric(font.font_ascent),- zero_advance: super::publication::drive_font_metric(font.font_zero_advance),- line_height: font.line_height_used.to_double(),+ cap_height: super::pipeline::drive::drive_font_metric(first_available.ascent),+ zero_advance: super::pipeline::drive::drive_font_metric(first_available.zero_advance),+ line_height: font.line_height_used().to_double(),},root_font_metrics: crate::css::style_compute::FfiFontMetrics {font_size: document.root_font_size,@@ -180,8 +230,7 @@ impl RetainedState {zero_advance: document.root_font_zero_advance,line_height: document.root_line_height,},- font_metrics_depend_on_viewport_metrics: view.dependency_flags & FONT_METRICS_DEPEND_ON_VIEWPORT_METRICS- != 0,+ font_metrics_depend_on_viewport_metrics: dependency_flags & FONT_METRICS_DEPEND_ON_VIEWPORT_METRICS != 0,root_font_metrics_depend_on_viewport_metrics: document.root_font_metrics_depend_on_viewport_metrics,has_container_width_basis: false,has_container_height_basis: false,@@ -207,10 +256,8 @@ impl RetainedState {let Some(view) = self.computed_group_sets.style_record_view(style_record) else {return to_color(value, &EMPTY_INPUT);};- let length = self.record_length_resolution_context(&view);- let values = crate::css::computed_value_views::ComputedValuesView::new(- crate::css::host_shared::SharedPayload::as_pointer_slice(view.payloads),- );+ let length = self.record_length_resolution_context(view.payloads, view.dependency_flags);+ let values = crate::css::computed_value_views::ComputedValuesView::of(view.payloads);let input = ColorResolutionInput {length: length.as_ref(),..ColorResolutionInput::for_style(values)@@ -221,6 +268,7 @@ impl RetainedState {/// The basis of one physical axis for a subject's container-relative lengths.fn container_unit_basis(&self,+ records: &impl ContainerRecords,subject: StyleNodeID,axis_is_horizontal: bool,subject_is_pseudo_element: bool,@@ -231,11 +279,11 @@ impl RetainedState {let mut ancestor = if subject_is_pseudo_element {Some(subject)} else {- self.tree.flat_tree_parent(subject)+ self.projection.flat_tree_parent(subject)};while let Some(node) = ancestor {- ancestor = self.tree.flat_tree_parent(node);- let Some(inputs) = self.container_query_inputs(node) else {+ ancestor = self.projection.flat_tree_parent(node);+ let Some(inputs) = records.query_row(node) else {continue;};// The container's own writing mode decides which of its axes is the inline one, the@@ -284,65 +332,25 @@ impl RetainedState {subject: StyleNodeID,subject_is_pseudo_element: bool,) -> ContainerUnitBases {- ContainerUnitBases([- self.container_unit_basis(subject, true, subject_is_pseudo_element),- self.container_unit_basis(subject, false, subject_is_pseudo_element),- ])+ self.container_unit_bases_with(self, subject, subject_is_pseudo_element)}- /// Keep what the container-relative lengths of a record the engine computed from `state` read- /// of the subject's containers for the host, which records it when it installs the record as- /// it does when it resolves them itself: the subject depends on its containers' sizes, each- /// container a basis is read from is asked about, one without a box is evaluated again after- /// layout, and a basis read from the viewport makes the subject depend on it.- pub(super) fn note_container_unit_effects_for_host(- &mut self,- node: StyleNodeID,- pseudo: bool,- state: CascadeStateID,- old_record: computed::FinalStyleRecordID,- ) {- // The units a substitution produced are no winner's: they are noted with the node.- let substituted_units = self- .nodes_with_element_relative_substitutions- .get(&node)- .map_or(0, |substitutions| substitutions.container_units);- if self.state_reads(node, state) & cascade::STATE_READS_CONTAINER_UNITS == 0 && substituted_units == 0 {- return;- }- // The writing mode the drive computed against decides which physical axes its logical- // units read: the record it drove again, else the parent's, which for a pseudo-element is- // its originating element's.- let axis_record = Some(old_record)- .filter(|record| *record != computed::FinalStyleRecordID::NONE)- .or_else(|| {- let parent = if pseudo {- Some(node)- } else {- self.tree.inheritance_parent(node)- };- self.computed_group_sets.assigned_style_record(parent?)- });- let inline_axis_is_horizontal = axis_record- .and_then(|record| self.computed_group_sets.style_record_view(record.raw()))- .is_none_or(|view| {- crate::css::computed_value_views::ComputedValuesView::new(- crate::css::host_shared::SharedPayload::as_pointer_slice(view.payloads),- )- .writing_mode()- == crate::css::css_enums::writing_mode::HORIZONTAL_TB- });- self.note_container_unit_reads_for_host(- node,- self.state_container_unit_mask(node, state) | substituted_units,- inline_axis_is_horizontal,- pseudo,- );+ /// The bases of both physical axes for a subject's container-relative lengths, against the+ /// query containers `records` holds.+ pub(super) fn container_unit_bases_with(+ &self,+ records: &impl ContainerRecords,+ subject: StyleNodeID,+ subject_is_pseudo_element: bool,+ ) -> ContainerUnitBases {+ ContainerUnitBases([+ self.container_unit_basis(records, subject, true, subject_is_pseudo_element),+ self.container_unit_basis(records, subject, false, subject_is_pseudo_element),+ ])}/// Keep for the host what container-relative units of `unit_mask` read of the subject's- /// containers, for a subject whose inline axis is or is not the horizontal one, as- /// `note_container_unit_effects_for_host` says.+ /// containers, for a subject whose inline axis is or is not the horizontal one.pub(super) fn note_container_unit_reads_for_host(&mut self,node: StyleNodeID,@@ -360,7 +368,7 @@ impl RetainedState {if !reads {continue;}- let basis = self.container_unit_basis(node, axis_is_horizontal, subject_is_pseudo_element);+ let basis = self.container_unit_basis(self, node, axis_is_horizontal, subject_is_pseudo_element);match basis.container {Some(container) => {verdict@@ -377,27 +385,26 @@ impl RetainedState {.push((node, FfiContainerEffectKind::SubjectViewportDependency)),}}- self.note_container_effects_for_host(node, verdict);+ self.note_container_effects_for_host(node, &std::sync::Arc::new(verdict));}- /// Evaluate a rule's container conditions for a subject, as the host evaluates them. `None`- /// when the engine cannot decide them: the rule has no target, or a container it asks about- /// holds no record or custom-property environment to read.- pub(crate) fn rule_container_verdict(+ /// Evaluate container conditions for a subject, as the host evaluates them: a rule's, or those+ /// around a block of a custom function's declarations. `None` when the engine cannot decide+ /// them.+ pub(super) fn container_conditions_verdict(&self,- rule: RuleID,+ containers: &[std::sync::Arc<crate::css::container_conditions::ContainerConditionsData>],subject: StyleNodeID,subject_is_pseudo_element: bool,) -> Option<ContainerVerdict> {- let containers = self.native_rules.targets.get(&rule)?.containers();- self.container_conditions_verdict(containers, subject, subject_is_pseudo_element)+ self.container_conditions_verdict_with(self, containers, subject, subject_is_pseudo_element)}- /// Evaluate container conditions for a subject, as the host evaluates them: a rule's, or those- /// around a block of a custom function's declarations. `None` when the engine cannot decide- /// them, as for `rule_container_verdict`.- pub(super) fn container_conditions_verdict(+ /// Evaluate container conditions for a subject as `container_conditions_verdict` does, over+ /// the containers `records` holds.+ pub(super) fn container_conditions_verdict_with(&self,+ records: &impl ContainerRecords,containers: &[std::sync::Arc<crate::css::container_conditions::ContainerConditionsData>],subject: StyleNodeID,subject_is_pseudo_element: bool,@@ -416,6 +423,7 @@ impl RetainedState {for condition in &conditions.conditions {let name = condition.name.as_ref().map_or(&[][..], |name| name.units());if self.container_condition_matches(+ records,subject,subject_is_pseudo_element,condition.query.as_deref(),@@ -439,6 +447,7 @@ impl RetainedState {/// the last layout commit.fn container_condition_matches(&self,+ records: &impl ContainerRecords,subject: StyleNodeID,subject_is_pseudo_element: bool,query: Option<&FfiQueryHandle>,@@ -452,7 +461,7 @@ impl RetainedState {let mut container = if subject_is_pseudo_element {Some(subject)} else {- self.tree.flat_tree_parent(subject)+ self.projection.flat_tree_parent(subject)};// A query asking only about style, by no name, may ask any element.let asks_only_style = name.is_empty()@@ -463,26 +472,16 @@ impl RetainedState {| CONTAINER_QUERY_REQUIRES_BLOCK_SIZE| CONTAINER_QUERY_REQUIRES_SCROLL_STATE)== 0;- let mut any_element_row;while let Some(candidate) = container {- container = self.tree.flat_tree_parent(candidate);- let inputs = match self.container_query_inputs(candidate) {+ container = self.projection.flat_tree_parent(candidate);+ let inputs = match records.query_row(candidate) {Some(inputs) => inputs,- // Every element is a style container, so the nearest one is the container; one- // holding no record yet is one the host styles in this update, which decides it.- // One this batch settled is read as the host will leave it, as a query container is.- None if asks_only_style => {- let style_record = self- .computed_group_sets- .assigned_style_record(candidate)- .map(|record| record.raw())- .or_else(|| self.held_style_records.get(&candidate).copied())?;- any_element_row = self.container_query_input_row(candidate, style_record, true);- any_element_row.as_ref()?- }+ // Every element is a style container, so the nearest one is the container, which+ // the records may not decide yet.+ None if asks_only_style => records.any_element_row(candidate)?,None => continue,};- if !name.is_empty() && !inputs.names.iter().any(|candidate| candidate == name) {+ if !name.is_empty() && !inputs.is_named(name) {continue;}let inline_axis_horizontal = inputs.writing_mode == crate::css::css_enums::writing_mode::HORIZONTAL_TB;@@ -508,13 +507,25 @@ impl RetainedState {let Some(query) = query else {return Some(true);};+ // A `rem` in the query resolves against the root element's font, and an `ex`, `cap`,+ // `ch` or `lh` against the container's.+ verdict.reads_root_font = true;+ if !verdict.font_metric_containers.contains(&candidate) {+ verdict.font_metric_containers.push(candidate);+ }let snapshot = self.layout_style_snapshot(candidate).unwrap_or_default();let document = &self.document_style_computation_inputs;- let view = self.computed_group_sets.style_record_view(inputs.style_record)?;- let mut length = self.record_length_resolution_context(&view)?;+ let view = records.record_view(candidate, inputs)?;+ let mut length = self.record_length_resolution_context(view.payloads, view.dependency_flags)?;+ if let Some(root_font) = records.root_font() {+ (+ length.root_font_metrics,+ length.root_font_metrics_depend_on_viewport_metrics,+ ) = root_font.font_metrics();+ }// A container-relative length in the query resolves against the container's own query// container, the nearest above it eligible for the axis, or the viewport.- let bases = self.container_unit_bases(candidate, false);+ let bases = self.container_unit_bases_with(records, candidate, false);bases.apply_to(&mut length);let mut resolved_viewport_relative_length = false;length.subject_inline_axis_is_horizontal = inline_axis_horizontal;@@ -536,20 +547,8 @@ impl RetainedState {// as the container's record computes them.let mut style_context = None;if requirements & CONTAINER_QUERY_REQUIRES_STYLE != 0 {- let environment = match self.element_custom_property_data.get(&candidate) {- Some(held) if held.sampled_over.is_some() => held.identity,- _ => self- .computed_group_sets- .style_record_custom_property_environment(inputs.style_record)- .unwrap_or_default(),- };- let store = match environment {- 0 => None,- identity => Some(&**self.custom_property_environments.store(identity)?),- };- let values = crate::css::computed_value_views::ComputedValuesView::new(- crate::css::host_shared::SharedPayload::as_pointer_slice(view.payloads),- );+ let store = records.custom_store(candidate, inputs)?;+ let values = crate::css::computed_value_views::ComputedValuesView::of(view.payloads);let inherited_text = values.inherited_text();style_context = Some(RetainedContainerStyleContext {store,@@ -566,7 +565,7 @@ impl RetainedState {.map(|position| (u64::from(position.count), u64::from(position.index))),});}- let facts = FfiContainerFacts {+ let facts = ContainerFacts {container_available: true,size_available: snapshot.has_committed_box && inputs.size_queries_available,width: crate::css::css_pixels::CssPixels::from_raw(snapshot.content_width_raw).to_double(),@@ -628,7 +627,6 @@ impl RetainedState {.effects.push((candidate, FfiContainerEffectKind::NeedsEvaluationAfterLayout));}- let references = &mut verdict.style_query_references;// SAFETY: The facts' length context is live for the call.let result = unsafe {crate::css::parser::query_parser::evaluate_container_query(query, &facts, &mut |feature| {@@ -642,7 +640,6 @@ impl RetainedState {&length,context.color,context.tree_counting,- references,)})};@@ -658,12 +655,19 @@ impl RetainedState {/// Keep what a row the engine answers read of its containers for the host, which records it/// when it installs the element's record, as it does for a row it computes itself.- pub(super) fn note_container_effects_for_host(&mut self, node: StyleNodeID, verdict: ContainerVerdict) {+ pub(super) fn note_container_effects_for_host(+ &mut self,+ node: StyleNodeID,+ verdict: &std::sync::Arc<ContainerVerdict>,+ ) {self.container_effects_for_host.note(node, verdict);}/// What the rows the host installs read of their containers, taken as it installs each.- pub(crate) fn take_container_effects_for_host(&mut self, node: StyleNodeID) -> Option<ContainerVerdict> {+ pub(crate) fn take_container_effects_for_host(+ &mut self,+ node: StyleNodeID,+ ) -> Option<std::sync::Arc<ContainerVerdict>> {self.container_effects_for_host.set(node, None)}@@ -682,232 +686,6 @@ impl RetainedState {debug_assert!(self.container_effects_for_host.effects.is_empty());self.container_effects_for_host.held = flag;}-- /// Whether the winners published for a node hold a rule's container conditions: they hold a- /// gated rule, the element's or a pseudo-element's, where its conditions held when they were- /// published, and the record loop checks that they still do.- pub(crate) fn container_gate_is_held(&self, node: Option<StyleNodeID>, rule: RuleID) -> bool {- !self.program.rule_is_gated_by_container_query(rule)- || node.is_some_and(|node| !self.container_gates_unheld.contains(&node))- }-- /// Whether one of a rule's container conditions asks a `style()` question, which every- /// element above the subject may answer.- fn rule_asks_container_style(&self, rule: RuleID) -> bool {- self.native_rules- .targets- .get(&rule)- .is_some_and(|target| conditions_ask_container_style(target.containers()))- }-- /// Decide, as a node's winners are published, whether its gated rules can be: their- /// conditions read the containers above it, which are final only when no ancestor's answer- /// moves in the same transaction.- pub(super) fn note_container_gates_for_publication(&mut self, node: StyleNodeID, effects: &AnswerEffects) {- if self.container_ancestor_answer_moves(node, effects) {- self.container_gates_unheld.insert(node);- } else {- self.container_gates_unheld.remove(&node);- }- }-- /// Whether an ancestor's answer moves in the transaction `effects` belong to: the containers- /// above `node` are not final then, and neither are its gated rules' conditions.- pub(super) fn container_ancestor_answer_moves(&self, node: StyleNodeID, effects: &AnswerEffects) -> bool {- let mut ancestor = self.tree.flat_tree_parent(node);- while let Some(current) = ancestor {- if effects.lookup(current).is_some() {- return true;- }- ancestor = self.tree.flat_tree_parent(current);- }- false- }-- /// A node whose gated rules decide differently over the containers as they stand now than- /// when its winners were published has its winners published again from its retained- /// selector answer, without matching its selectors again. Where no answer says what the node- /// matches, or this transaction replaces rules that answer may name, the winners are dropped- /// instead, and the node is published anew when it is matched.- pub(super) fn refresh_winners_whose_container_verdicts_moved(- &mut self,- rule_program_is_changing: bool,- republication: super::publication::WinnerRepublication,- ) {- if self.published_container_verdicts.is_empty() {- return;- }- let moved: Vec<StyleNodeID> = self- .published_container_verdicts- .keys()- .copied()- .filter(|&node| self.container_verdicts_moved(node))- .collect();- for node in moved {- if rule_program_is_changing || self.republish_winners_from_answer(node, republication).is_none() {- self.published_container_verdicts.remove(&node);- self.winner_groups.remove(node);- }- }- }-- /// Whether one of the gated rules of a node's winners decides differently now than when they- /// were published. One the engine could not decide then, and still cannot, has not moved:- /// the record loop leaves that node to the host without publishing its winners again.- pub(super) fn container_verdicts_moved(&self, node: StyleNodeID) -> bool {- self.published_container_verdicts.get(&node).is_some_and(|verdicts| {- verdicts.iter().any(|verdict| {- self.rule_container_verdict(verdict.rule, node, verdict.pseudo)- .map(|now| now.matches)- != verdict.held- })- })- }-- /// Note for the host what the conditions of the node's pseudo-element verdicts read of the- /// containers, decided over the element's record as it stands now.- pub(super) fn note_pseudo_container_effects_for_host(&mut self, node: StyleNodeID) {- let Some(published) = self.published_container_verdicts.get(&node) else {- return;- };- let verdicts: SmallVec<[ContainerVerdict; 2]> = published- .iter()- .filter(|verdict| verdict.pseudo)- .filter_map(|verdict| self.rule_container_verdict(verdict.rule, node, true))- .collect();- for verdict in verdicts {- self.note_container_effects_for_host(node, verdict);- }- }-- /// Whether a node's winners are not the ones its gated rules decide now: they were published- /// while an ancestor's answer was moving, or a verdict moved since.- pub(super) fn container_winners_are_stale(&self, node: StyleNodeID) -> bool {- self.container_gates_unheld.contains(&node) || self.container_verdicts_moved(node)- }-- /// Whether a moved container reaches a node's record past the verdicts of its gated rules,- /// which the record loop decides again: a winner of the element or of one of its- /// pseudo-elements measures the containers through a container-relative length, or may- /// through a substitution, and no winner shows it. A node whose winners hold no gated rule- /// asks about its containers only through such values.- pub(super) fn container_input_drives_in_full(&self, node: StyleNodeID) -> bool {- if !self.published_container_verdicts.contains_key(&node) {- return true;- }- let winners = self.current_winner_groups();- let Lookup::Known((_, state)) = winners.token_for(WinnerGroupKey::current(node, self.program.version())) else {- return true;- };- std::iter::once(state)- .chain(winners.pseudo_states(node).map(|(_, _, state, _)| state))- .any(|state| {- self.state_has_substitutions(node, state)- || self.state_reads(node, state) & cascade::STATE_READS_CONTAINER_UNITS != 0- })- }-- /// Whether a rule decides for the node's element, or for one of its pseudo-elements, as far- /// as its container conditions go: an ungated rule always does, a gated one where they held- /// for that target when the node's winners were published.- pub(crate) fn published_container_verdict_holds(&self, node: StyleNodeID, rule: RuleID, pseudo: bool) -> bool {- !self.program.rule_is_gated_by_container_query(rule)- || self.published_container_verdicts.get(&node).is_some_and(|verdicts| {- verdicts- .iter()- .any(|verdict| verdict.rule == rule && verdict.pseudo == pseudo && verdict.held == Some(true))- })- }-- pub(super) fn publish_container_verdicts(&mut self, node: StyleNodeID, verdicts: Vec<PublishedContainerVerdict>) {- if verdicts.is_empty() {- self.published_container_verdicts.remove(&node);- } else {- self.published_container_verdicts.insert(node, verdicts);- }- }-- /// Whether every gated rule of a node's winners decides now as it did when they were published,- /// over its containers as its settled ancestors left them. What the evaluations read of the- /// containers is kept for the host, which records it with the node's record. An undecided one- /// never stands: the winners hold the rule nowhere, which may not be where it holds.- pub(super) fn container_verdicts_stand(&mut self, node: StyleNodeID, targets: VerdictTargets) -> bool {- let Some(published) = self.published_container_verdicts.get(&node) else {- return true;- };- let mut verdicts = Vec::with_capacity(published.len());- for published in published {- if published.pseudo && targets == VerdictTargets::Element {- continue;- }- match self.rule_container_verdict(published.rule, node, published.pseudo) {- Some(verdict) if published.held == Some(verdict.matches) => verdicts.push(verdict),- _ => return false,- }- }- for verdict in verdicts {- self.note_container_effects_for_host(node, verdict);- }- true- }-- /// Whether a flat-tree ancestor of the node the conditions can ask about was declined in this- /// batch: the record the host computes for it is installed after the batch, and so are the- /// container inputs it publishes. A size or scroll-state query asks only about an ancestor that- /// is such a container, or whose winners may make it one; a style query about any.- pub(super) fn container_ancestor_is_unsettled(- &self,- node: StyleNodeID,- scratch: &super::publication::EngineComputedRecordScratch,- ) -> bool {- // Winners published while an ancestor was moving hold no verdicts to say what their gated- // rules ask about.- let asks_about_style = self.container_gates_unheld.contains(&node)- || self.published_container_verdicts.get(&node).is_some_and(|verdicts| {- verdicts- .iter()- .any(|verdict| self.rule_asks_container_style(verdict.rule))- });- let mut ancestor = self.tree.flat_tree_parent(node);- while let Some(current) = ancestor {- if let Some(index) = current.element_index()- && scratch- .derived_child_inputs- .get(index as usize)- .is_some_and(|row| row.declined)- && (asks_about_style || self.may_be_a_query_container(current))- {- return true;- }- ancestor = self.tree.flat_tree_parent(current);- }- false- }-- /// Whether an element is a size, scroll-state or named container, or its winners may make it- /// one: an element that is none now and declares neither `container-type` nor `container-name`- /// is none a query asks about. A declared name can move with what it substitutes.- fn may_be_a_query_container(&self, node: StyleNodeID) -> bool {- use crate::css::property_metadata::property_id::{CONTAINER_NAME, CONTAINER_TYPE};- if self.container_query_inputs(node).is_some_and(|inputs| {- inputs.is_size_container- || inputs.is_inline_size_container- || inputs.is_scroll_state_container- || !inputs.names.is_empty()- }) {- return true;- }- match self- .current_winner_groups()- .token_for(WinnerGroupKey::current(node, self.program.version()))- {- Lookup::Known((_, state)) => {- self.winner_groups.winner_in_state(state, CONTAINER_TYPE).is_some()- || self.winner_groups.winner_in_state(state, CONTAINER_NAME).is_some()- }- _ => true,- }- }}/// What the container conditions of the rows the engine answered read of their containers, per element, kept for the@@ -915,22 +693,33 @@ impl RetainedState {/// any is kept.#[derive(Clone, Default)]pub(super) struct ContainerEffectsForHost {- effects: HashMap<StyleNodeID, ContainerVerdict>,+ effects: HashMap<StyleNodeID, std::sync::Arc<ContainerVerdict>>,held: std::sync::Arc<std::sync::atomic::AtomicBool>,}impl ContainerEffectsForHost {pub(super) fn get(&self, node: &StyleNodeID) -> Option<&ContainerVerdict> {- self.effects.get(node)+ self.effects.get(node).map(|verdict| &**verdict)}- fn note(&mut self, node: StyleNodeID, verdict: ContainerVerdict) {- self.effects.entry(node).or_default().add_reads(verdict);+ fn note(&mut self, node: StyleNodeID, verdict: &std::sync::Arc<ContainerVerdict>) {+ match self.effects.entry(node) {+ std::collections::hash_map::Entry::Occupied(mut held) => {+ std::sync::Arc::make_mut(held.get_mut()).add_reads((**verdict).clone());+ }+ std::collections::hash_map::Entry::Vacant(entry) => {+ entry.insert(verdict.clone());+ }+ }self.held.store(true, std::sync::atomic::Ordering::Relaxed);}/// Keeps `verdict` for `node`, or none, and answers what it kept before.- pub(super) fn set(&mut self, node: StyleNodeID, verdict: Option<ContainerVerdict>) -> Option<ContainerVerdict> {+ pub(super) fn set(+ &mut self,+ node: StyleNodeID,+ verdict: Option<std::sync::Arc<ContainerVerdict>>,+ ) -> Option<std::sync::Arc<ContainerVerdict>> {let previous = match verdict {Some(verdict) => self.effects.insert(node, verdict),None => self.effects.remove(&node),@@ -939,9 +728,4 @@ impl ContainerEffectsForHost {.store(!self.effects.is_empty(), std::sync::atomic::Ordering::Relaxed);previous}-- pub(super) fn clear(&mut self) {- self.effects.clear();- self.held.store(false, std::sync::atomic::Ordering::Relaxed);- }}diff --git a/Libraries/LibWeb/Rust/src/css/style/container_query_tests.rs b/Libraries/LibWeb/Rust/src/css/style/container_query_tests.rsindex b8eb9d093ca..e836354beae 100644--- a/Libraries/LibWeb/Rust/src/css/style/container_query_tests.rs+++ b/Libraries/LibWeb/Rust/src/css/style/container_query_tests.rs@@ -5,18 +5,8 @@*/use super::*;-use crate::css::computed_values::{- BoxValues, MiscResetValues, clone_group_payload, default_group_payload, release_group_payload,-};-use crate::css::custom_properties::{- CustomPropertyRegistry, FfiCustomPropertyRegistration, FfiCustomPropertyRegistryContext,- rust_custom_property_registry_create, rust_custom_property_registry_update,-};-use crate::css::ffi_support::FfiUtf16View;-use crate::css::parser::syntax::{SyntaxNode, rust_parse_syntax};-use crate::css::style_value::{RetainedStyleValueData, StyleValueData};+use crate::css::computed_values::{BoxValues, MiscLayoutValues};use crate::css::table_group_builder::group_index;-use std::sync::Arc;fn engine_with_containers() -> (StyleEngine, [StyleNodeID; 3]) {let mut engine = StyleEngine::new();@@ -35,8 +25,8 @@ fn engine_with_containers() -> (StyleEngine, [StyleNodeID; 3]) {);}super::tests::discard_transaction(&mut engine);- assert_eq!(engine.tree.flat_tree_parent(nodes[1]), Some(nodes[0]));- assert_eq!(engine.tree.flat_tree_parent(nodes[2]), Some(nodes[1]));+ assert_eq!(engine.projection.flat_tree_parent(nodes[1]), Some(nodes[0]));+ assert_eq!(engine.projection.flat_tree_parent(nodes[2]), Some(nodes[1]));publish_box(&mut engine,nodes[0],@@ -76,45 +66,27 @@ fn publish_box_with_types(types: (bool, bool, bool),) -> u64 {engine.set_element_box_kind(node, kind);- let payloads: Vec<_> = (0..group_index::COUNT)- .map(|index| {- // SAFETY: The source is the immutable default payload for this group.- SharedPayload::new(unsafe { clone_group_payload(index, default_group_payload(index)) }.cast_const())- })- .collect();- // SAFETY: The clones are privately owned and unpublished, with the indicated group layouts.+ let mut payloads = engine.default_groups().groups().clone();+ // SAFETY: The groups at these indices hold the named payload types.unsafe {- let box_values = &mut *payloads[group_index::BOX].as_ptr().cast_mut().cast::<BoxValues>();- box_values.display = display;- box_values.is_size_container = types.0;- box_values.is_inline_size_container = types.1;- box_values.is_scroll_state_container = types.2;- (*payloads[group_index::MISC_RESET]- .as_ptr()- .cast_mut()- .cast::<MiscResetValues>())- .appearance = appearance;- }- let publication = engine.publish_computed_groups(- computed::ComputedStyleTarget::new(node, u8::MAX),- &payloads,- computed::ENGINE_INHERITED_GROUP_COUNT,- 0,- computed::ComputedMetadataInput {- pseudo_element_styles: 0,- dependency_flags: 0,- counter_style_environment_identity: 0,- animation_overlay_identity: 0,- animated_overlay: HostShared::null(),- animation_overlay_payloads: &[],- longhand_table: HostShared::null(),- },- );- let record = publication.style_record_identity.raw();- engine.set_held_style_record(node, record);- for (index, payload) in payloads.iter().enumerate() {- release_group_payload(index, payload.as_ptr());+ payloads.write_group::<BoxValues>(group_index::BOX, |box_values| {+ box_values.display = display;+ box_values.is_size_container = types.0;+ box_values.is_inline_size_container = types.1;+ box_values.is_scroll_state_container = types.2;+ });+ payloads.write_group::<MiscLayoutValues>(group_index::MISC_LAYOUT, |misc| misc.appearance = appearance);}+ let record = engine+ .install_test_record(+ computed::ComputedStyleTarget::new(node, u8::MAX),+ None,+ Some(&payloads),+ 0,+ )+ .raw();+ let held = engine.computed_group_sets.host_record(record).cloned();+ engine.set_held_style_record(node, held);record}@@ -127,203 +99,6 @@ fn set_width(engine: &mut StyleEngine, node: StyleNodeID, width: i32) {}]);}-fn length_registry() -> Arc<CustomPropertyRegistry> {- let initial = RetainedStyleValueData::from_owned(StyleValueData::Length {- value: 0.0,- unit: crate::css::style_compute::px_length_unit(),- });- let syntax = rust_parse_syntax(FfiUtf16View::from_latin1(b"<length>"), false);- let registration = FfiCustomPropertyRegistration {- name: FfiUtf16View::from_latin1(b"--width"),- syntax,- inherits: false,- has_initial_value: true,- initial_value: FfiUtf16View::from_latin1(b"0px"),- computed_initial_value: initial.pointer().cast(),- };- let context = FfiCustomPropertyRegistryContext {- document_url: std::ptr::null(),- document_url_length: 0,- document_base_url: std::ptr::null(),- document_base_url_length: 0,- };- // SAFETY: The registry, syntax, strings, and initial value are live for the call; update consumes the old registry.- let registry = unsafe {- rust_custom_property_registry_update(- rust_custom_property_registry_create(),- &raw const context,- &raw const registration,- 1,- )- };- // SAFETY: Both APIs return one owned Arc reference. The registry copied the parsed syntax.- unsafe {- drop(Arc::from_raw(syntax.cast::<SyntaxNode>()));- Arc::from_raw(registry.cast::<CustomPropertyRegistry>())- }-}--fn resolve_width(- engine: &mut StyleEngine,- node: StyleNodeID,- pseudo: Option<u8>,- registry: Option<&CustomPropertyRegistry>,- settled: Option<&custom_property_cascade::RegisteredValueContext>,-) -> (RetainedStyleValueData, Option<container_queries::ContainerVerdict>) {- let name: Vec<_> = "--width".encode_utf16().collect();- let fly = ak::Utf16FlyString::from_utf16(&name);- let atom = engine.intern_atom(fly.raw_identity());- // SAFETY: The fly string is live and the engine retains its noted name.- unsafe {- engine.note_custom_property_name(atom, fly.raw_identity(), &name);- }- let source: Vec<_> = "10cqw".encode_utf16().collect();- let value = RetainedStyleValueData::from_owned(crate::css::parser::value_parser::unresolved_value_from_string(- &source,- Default::default(),- ));- let declaration = program::CustomDeclaration {- name: atom,- important: false,- operator: cascade::CascadeOperator::Declared,- value: cascade::SpecifiedValueID(value.pointer() as u64),- };- let inputs = bridge::FfiDocumentStyleComputationInputs {- custom_property_registry: registry- .map_or_default(|registry| bridge::FfiHostHandle::from_pointer(std::ptr::from_ref(registry).cast())),- viewport_width: 800.0,- viewport_height: 600.0,- ..Default::default()- };- engine.document_style_computation_inputs = inputs;- let environment = engine- .engine_custom_property_environment_over(node, pseudo, vec![(declaration, value)], 0, &inputs, settled)- .unwrap_or_else(|error| panic!("registered value should resolve: {error:?}"));- let value = engine- .custom_property_environments- .store(environment)- .unwrap()- .get(fly.raw_identity())- .unwrap()- .value- .clone();- let effects = engine.take_container_effects_for_host(node);- (value, effects)-}--fn px(value: &RetainedStyleValueData) -> f64 {- match value.data() {- StyleValueData::Length { value, unit } if *unit == crate::css::style_compute::px_length_unit() => *value,- _ => panic!("expected a computed absolute length"),- }-}--fn uses_container(effects: &Option<container_queries::ContainerVerdict>, expected: StyleNodeID) -> bool {- effects.as_ref().is_some_and(|effects| {- effects- .effects- .iter()- .any(|(node, kind)| *node == expected && matches!(kind, bridge::FfiContainerEffectKind::SizeContainerUsage))- })-}--#[test]-fn registered_pseudo_finalization() {- let (mut engine, nodes) = engine_with_containers();- let registry = length_registry();- let (value, effects) = resolve_width(- &mut engine,- nodes[1],- Some(super::publication::pseudo_kind::BEFORE),- Some(®istry),- None,- );- assert_eq!(px(&value), 20.0);- assert!(uses_container(&effects, nodes[1]));-}--#[test]-fn registered_pseudo_resize_and_retarget() {- let (mut engine, nodes) = engine_with_containers();- let registry = length_registry();- set_width(&mut engine, nodes[1], 300);- let (value, effects) = resolve_width(- &mut engine,- nodes[1],- Some(super::publication::pseudo_kind::BEFORE),- Some(®istry),- None,- );- assert_eq!(px(&value), 30.0);- assert!(uses_container(&effects, nodes[1]));- publish_box(- &mut engine,- nodes[1],- bridge::ElementBoxKind::FromDisplay,- crate::css::display::FfiDisplay::none(),- crate::css::css_enums::appearance::AUTO,- );- let (retargeted, effects) = resolve_width(- &mut engine,- nodes[1],- Some(super::publication::pseudo_kind::BEFORE),- Some(®istry),- None,- );- assert_eq!(px(&retargeted), 50.0);- assert!(uses_container(&effects, nodes[0]));- assert!(!uses_container(&effects, nodes[1]));-}--#[test]-fn registered_pseudo_settled_context() {- let (mut engine, nodes) = engine_with_containers();- let registry = length_registry();- let settled = custom_property_cascade::RegisteredValueContext {- length: crate::css::style_compute::FfiLengthResolutionContext {- container_width_basis: 999.0,- has_container_width_basis: true,- ..Default::default()- },- color_scheme: 0,- };- let (value, effects) = resolve_width(- &mut engine,- nodes[1],- Some(super::publication::pseudo_kind::BEFORE),- Some(®istry),- Some(&settled),- );- assert_eq!(px(&value), 20.0);- assert!(uses_container(&effects, nodes[1]));-}--#[test]-fn unregistered_pseudo_preserves_tokens() {- let (mut engine, nodes) = engine_with_containers();- let (value, effects) = resolve_width(- &mut engine,- nodes[1],- Some(super::publication::pseudo_kind::BEFORE),- None,- None,- );- assert_eq!(- String::from_utf16(&crate::css::serialize::serialize_style_value_to_utf16(value.data())).unwrap(),- "10cqw"- );- assert!(effects.is_none());-}--#[test]-fn registered_ordinary_ancestor() {- let (mut engine, nodes) = engine_with_containers();- let registry = length_registry();- let (value, effects) = resolve_width(&mut engine, nodes[1], None, Some(®istry), None);- assert_eq!(px(&value), 50.0);- assert!(uses_container(&effects, nodes[0]));-}-#[test]fn direct_pseudo_origin() {let (engine, nodes) = engine_with_containers();@@ -346,7 +121,7 @@ fn box_kind_row_refresh() {assert!(engine.container_query_inputs(node).unwrap().size_queries_available);engine.set_element_box_kind(node, bridge::ElementBoxKind::FromDisplay);assert!(!engine.container_query_inputs(node).unwrap().size_queries_available);- assert_eq!(engine.held_style_records.get(&node), Some(&record));+ assert_eq!(engine.held_style_record(node), Some(record));engine.set_element_box_kind(node, bridge::ElementBoxKind::Image);assert!(engine.container_query_inputs(node).unwrap().size_queries_available);}@@ -420,7 +195,7 @@ fn box_kind_change_invalidates_same_size_dependents() {engine.set_element_box_kind(nodes[1], bridge::ElementBoxKind::FromDisplay);assert!(engine.has_size_containers_needing_evaluation_after_layout());engine.evaluate_size_containers_needing_evaluation_after_layout();- assert!(engine.row_inputs_moved.containers_moved(nodes[2]));+ assert!(engine.has_deferred_element_style_input(nodes[2]));}#[test]@@ -469,7 +244,7 @@ fn newly_eligible_unqueried_container_invalidates_dependents() {assert_eq!(engine.size_query_container_scan_visits(true), 0);assert!(engine.has_size_containers_needing_evaluation_after_layout());engine.evaluate_size_containers_needing_evaluation_after_layout();- assert!(engine.row_inputs_moved.containers_moved(nodes[2]));+ assert!(engine.has_deferred_element_style_input(nodes[2]));engine.size_query_container_scan_visits(true);engine.record_size_container_query_dependents(nodes[1]);assert_eq!(engine.size_query_container_scan_visits(true), 0);@@ -511,7 +286,7 @@ fn input_construction_fact_keeps_generic_boxes_atomic() {fn assert_scroll_only_publication_does_not_scan(unrelated_dependent: bool) {let (mut engine, nodes) = engine_with_containers();- engine.container_query_inputs.clear(nodes[1]);+ engine.size_container_queries.forget_availability(nodes[1]);engine.set_element_size_container_query_facts(nodes[0], false, unrelated_dependent);engine.size_query_container_scan_visits(true);publish_box_with_types(@@ -576,7 +351,7 @@ fn foreign_object_inline_box_matches_layout_atomicity_and_selection() {crate::css::css_enums::appearance::AUTO,);let payloads = engine.computed_group_sets.style_record_payloads(record).unwrap();- let values = crate::css::computed_value_views::ComputedValuesView::new(SharedPayload::as_pointer_slice(payloads));+ let values = crate::css::computed_value_views::ComputedValuesView::of(&payloads);let kind = crate::layout::node_data::NodeKind::SVGForeignObjectBox;let flags = crate::layout::node_facts::construction_flags(kind, false, 0);assert!(!crate::layout::node_facts::kind_is_replaced_box(kind));diff --git a/Libraries/LibWeb/Rust/src/css/style/exact_matcher.rs b/Libraries/LibWeb/Rust/src/css/style/exact_matcher.rsindex 5750635767c..ea7a013189e 100644--- a/Libraries/LibWeb/Rust/src/css/style/exact_matcher.rs+++ b/Libraries/LibWeb/Rust/src/css/style/exact_matcher.rs@@ -6,25 +6,22 @@//! The cache-free selector correctness floor.//!-//! This matcher enumerates attached rules directly from the stylesheet program and evaluates their-//! match selector IR against committed facts and tree relations. It deliberately owns no+//! This matcher enumerates attached rules directly from the rule store and matches their selectors+//! against committed facts and tree relations. It deliberately owns no//! dispatch index, Bloom summary, prefix state, relation or position cache, retained witness,//! retained answer, or cascade-pruning state.-use super::index::StyleNodeFacts;-use super::instrumentation::Counters;-use super::program::CascadeOrigin;-use super::program::RuleID;-use super::program::SelectorProgramID;-use super::program::StyleSheetProgram;+use super::RetainedState;+use super::pipeline::projection::Projection;+use super::pipeline::rule_store::CascadeOrigin;+use super::pipeline::rule_store::RuleID;+use super::pipeline::rule_store::RuleStore;use super::selector::Incomplete;-use super::selector::MatchEvaluator;-use super::selector::SelectorPrograms;use super::selector::Specificity;use super::tree::PseudoElementTarget;use super::tree::StyleNodeID;-use super::tree::StyleNodeTree;use super::tree::TreeScopeID;+use smallvec::SmallVec;/// One selector-list answer produced without derived matching state.#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]@@ -32,7 +29,6 @@ pub struct ExactRuleMatch {pub node: StyleNodeID,pub pseudo_element: Option<PseudoElementTarget>,pub rule: RuleID,- pub program: SelectorProgramID,pub entry: u32,pub specificity: Specificity,pub tree_scope: TreeScopeID,@@ -51,13 +47,12 @@ pub enum ExactMatchContext {/// Direct evaluator over attached rules and committed base relations only.pub struct ExactMatcher<'a> {- tree: &'a StyleNodeTree,- facts: &'a StyleNodeFacts,- programs: &'a SelectorPrograms,- program: &'a StyleSheetProgram,+ projection: &'a Projection,+ program: &'a RuleStore,scope: TreeScopeID,shadow_root: Option<StyleNodeID>,context: ExactMatchContext,+ document: super::component_matching::DocumentMatching,}#[derive(Clone, Copy, PartialEq, Eq)]@@ -68,20 +63,18 @@ enum DocumentSheets {impl<'a> ExactMatcher<'a> {#[must_use]- pub fn new(- tree: &'a StyleNodeTree,- facts: &'a StyleNodeFacts,- programs: &'a SelectorPrograms,- program: &'a StyleSheetProgram,+ pub(super) fn new(+ projection: &'a Projection,+ program: &'a RuleStore,+ document: super::component_matching::DocumentMatching,) -> Self {Self {- tree,- facts,- programs,+ projection,program,scope: TreeScopeID::DOCUMENT,shadow_root: None,context: ExactMatchContext::Ordinary,+ document,}}@@ -104,24 +97,19 @@ impl<'a> ExactMatcher<'a> {}/// Evaluate one element by walking every attached rule entry directly.- pub fn match_node(- &self,- node: StyleNodeID,- out: &mut Vec<ExactRuleMatch>,- counters: &Counters,- ) -> Result<(), Incomplete> {- if self.facts.row_of(node).is_none() {+ pub fn match_node(&self, node: StyleNodeID, out: &mut Vec<ExactRuleMatch>) -> Result<(), Incomplete> {+ if self.projection.facts(node).is_none() {return Err(Incomplete::MissingFacts(node));}let start = out.len();let result = (|| {- self.match_sheets(node, self.scope, DocumentSheets::All, start, out, counters)?;+ self.match_sheets(node, self.scope, DocumentSheets::All, start, out)?;if self.scope != TreeScopeID::DOCUMENT {let document_sheets = match self.program.scope_uses_document_sheets(self.scope) {true => DocumentSheets::All,false => DocumentSheets::NonAuthorOnly,};- self.match_sheets(node, TreeScopeID::DOCUMENT, document_sheets, start, out, counters)?;+ self.match_sheets(node, TreeScopeID::DOCUMENT, document_sheets, start, out)?;}Ok(())})();@@ -133,25 +121,6 @@ impl<'a> ExactMatcher<'a> {Ok(())}- /// Evaluate every element under `root` in preorder.- #[cfg(test)]- pub fn match_subtree(- &self,- root: StyleNodeID,- out: &mut Vec<ExactRuleMatch>,- counters: &Counters,- ) -> Result<(), Incomplete> {- let start = out.len();- for node in self.tree.preorder(root) {- if let Err(incomplete) = self.match_node(node, out, counters) {- out.truncate(start);- return Err(incomplete);- }- }- out[start..].sort_unstable_by_key(|matched| (matched.node, matched.rule, matched.pseudo_element));- Ok(())- }-fn match_sheets(&self,node: StyleNodeID,@@ -159,7 +128,6 @@ impl<'a> ExactMatcher<'a> {take: DocumentSheets,match_start: usize,out: &mut Vec<ExactRuleMatch>,- counters: &Counters,) -> Result<(), Incomplete> {for &sheet in self.program.sheets_in_scope(sheet_scope) {if take == DocumentSheets::NonAuthorOnly@@ -178,35 +146,41 @@ impl<'a> ExactMatcher<'a> {if !version.kind.matches_elements() {continue;}- let Some(program_id) = version.selector_program else {+ let Some(selectors) = self.program.selectors_of(sheet, version) else {continue;};- let compiled = self.programs.get(program_id);- let mut evaluator = MatchEvaluator::new(self.tree, self.facts);- if let Some(shadow_root) = self.shadow_root {- evaluator = evaluator.in_shadow_tree(shadow_root);- }+ let scope = self.program.scope_chain(version.scope).map(|chain| &**chain);+ let mut evaluator = self.projection.evaluator();+ evaluator.set_scope_shadow_root(self.shadow_root);if self.context == ExactMatchContext::Part {- evaluator = evaluator.for_a_part_exposed_in(self.scope);+ evaluator.set_part_exposure_scope(Some(self.scope));}- for (index, entry) in compiled.entries().iter().enumerate() {+ for (index, (selector, specificity, pseudo_kind)) in super::pipeline::entries_of(&selectors).enumerate()+ {+ let entry_selector = super::component_matching::EntrySelector::new(selector, scope);+ let facts = super::selector_analysis::EntryFacts::of(entry_selector);let context_admits = match self.context {ExactMatchContext::Ordinary => true,- ExactMatchContext::Slotted => compiled.subject_is_slotted(entry.root),- ExactMatchContext::Part => compiled.subject_is_a_part(entry.root),- ExactMatchContext::Host => compiled.subject_is_the_host(entry.root),+ ExactMatchContext::Slotted => facts.slotted,+ ExactMatchContext::Part => facts.part,+ ExactMatchContext::Host => facts.host,};- if !context_admits || !evaluator.matches_entry(compiled, entry, node, counters)? {+ if !context_admits {continue;}- let scope_proximity = evaluator.scope_proximity_of(compiled, entry, node, counters)?;+ let matched = evaluator.matches_entry_selector(entry_selector, node, self.document)?;+ let pseudo_element = (pseudo_kind != u8::MAX)+ .then(|| PseudoElementTarget::new(super::tree::PseudoElementKind(u16::from(pseudo_kind))));+ if !matched {+ continue;+ }+ let scope_proximity = evaluator.scope_proximity_of_match(node);let candidate = ExactRuleMatch {node,- pseudo_element: entry.pseudo_element,+ pseudo_element,rule,- program: program_id,entry: u32::try_from(index).expect("selector entry space exhausted"),- specificity: entry.specificity,+ specificity,tree_scope: self.scope,scope_proximity,};@@ -214,7 +188,7 @@ impl<'a> ExactMatcher<'a> {existing.node == node&& existing.rule == rule&& existing.tree_scope == self.scope- && existing.pseudo_element == entry.pseudo_element+ && existing.pseudo_element == pseudo_element}) {if candidate.specificity > existing.specificity {*existing = candidate;@@ -229,118 +203,68 @@ impl<'a> ExactMatcher<'a> {}}-#[cfg(test)]-mod tests {- use super::super::index::StateSet;- use super::super::index::StyleAtomID;- use super::super::program::RuleKind;- use super::super::program::StyleSheetObjectID;- use super::super::selector::FeatureTest;- use super::super::selector::SelectorOp;- use super::super::selector::SelectorProgramBuilder;- use super::*;-- #[test]- fn exact_matching_enumerates_rules_without_a_dispatch() {- let mut tree = StyleNodeTree::new();- let root = tree.allocate_element();- let child = tree.allocate_element();- tree.set_first_element_child(root, Some(child));- tree.set_parent(child, Some(root));-- let theme = StyleAtomID(1);- let item = StyleAtomID(2);- let mut facts = StyleNodeFacts::new();- facts.push_row(- root,- StyleAtomID(10),- StyleAtomID::NONE,- StateSet::default(),- &[theme],- &[],- );- facts.push_row(- child,- StyleAtomID(11),- StyleAtomID::NONE,- StateSet::default(),- &[item],- &[],- );-- let mut programs = SelectorPrograms::new();- let mut builder = SelectorProgramBuilder::new();- let ancestor = builder.push_feature(FeatureTest::Class(theme));- let ancestor = builder.push(SelectorOp::Ancestor(ancestor));- let subject = builder.push_feature(FeatureTest::Class(item));- let selector = builder.push_compound(&[subject, ancestor]);- builder.push_entry(selector);- let selector = programs.add(builder.finish());-- let mut program = StyleSheetProgram::new();- let sheet = program.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- program.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = program.append_rule(sheet, None, RuleKind::Style);- let mut version = program.rule_version(rule);- version.selector_program = Some(selector);- program.replace_rule_version(rule, version);-- let mut matches = Vec::new();- let counters = Counters::new();- ExactMatcher::new(&tree, &facts, &programs, &program)- .match_subtree(root, &mut matches, &counters)- .unwrap();-- assert_eq!(matches.len(), 1);- assert_eq!(matches[0].node, child);- assert_eq!(matches[0].rule, rule);+impl RetainedState {+ pub(super) fn append_exact_matches_in_scope(+ &self,+ node: StyleNodeID,+ scope: TreeScopeID,+ context: ExactMatchContext,+ matches: &mut Vec<ExactRuleMatch>,+ ) -> Result<(), Incomplete> {+ let shadow_root = self.scope_root(scope);+ let mut matcher = ExactMatcher::new(&self.projection, &self.rules, self.document_matching())+ .in_scope(scope)+ .with_context(context);+ if let Some(shadow_root) = shadow_root {+ matcher = matcher.in_shadow_tree(shadow_root);+ }+ matcher.match_node(node, matches)}- #[test]- fn exact_matching_keeps_the_greatest_selector_list_specificity() {- let mut tree = StyleNodeTree::new();- let node = tree.allocate_element();- let class = StyleAtomID(1);- let id = StyleAtomID(2);- let mut facts = StyleNodeFacts::new();- facts.push_row(node, StyleAtomID(10), id, StateSet::default(), &[class], &[]);-- let mut programs = SelectorPrograms::new();- let mut builder = SelectorProgramBuilder::new();- let by_class = builder.push_feature(FeatureTest::Class(class));- let by_class = builder.push_entry(by_class);- builder.set_entry_specificity(- by_class,- Specificity {- classes: 1,- ..Specificity::default()- },- );- let by_id = builder.push_feature(FeatureTest::Id(id));- let by_id = builder.push_entry(by_id);- builder.set_entry_specificity(- by_id,- Specificity {- ids: 1,- ..Specificity::default()- },- );- let selector = programs.add(builder.finish());-- let mut program = StyleSheetProgram::new();- let sheet = program.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- program.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = program.append_rule(sheet, None, RuleKind::Style);- let mut version = program.rule_version(rule);- version.selector_program = Some(selector);- program.replace_rule_version(rule, version);+ /// Append what `node` matches from every tree whose rules can decide for it, evaluating every+ /// attached rule directly, and answer whether a rule can match it from more than one tree.+ pub(super) fn append_exact_matches_in_every_scope(+ &self,+ node: StyleNodeID,+ exact: &mut Vec<ExactRuleMatch>,+ ) -> Result<bool, Incomplete> {+ let scope = self.projection.tree_scope(node);+ let inner_scope = self+ .projection+ .shadow_root_of(node)+ .and_then(|shadow_root| self.scope_by_root.get(shadow_root).filter(|&inner| inner != scope));+ let slotted_scopes: SmallVec<[TreeScopeID; 1]> = self+ .scopes_slotted_into(node)+ .filter(|&slotted| slotted != scope && Some(slotted) != inner_scope)+ .collect();+ let part_scopes: SmallVec<[TreeScopeID; 1]> = self+ .part_exposure_scopes(node)+ .filter(|&exposed| exposed != scope && Some(exposed) != inner_scope && !slotted_scopes.contains(&exposed))+ .collect();- let mut matches = Vec::new();- ExactMatcher::new(&tree, &facts, &programs, &program)- .match_node(node, &mut matches, &Counters::new())- .unwrap();+ for_each_matching_scope(scope, inner_scope, &slotted_scopes, &part_scopes, |scope, context| {+ self.append_exact_matches_in_scope(node, scope, context, exact)+ })?;+ Ok(inner_scope.is_some() || !slotted_scopes.is_empty() || !part_scopes.is_empty())+ }+}- assert_eq!(matches.len(), 1);- assert_eq!(matches[0].entry, 1);+fn for_each_matching_scope(+ scope: TreeScopeID,+ inner_scope: Option<TreeScopeID>,+ slotted_scopes: &[TreeScopeID],+ part_scopes: &[TreeScopeID],+ mut ask: impl FnMut(TreeScopeID, ExactMatchContext) -> Result<(), Incomplete>,+) -> Result<(), Incomplete> {+ ask(scope, ExactMatchContext::Ordinary)?;+ if let Some(inner_scope) = inner_scope {+ ask(inner_scope, ExactMatchContext::Host)?;+ }+ for &slotted_scope in slotted_scopes {+ ask(slotted_scope, ExactMatchContext::Slotted)?;+ }+ for &part_scope in part_scopes {+ ask(part_scope, ExactMatchContext::Part)?;}+ Ok(())}diff --git a/Libraries/LibWeb/Rust/src/css/style/impact.rs b/Libraries/LibWeb/Rust/src/css/style/impact.rsdeleted file mode 100644index a25bd046d88..00000000000--- a/Libraries/LibWeb/Rust/src/css/style/impact.rs+++ /dev/null@@ -1,2260 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! Impact regions: the transaction-local execution plan for one style flush.-//!-//! An impact region is the normalized union of everything the transaction's transpose programs can-//! reach. It is a plan, never a retained element-by-selector relation, and it exists to answer one-//! question: between the last committed state and the final live state, which style nodes can have-//! a different semantic output?-//!-//! The obligation is one-sided. A region may be wider than the truth, because every subject it-//! yields is checked exactly before anything downstream is emitted. It may never be narrower, so an-//! operator that cannot construct a proven region widens to the document. Unknown scope is never-//! treated as empty scope.-//!-//! Regions carry the tree relation they were named with. Coalescing two overlapping regions keeps-//! that relation rather than flattening both into a node set, because the relation is what a later-//! stage needs in order to enumerate the region without materializing it.--use super::column::BitColumn;-use super::column::PagedColumn;-use super::column::PagedColumnPage;-use super::instrumentation::Counter;-use super::instrumentation::Counters;-use super::program::EntryID;-use super::program::RuleID;-use super::selector::InverseStep;-use super::tree::StyleNodeID;-use super::tree::StyleNodeTree;-use super::tree::TreeScopeID;--/// One region of the impact plan, named by the tree relation that produced it.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]-pub enum ImpactRegion {- /// No style node at all. A relation step can prove this: a host with no shadow root hosts- /// nothing, and an unslotted node reaches no slot. Saying so is what keeps a route that leads- /// nowhere from being indistinguishable from one that could not be proven.- Empty,- /// Exactly one style node.- Node(StyleNodeID),- /// A node's element children.- Children(StyleNodeID),- /// A node and everything below it.- Subtree(StyleNodeID),- /// Everything below a node, but not the node.- ///- /// `:host *` describes the host's descendants and not the host, and the difference is the whole- /// of what such a rule reaches when the host is the only element it would otherwise add.- StrictSubtree(StyleNodeID),- /// The immediately following element sibling of a node.- NextSibling(StyleNodeID),- /// Every following element sibling of a node.- FollowingSiblings(StyleNodeID),- /// Every following element sibling of a node and each sibling's subtree.- ///- /// This bounds the forest produced by a sibling combinator followed by a descendant or child- /// combinator. Keeping the forest named avoids widening it to the parent's whole subtree,- /// which would include the origin and every preceding sibling as well.- FollowingSiblingSubtrees(StyleNodeID),- /// The whole child sequence a node belongs to.- SiblingSequence(StyleNodeID),- /// A node's ancestors: the possible anchors of a descendant `:has()` query.- Ancestors(StyleNodeID),- /// The immediately preceding element sibling: the anchor of an adjacent-sibling query.- PreviousSibling(StyleNodeID),- /// The preceding element siblings: the anchors of a following-sibling query.- PrecedingSiblings(StyleNodeID),- /// Every node of every shadow tree nested at or below the one a host hosts.- ///- /// Named by the host rather than by its shadow root, because what bounds the region is how many- /// shadow roots stand between a node and that host: a `::part()` name forwarded outwards by- /// `exportparts` crosses one per level, and the host's own light-DOM descendants cross none and- /// are not in the region at all.- HostedSubtrees(StyleNodeID),- /// A complete tree scope, when no narrower region could be proven.- TreeScope(TreeScopeID),- /// The whole document, the widest an operator can go.- Document,-}--impl ImpactRegion {- /// Whether the region lies outside the document tree scope.- #[must_use]- pub(super) fn lies_outside_document_scope(self, tree: &StyleNodeTree) -> bool {- match self {- Self::Empty | Self::Document => false,- Self::TreeScope(scope) => scope != TreeScopeID::DOCUMENT,- Self::HostedSubtrees(_) => true,- Self::Node(node)- | Self::Children(node)- | Self::Subtree(node)- | Self::StrictSubtree(node)- | Self::NextSibling(node)- | Self::FollowingSiblings(node)- | Self::FollowingSiblingSubtrees(node)- | Self::SiblingSequence(node)- | Self::Ancestors(node)- | Self::PreviousSibling(node)- | Self::PrecedingSiblings(node) => tree.tree_scope(node) != TreeScopeID::DOCUMENT,- }- }-- /// Widen a region by one inverse relation step.- ///- /// Each case answers "where can this relation reach, starting from everything already in the- /// region". Sibling steps applied to a region that holds a subtree's root escape upwards,- /// because the siblings of that root lie outside the subtree. A region below its root keeps- /// them inside, since siblings share a parent.- #[must_use]- pub fn step(self, step: InverseStep, tree: &StyleNodeTree) -> Self {- match (self, step) {- (Self::Empty, _) => Self::Empty,- (Self::Document, _) => Self::Document,- (Self::TreeScope(scope), _) => Self::TreeScope(scope),-- (Self::Node(node), InverseStep::Descendants) => Self::StrictSubtree(node),- (Self::Node(node), InverseStep::Children) => Self::Children(node),- (Self::Node(node), InverseStep::NextSibling) => Self::NextSibling(node),- (Self::Node(node), InverseStep::FollowingSiblings) => Self::FollowingSiblings(node),- (Self::Node(node), InverseStep::SiblingSequence) => Self::SiblingSequence(node),-- // Children of a node's children, and everything below them, stay below the node.- (Self::Children(node), InverseStep::Descendants | InverseStep::Children) => Self::StrictSubtree(node),- (Self::Subtree(node), InverseStep::Descendants | InverseStep::Children) => Self::Subtree(node),-- // The siblings of a node's children are its children, and the siblings of anything below- // a node are below it too.- (- Self::Children(node),- InverseStep::NextSibling | InverseStep::FollowingSiblings | InverseStep::SiblingSequence,- ) => Self::Children(node),- (- Self::StrictSubtree(node),- InverseStep::Descendants- | InverseStep::Children- | InverseStep::NextSibling- | InverseStep::FollowingSiblings- | InverseStep::SiblingSequence,- ) => Self::StrictSubtree(node),-- // A sibling step from a subtree can leave it through the root, so it widens to the- // parent's subtree.- (- Self::Subtree(node),- InverseStep::NextSibling | InverseStep::FollowingSiblings | InverseStep::SiblingSequence,- ) => match tree.parent(node) {- Some(parent) => Self::Subtree(parent),- None => Self::Subtree(node),- },-- // The sibling-shaped regions are already a set of nodes at one level; widening them- // means treating that level as the starting set.- (Self::NextSibling(node), InverseStep::Descendants | InverseStep::Children) => {- match tree.next_element_sibling(node) {- Some(next) => Self::Subtree(next),- None => Self::Empty,- }- }- (Self::FollowingSiblings(node), InverseStep::Descendants | InverseStep::Children) => {- Self::FollowingSiblingSubtrees(node)- }- (Self::SiblingSequence(node), InverseStep::Descendants | InverseStep::Children) => {- match tree.parent(node) {- Some(parent) => Self::Subtree(parent),- None => Self::Subtree(node),- }- }- (- Self::NextSibling(node) | Self::FollowingSiblings(node) | Self::SiblingSequence(node),- InverseStep::NextSibling | InverseStep::FollowingSiblings | InverseStep::SiblingSequence,- ) => Self::SiblingSequence(node),-- (- Self::FollowingSiblingSubtrees(node),- InverseStep::Descendants- | InverseStep::Children- | InverseStep::NextSibling- | InverseStep::FollowingSiblings,- ) => Self::FollowingSiblingSubtrees(node),- (Self::FollowingSiblingSubtrees(node), InverseStep::SiblingSequence) => match tree.parent(node) {- Some(parent) => Self::Subtree(parent),- None => Self::Subtree(node),- },-- // A host reaches the tree it hosts, and the shadow root's own identity is what makes- // that a subtree rather than a boundary. A host with no shadow root hosts nothing, so- // the step reaches nothing at all rather than everything.- (Self::Node(node), InverseStep::HostedTree) => match tree.shadow_root_of(node) {- Some(shadow_root) => Self::Subtree(shadow_root),- None => Self::Empty,- },-- // An element backing a pseudo-element reaches its shadow host, and only its host.- (Self::Node(node), InverseStep::ShadowHost) => match tree.shadow_host_of(node) {- Some(host) => Self::Node(host),- None => Self::Empty,- },-- // A slotted node reaches its slot, and only its slot.- (Self::Node(node), InverseStep::SlotAssignment) => match tree.assigned_slot_of(node) {- Some(slot) => Self::Node(slot),- None => Self::Empty,- },-- // Assigned elements are light-DOM children of the shadow host. This region can include- // unassigned children, which exact matching filters, but can never omit an assignee.- (Self::Node(node), InverseStep::SlotAssignees) => match tree.shadow_host_of(node) {- Some(host) => Self::Children(host),- None => Self::Empty,- },-- // A host reaches every tree nested below the one it hosts, because `exportparts` carries- // a part name outwards through any number of hosts.- (Self::Node(node), InverseStep::HostedTrees) => match tree.shadow_root_of(node) {- Some(_) => Self::HostedSubtrees(node),- None => Self::Empty,- },-- // From a region wider than one node the relation is a set lookup per member, which the- // plan cannot enumerate without walking the region it was trying to avoid.- (- _,- InverseStep::HostedTree- | InverseStep::HostedTrees- | InverseStep::ShadowHost- | InverseStep::SlotAssignment- | InverseStep::SlotAssignees,- ) => Self::Document,-- // The anchor-shaped regions already span an ancestor path or a sibling range, and any- // further step from them can leave whatever subtree bounded them. A region spanning- // nested shadow trees is bounded by no single subtree either.- (- Self::Ancestors(_) | Self::PreviousSibling(_) | Self::PrecedingSiblings(_) | Self::HostedSubtrees(_),- _,- ) => Self::Document,- }- }-- /// Apply a whole transpose path, in application order.- #[must_use]- pub fn follow(node: StyleNodeID, path: &[InverseStep], tree: &StyleNodeTree) -> Self {- path.iter()- .fold(Self::Node(node), |region, &step| region.step(step, tree))- }-- /// Whether this region contains everything `other` does.- #[must_use]- fn contains_with_topology(self, other: Self, tree: &StyleNodeTree, topology: Option<&TransactionTopology>) -> bool {- if self == other {- return true;- }- if other == Self::Empty {- return true;- }- match self {- Self::Empty => false,- Self::Document => true,- Self::Subtree(root) => match other {- Self::Node(node) | Self::Subtree(node) | Self::StrictSubtree(node) => topology- .and_then(|topology| topology.is_in_subtree_of(node, root))- .unwrap_or_else(|| tree.is_in_subtree_of(node, root)),- Self::Children(node) => topology- .and_then(|topology| topology.is_in_subtree_of(node, root))- .unwrap_or_else(|| tree.is_in_subtree_of(node, root)),- _ => false,- },- Self::StrictSubtree(root) => match other {- Self::Node(node) | Self::Subtree(node) | Self::StrictSubtree(node) => {- node != root- && topology- .and_then(|topology| topology.is_in_subtree_of(node, root))- .unwrap_or_else(|| tree.is_in_subtree_of(node, root))- }- Self::Children(node) => topology- .and_then(|topology| topology.is_in_subtree_of(node, root))- .unwrap_or_else(|| tree.is_in_subtree_of(node, root)),- _ => false,- },- Self::FollowingSiblingSubtrees(_) => match other {- Self::Node(node) | Self::Subtree(node) | Self::StrictSubtree(node) => {- self.contains_node_with_topology(node, tree, topology)- }- Self::Children(node) => self.contains_node_with_topology(node, tree, topology),- _ => false,- },- _ => false,- }- }-- /// Whether `node` lies in this region.- ///- /// Proving membership walks the named relation, which is what a selective plan pays per- /// candidate in exchange for not streaming the whole region.- #[must_use]- pub fn contains_node(self, node: StyleNodeID, tree: &StyleNodeTree) -> bool {- self.contains_node_with_topology(node, tree, None)- }-- #[must_use]- fn contains_node_with_topology(- self,- node: StyleNodeID,- tree: &StyleNodeTree,- topology: Option<&TransactionTopology>,- ) -> bool {- match self {- Self::Empty => false,- Self::Node(other) => node == other,- Self::Children(parent) => tree.parent(node) == Some(parent),- Self::Subtree(root) => topology- .and_then(|topology| topology.is_in_subtree_of(node, root))- .unwrap_or_else(|| tree.is_in_subtree_of(node, root)),- Self::StrictSubtree(root) => {- node != root- && topology- .and_then(|topology| topology.is_in_subtree_of(node, root))- .unwrap_or_else(|| tree.is_in_subtree_of(node, root))- }- // Climbing out of a shadow tree goes through its host, so the number of roots crossed on- // the way to `host` is what says whether the node is in a tree it hosts. Zero crossings- // means the node is in the host's own light DOM, which this region does not cover.- Self::HostedSubtrees(host) => {- let mut current = node;- let mut crossed_a_shadow_root = false;- loop {- if current == host {- return crossed_a_shadow_root;- }- if let Some(parent) = tree.parent(current) {- current = parent;- continue;- }- match tree.host_of(current) {- Some(host_of_root) => {- crossed_a_shadow_root = true;- current = host_of_root;- }- None => return false,- }- }- }- Self::NextSibling(anchor) => tree.next_element_sibling(anchor) == Some(node),- Self::FollowingSiblings(anchor) => {- let mut current = tree.next_element_sibling(anchor);- while let Some(sibling) = current {- if sibling == node {- return true;- }- current = tree.next_element_sibling(sibling);- }- false- }- Self::FollowingSiblingSubtrees(anchor) => {- let Some(parent) = tree.parent(anchor) else {- return false;- };- let mut branch = node;- loop {- match tree.parent(branch) {- Some(branch_parent) if branch_parent == parent => break,- Some(ancestor) => branch = ancestor,- None => return false,- }- }- let mut sibling = tree.next_element_sibling(anchor);- while let Some(current) = sibling {- if current == branch {- return true;- }- sibling = tree.next_element_sibling(current);- }- false- }- Self::SiblingSequence(member) => tree.parent(node) == tree.parent(member),- Self::Ancestors(from) => topology- .and_then(|topology| topology.is_in_subtree_of(from, node))- .map_or_else(- || tree.ancestors(from).any(|ancestor| ancestor == node),- |inside| inside && from != node,- ),- Self::PreviousSibling(anchor) => tree.previous_element_sibling(anchor) == Some(node),- Self::PrecedingSiblings(anchor) => {- let Some(parent) = tree.parent(anchor) else {- return false;- };- for sibling in tree.children(parent) {- if sibling == anchor {- return false;- }- if sibling == node {- return true;- }- }- false- }- Self::TreeScope(scope) => tree.tree_scope(node) == scope,- Self::Document => true,- }- }-- /// Stream the style nodes of the region. The relation the region was named with decides how it- /// is walked, which is why coalescing preserves it.- pub fn for_each(self, tree: &StyleNodeTree, mut visit: impl FnMut(StyleNodeID)) {- match self {- Self::Empty => {}- Self::Node(node) => visit(node),- Self::Children(node) => tree.children(node).for_each(visit),- Self::Subtree(node) => tree.preorder(node).for_each(visit),- Self::StrictSubtree(root) => tree.preorder(root).filter(|&node| node != root).for_each(visit),- // A shadow root is not a descendant of its host, so the walk has to be seeded with each- // one it reaches rather than falling out of a single preorder.- Self::HostedSubtrees(host) => {- let mut pending: Vec<StyleNodeID> = tree.shadow_root_of(host).into_iter().collect();- while let Some(root) = pending.pop() {- for node in tree.preorder(root) {- if let Some(nested) = tree.shadow_root_of(node) {- pending.push(nested);- }- visit(node);- }- }- }- Self::NextSibling(node) => {- if let Some(next) = tree.next_element_sibling(node) {- visit(next);- }- }- Self::FollowingSiblings(node) => {- let mut current = tree.next_element_sibling(node);- while let Some(sibling) = current {- visit(sibling);- current = tree.next_element_sibling(sibling);- }- }- Self::FollowingSiblingSubtrees(node) => {- let mut sibling = tree.next_element_sibling(node);- while let Some(root) = sibling {- tree.preorder(root).for_each(&mut visit);- sibling = tree.next_element_sibling(root);- }- }- Self::SiblingSequence(node) => match tree.parent(node) {- Some(parent) => tree.children(parent).for_each(visit),- None => visit(node),- },- Self::Ancestors(node) => tree.ancestors(node).for_each(visit),- Self::PreviousSibling(node) => {- if let Some(previous) = tree.previous_element_sibling(node) {- visit(previous);- }- }- Self::PrecedingSiblings(node) => {- if let Some(parent) = tree.parent(node) {- for sibling in tree.children(parent) {- if sibling == node {- break;- }- visit(sibling);- }- }- }- // A document contains independent DOM preorders for its document and shadow-tree- // scopes. Live identity order covers all of them without treating a shadow root as a- // descendant of its host.- Self::TreeScope(scope) => tree- .live_nodes()- .filter(|&node| tree.tree_scope(node) == scope)- .for_each(visit),- Self::Document => tree.live_nodes().for_each(visit),- }- }-}--/// Coalescing more than this many regions pairwise would cost more relation steps than the-/// widening it saves, so beyond it only exact duplicates are removed.-pub(super) const MAX_PAIRWISE_COALESCE: usize = 64;--const NO_PREORDER_POSITION: u32 = u32::MAX;--#[derive(Clone, Copy, Debug, PartialEq, Eq, PartialOrd, Ord)]-struct PreorderInterval {- start: u32,- end: u32,-}--/// Dense transaction-local membership for emitted region identities.-///-/// Every element index owns one bit per node-shaped region kind. Pseudo-elements do not have an-/// element index and remain in a small linear tail, while tree scopes use the same compact bitset-/// shape. This replaces hashing integer identities and folds exact-node membership into the same-/// index.-const REGION_KIND_PAGE_BITS: usize = 8;-const REGION_KIND_PAGE_SIZE: usize = 1 << REGION_KIND_PAGE_BITS;--struct RegionKindPage {- kinds: [u16; REGION_KIND_PAGE_SIZE],-}--impl Default for RegionKindPage {- fn default() -> Self {- Self {- kinds: [0; REGION_KIND_PAGE_SIZE],- }- }-}--impl PagedColumnPage for RegionKindPage {- type Value = u16;-- const SHIFT: usize = REGION_KIND_PAGE_BITS;-- fn get(&self, index: usize) -> Option<u16> {- (self.kinds[index] != 0).then_some(self.kinds[index])- }-- fn insert(&mut self, index: usize, kinds: u16) {- self.kinds[index] = kinds;- }-}--#[derive(Default)]-struct RegionKindPages(PagedColumn<RegionKindPage>);--impl RegionKindPages {- fn insert(&mut self, element_index: u32, kind: u16) -> bool {- let index = element_index as usize;- let (page, _) = self.0.page_mut_or_default(index);- let kinds = &mut page.kinds[index & (REGION_KIND_PAGE_SIZE - 1)];- let was_present = *kinds & kind != 0;- *kinds |= kind;- !was_present- }-- fn contains(&self, element_index: u32, kind: u16) -> bool {- self.0- .get(element_index as usize)- .is_some_and(|kinds| kinds & kind != 0)- }-- fn clear(&mut self) {- for page in self.0.pages_mut() {- page.kinds.fill(0);- }- }-}--#[derive(Default)]-struct ImpactRegionIndex {- element_kinds: RegionKindPages,- tree_scopes: BitColumn,- document: bool,-}--impl ImpactRegionIndex {- fn node_and_kind(region: ImpactRegion) -> Option<(StyleNodeID, u16)> {- let (node, bit) = match region {- ImpactRegion::Node(node) => (node, 0),- ImpactRegion::Children(node) => (node, 1),- ImpactRegion::Subtree(node) => (node, 2),- ImpactRegion::StrictSubtree(node) => (node, 3),- ImpactRegion::NextSibling(node) => (node, 4),- ImpactRegion::FollowingSiblings(node) => (node, 5),- ImpactRegion::FollowingSiblingSubtrees(node) => (node, 6),- ImpactRegion::SiblingSequence(node) => (node, 7),- ImpactRegion::Ancestors(node) => (node, 8),- ImpactRegion::PreviousSibling(node) => (node, 9),- ImpactRegion::PrecedingSiblings(node) => (node, 10),- ImpactRegion::HostedSubtrees(node) => (node, 11),- ImpactRegion::Empty | ImpactRegion::TreeScope(_) | ImpactRegion::Document => return None,- };- Some((node, 1 << bit))- }-- fn insert(&mut self, region: ImpactRegion) -> bool {- match region {- ImpactRegion::Empty => false,- ImpactRegion::Document => {- let was_present = self.document;- self.document = true;- !was_present- }- ImpactRegion::TreeScope(scope) => {- let index = scope.0 as usize;- self.tree_scopes.set(index, true).0- }- _ => {- let (node, kind) = Self::node_and_kind(region).unwrap();- self.element_kinds.insert(node.element_index().unwrap(), kind)- }- }- }-- fn contains(&self, region: ImpactRegion) -> bool {- match region {- ImpactRegion::Empty => false,- ImpactRegion::Document => self.document,- ImpactRegion::TreeScope(scope) => self.tree_scopes.contains(scope.0 as usize),- _ => {- let (node, kind) = Self::node_and_kind(region).unwrap();- self.element_kinds.contains(node.element_index().unwrap(), kind)- }- }- }-- fn clear(&mut self) {- self.element_kinds.clear();- self.tree_scopes.clear();- self.document = false;- }-}--/// A region union compiled for repeated iteration and membership tests.-///-/// Transactions with topology coordinates retain only disjoint preorder intervals. The fallback-/// stores sorted node identities so small transactions do not pay to build a complete topology.-enum ImpactRegionBatchStorage {- PreorderIntervals(Box<[PreorderInterval]>),- Nodes(Box<[StyleNodeID]>),-}--pub(super) struct ImpactRegionBatch(ImpactRegionBatchStorage);--impl ImpactRegionBatch {- #[must_use]- pub(super) fn node_count(&self) -> usize {- match &self.0 {- ImpactRegionBatchStorage::PreorderIntervals(intervals) => intervals- .iter()- .map(|interval| (interval.end - interval.start) as usize)- .sum(),- ImpactRegionBatchStorage::Nodes(nodes) => nodes.len(),- }- }-- #[must_use]- pub(super) fn interval_count(&self) -> Option<usize> {- match &self.0 {- ImpactRegionBatchStorage::PreorderIntervals(intervals) => Some(intervals.len()),- ImpactRegionBatchStorage::Nodes(_) => None,- }- }-}--/// Transaction-local tree coordinates for repeated impact-region queries.-///-/// The live tree deliberately retains no document-order label. Once a transaction asks enough-/// region-membership questions to justify one pass over the tree, this workspace turns subtree-/// membership into an interval comparison without adding anything to the mandatory per-node state.-#[derive(Clone)]-pub(super) struct TransactionTopology {- nodes: Vec<StyleNodeID>,- preorder_by_element_index: Vec<u32>,- subtree_end_by_element_index: Vec<u32>,-}--impl TransactionTopology {- #[must_use]- fn new(tree: &StyleNodeTree, root: StyleNodeID) -> Self {- let nodes: Vec<StyleNodeID> = tree.preorder(root).collect();- let slot_count = nodes- .iter()- .filter_map(|node| node.element_index())- .max()- .map_or(0, |index| index as usize + 1);- let mut preorder_by_element_index = vec![NO_PREORDER_POSITION; slot_count];- let mut subtree_end_by_element_index = vec![NO_PREORDER_POSITION; slot_count];- let mut open = Vec::new();-- for (position, &node) in nodes.iter().enumerate() {- let parent = tree.parent(node);- while open.last().copied().is_some_and(|candidate| Some(candidate) != parent) {- let finished = open.pop().unwrap();- subtree_end_by_element_index[finished.element_slot()] =- u32::try_from(position).expect("transaction preorder space exhausted");- }- debug_assert!(node == root || open.last().copied() == parent);- preorder_by_element_index[node.element_slot()] =- u32::try_from(position).expect("transaction preorder space exhausted");- open.push(node);- }- let end = u32::try_from(nodes.len()).expect("transaction preorder space exhausted");- for node in open {- subtree_end_by_element_index[node.element_slot()] = end;- }-- Self {- nodes,- preorder_by_element_index,- subtree_end_by_element_index,- }- }-- fn preorder_position(&self, node: StyleNodeID) -> Option<u32> {- let position = *self.preorder_by_element_index.get(node.element_index()? as usize)?;- (position != NO_PREORDER_POSITION).then_some(position)- }-- fn subtree_interval(&self, root: StyleNodeID) -> Option<(u32, u32)> {- let start = self.preorder_position(root)?;- let end = *self.subtree_end_by_element_index.get(root.element_index()? as usize)?;- (end != NO_PREORDER_POSITION).then_some((start, end))- }-- #[must_use]- fn is_in_subtree_of(&self, node: StyleNodeID, root: StyleNodeID) -> Option<bool> {- let position = self.preorder_position(node)?;- let (start, end) = self.subtree_interval(root)?;- Some((start..end).contains(&position))- }-- fn push_node_interval(&self, node: StyleNodeID, intervals: &mut Vec<PreorderInterval>) -> bool {- let Some(start) = self.preorder_position(node) else {- return false;- };- intervals.push(PreorderInterval { start, end: start + 1 });- true- }-- fn collect_region_intervals(- &self,- region: ImpactRegion,- tree: &StyleNodeTree,- document_root: Option<StyleNodeID>,- intervals: &mut Vec<PreorderInterval>,- ) -> bool {- match region {- ImpactRegion::Empty => true,- // Nested shadow trees are not one preorder run, so there is no interval set to hand- // back and the caller falls back to walking the region.- ImpactRegion::HostedSubtrees(_) => false,- ImpactRegion::Node(node) => self.push_node_interval(node, intervals),- ImpactRegion::Children(parent) => {- for child in tree.children(parent) {- if !self.push_node_interval(child, intervals) {- return false;- }- }- true- }- ImpactRegion::Subtree(root) => {- let Some((start, end)) = self.subtree_interval(root) else {- return false;- };- intervals.push(PreorderInterval { start, end });- true- }- ImpactRegion::StrictSubtree(root) => {- let Some((start, end)) = self.subtree_interval(root) else {- return false;- };- if start + 1 < end {- intervals.push(PreorderInterval { start: start + 1, end });- }- true- }- ImpactRegion::NextSibling(anchor) => tree- .next_element_sibling(anchor)- .is_none_or(|node| self.push_node_interval(node, intervals)),- ImpactRegion::FollowingSiblings(anchor) => {- let mut sibling = tree.next_element_sibling(anchor);- while let Some(node) = sibling {- if !self.push_node_interval(node, intervals) {- return false;- }- sibling = tree.next_element_sibling(node);- }- true- }- ImpactRegion::FollowingSiblingSubtrees(anchor) => {- let Some(first) = tree.next_element_sibling(anchor) else {- return true;- };- let Some(parent) = tree.parent(anchor) else {- return false;- };- let Some(start) = self.preorder_position(first) else {- return false;- };- let Some((_, end)) = self.subtree_interval(parent) else {- return false;- };- intervals.push(PreorderInterval { start, end });- true- }- ImpactRegion::SiblingSequence(member) => {- let Some(parent) = tree.parent(member) else {- return self.push_node_interval(member, intervals);- };- for sibling in tree.children(parent) {- if !self.push_node_interval(sibling, intervals) {- return false;- }- }- true- }- ImpactRegion::Ancestors(node) => {- for ancestor in tree.ancestors(node) {- if !self.push_node_interval(ancestor, intervals) {- return false;- }- }- true- }- ImpactRegion::PreviousSibling(anchor) => tree- .previous_element_sibling(anchor)- .is_none_or(|node| self.push_node_interval(node, intervals)),- ImpactRegion::PrecedingSiblings(anchor) => {- let Some(parent) = tree.parent(anchor) else {- return true;- };- for sibling in tree.children(parent) {- if sibling == anchor {- break;- }- if !self.push_node_interval(sibling, intervals) {- return false;- }- }- true- }- ImpactRegion::TreeScope(_) => false,- ImpactRegion::Document => {- if self.node_count() != tree.connected_element_count() as usize {- return false;- }- let Some(root) = document_root else {- return false;- };- let Some((start, end)) = self.subtree_interval(root) else {- return false;- };- intervals.push(PreorderInterval { start, end });- true- }- }- }-- fn canonical_intervals(- &self,- regions: &[ImpactRegion],- tree: &StyleNodeTree,- document_root: Option<StyleNodeID>,- ) -> Option<Vec<PreorderInterval>> {- let mut intervals = Vec::new();- for ®ion in regions {- if !self.collect_region_intervals(region, tree, document_root, &mut intervals) {- return None;- }- }- intervals.sort_unstable();- let mut write = 0;- for read in 0..intervals.len() {- if write != 0 && intervals[read].start <= intervals[write - 1].end {- intervals[write - 1].end = intervals[write - 1].end.max(intervals[read].end);- } else {- intervals[write] = intervals[read];- write += 1;- }- }- intervals.truncate(write);- Some(intervals)- }-- fn for_each_interval(&self, interval: PreorderInterval, visit: &mut impl FnMut(StyleNodeID)) {- self.nodes[interval.start as usize..interval.end as usize]- .iter()- .copied()- .for_each(visit);- }-- #[must_use]- fn node_count(&self) -> usize {- self.nodes.len()- }-- #[must_use]- pub(super) fn nodes(&self) -> &[StyleNodeID] {- &self.nodes- }-}--/// The cursor state of one preorder walk over a `PatchCover`'s attribution intervals.-#[derive(Default)]-pub(super) struct AttributionSweep {- cursor: usize,- /// `(end, key index)` of every interval entered and not yet left, in entry order.- active: Vec<(u32, u32)>,- last_position: Option<u32>,-}--/// Compiled per-transaction patch coverage: which nodes must fully re-derive and which rules a-/// covered node's narrowed patch must include.-pub(super) struct PatchCover {- pub(super) full: ImpactRegionBatch,- /// Attributed extents as half-open preorder intervals `(start, end, key index)`, sorted.- intervals: Vec<(u32, u32, u32)>,- /// Running maximum interval end per sorted prefix, bounding the leftward stab walk.- prefix_max_end: Vec<u32>,- keys: Vec<(RuleID, EntryID)>,- /// Broad coverage needs no per-node expansion.- document_keys: Vec<(RuleID, EntryID)>,- scope_keys: Vec<(TreeScopeID, (RuleID, EntryID))>,- /// Materialized attributions without preorder coordinates, sorted by node and rule key.- exact_nodes: Vec<(StyleNodeID, (RuleID, EntryID))>,-}--/// The normalized impact plan for one transaction.-#[derive(Default)]-pub struct ImpactRegions {- regions: Vec<ImpactRegion>,- region_index: ImpactRegionIndex,- covered_subtrees: Vec<PreorderInterval>,- /// The subtrees among `covered_subtrees` that were added without attribution and therefore- /// force covered retained answers to a full re-derivation. Coverage by these alone justifies- /// dropping a route's contribution outright; coverage by an attributed subtree does not.- full_covered_subtrees: Vec<PreorderInterval>,- topology: Option<TransactionTopology>,- exact_node_generation: u64,- exact_node_history_start_generation: u64,- /// Every region added without rule attribution, in original extent: what forces a covered- /// node's retained answer to a full re-derivation.- unattributed: Vec<ImpactRegion>,- /// Rule-attributed emissions in original extent. A route naming its exact entry can prove- /// that within its region only that rule's truth moved, so a node covered exclusively by- /// attributed regions patches against the union of its covering attributions.- attributions: Vec<(ImpactRegion, (RuleID, EntryID))>,-}--impl ImpactRegions {- #[must_use]- pub fn new() -> Self {- Self {- regions: Vec::new(),- region_index: ImpactRegionIndex::default(),- covered_subtrees: Vec::new(),- full_covered_subtrees: Vec::new(),- topology: None,- exact_node_generation: 0,- exact_node_history_start_generation: 0,- unattributed: Vec::new(),- attributions: Vec::new(),- }- }-- #[must_use]- pub fn with_topology(tree: &StyleNodeTree, root: StyleNodeID) -> Self {- Self {- topology: Some(TransactionTopology::new(tree, root)),- ..Self::new()- }- }-- #[must_use]- pub fn topology_node_count(&self) -> usize {- self.topology.as_ref().map_or(0, TransactionTopology::node_count)- }-- pub(super) fn take_topology(&mut self) -> Option<TransactionTopology> {- self.topology.take()- }-- fn invalidate_exact_node_history(&mut self) {- self.exact_node_generation = self.exact_node_generation.wrapping_add(1);- self.exact_node_history_start_generation = self.exact_node_generation;- }-- /// The preorder interval a subtree-shaped region covers, which leaves out the root of a strict subtree.- fn covered_interval(&self, region: ImpactRegion) -> Option<PreorderInterval> {- let (root, strict) = match region {- ImpactRegion::Subtree(root) => (root, false),- ImpactRegion::StrictSubtree(root) => (root, true),- _ => return None,- };- let (start, end) = self.topology.as_ref()?.subtree_interval(root)?;- let start = if strict { start + 1 } else { start };- (start < end).then_some(PreorderInterval { start, end })- }-- fn insert_covered_subtree(&mut self, region: ImpactRegion) {- if let Some(interval) = self.covered_interval(region) {- Self::insert_covered_interval(&mut self.covered_subtrees, interval);- }- }-- fn insert_full_covered_subtree(&mut self, region: ImpactRegion) {- if let Some(interval) = self.covered_interval(region) {- Self::insert_covered_interval(&mut self.full_covered_subtrees, interval);- }- }-- fn insert_covered_interval(covered: &mut Vec<PreorderInterval>, interval: PreorderInterval) {- let first = covered.partition_point(|existing| existing.end < interval.start);- let count = covered[first..].partition_point(|existing| existing.start <= interval.end);- if count == 0 {- covered.insert(first, interval);- return;- }-- let last = first + count;- let merged = PreorderInterval {- start: interval.start.min(covered[first].start),- end: interval.end.max(covered[last - 1].end),- };- covered.splice(first..last, [merged]);- }-- fn rebuild_indexes(&mut self) {- self.region_index.clear();- self.covered_subtrees.clear();- self.invalidate_exact_node_history();- for index in 0..self.regions.len() {- let region = self.regions[index];- self.region_index.insert(region);- self.insert_covered_subtree(region);- }- }-- pub fn add(&mut self, region: ImpactRegion) {- if !matches!(region, ImpactRegion::Empty | ImpactRegion::Node(_)) {- self.unattributed.push(region);- }- self.insert_full_covered_subtree(region);- self.add_recorded(region);- }-- /// Add a region whose emitting route names the one rule whose truth can move within it.- /// Recorded in original extent, before merging, so patch narrowing can union the covering- /// attributions per node; duplicate adds of the same extent by unattributed routes still- /// force full re-derivation because every unattributed add is recorded independently.- pub fn add_attributed(&mut self, region: ImpactRegion, key: (RuleID, EntryID)) {- self.attribute_extent(region, key);- self.add_recorded(region);- }-- /// Record a rule attribution over a region without planning the region. A route whose- /// candidates are already planned owes the patch only the fact that its rule may have moved- /// inside its extent; this carries that fact symbolically, one row per route instead of one- /// row per (node, rule), and the per-node union is rebuilt lazily by `covering_attributions`.- pub fn attribute_extent(&mut self, region: ImpactRegion, key: (RuleID, EntryID)) {- if region != ImpactRegion::Empty {- self.attributions.push((region, key));- }- }-- fn add_recorded(&mut self, region: ImpactRegion) {- if region == ImpactRegion::Empty {- return;- }- if region == ImpactRegion::Document {- self.regions.clear();- self.region_index.clear();- self.covered_subtrees.clear();- self.full_covered_subtrees.clear();- self.invalidate_exact_node_history();- self.regions.push(ImpactRegion::Document);- self.region_index.insert(ImpactRegion::Document);- return;- }- if self.regions.first() == Some(&ImpactRegion::Document) {- return;- }- if !self.region_index.insert(region) {- return;- }- self.insert_covered_subtree(region);- if matches!(region, ImpactRegion::Node(_)) {- self.exact_node_generation = self.exact_node_generation.wrapping_add(1);- }- self.regions.push(region);- }-- #[must_use]- pub fn contains_node(&self, node: StyleNodeID) -> bool {- self.region_index.contains(ImpactRegion::Node(node))- }-- #[must_use]- pub(super) fn exact_node_generation(&self) -> u64 {- self.exact_node_generation- }-- #[must_use]- /// Visit a bounded suffix of exact-node additions when the region vector has remained in- /// append order since `generation`. Returns false when the caller must inspect the full plan.- pub(super) fn for_each_exact_node_added_after(- &self,- generation: u64,- limit: usize,- mut visit: impl FnMut(StyleNodeID),- ) -> bool {- let Some(count) = self.exact_node_generation.checked_sub(generation) else {- return false;- };- if generation < self.exact_node_history_start_generation || count > limit as u64 {- return false;- }- self.regions- .iter()- .rev()- .filter_map(|region| match region {- ImpactRegion::Node(node) => Some(*node),- _ => None,- })- .take(count as usize)- .for_each(&mut visit);- true- }-- /// Whether an already named subtree contains all of `region`.- ///- /// Arrival subtrees establish the transaction's dirty envelope before selector routing. Asking- /// this through the region set keeps a route that stays inside that envelope from doing any- /// candidate discovery or exact matching merely to emit a region normalization will discard.- #[must_use]- pub fn is_covered_by_subtree(&self, region: ImpactRegion, tree: &StyleNodeTree) -> bool {- let (ImpactRegion::Node(node)- | ImpactRegion::Children(node)- | ImpactRegion::Subtree(node)- | ImpactRegion::StrictSubtree(node)) = region- else {- return false;- };- if let Some(position) = self- .topology- .as_ref()- .and_then(|topology| topology.preorder_position(node))- {- let index = self- .covered_subtrees- .partition_point(|interval| interval.end <= position);- return self- .covered_subtrees- .get(index)- .is_some_and(|interval| interval.start <= position);- }- self.region_index.contains(ImpactRegion::Subtree(node))- || tree- .ancestors(node)- .any(|ancestor| self.region_index.contains(ImpactRegion::Subtree(ancestor)))- }-- /// Whether a subtree that forces full re-derivation contains all of `region`. Coverage by an- /// attributed subtree keeps a node planned but narrows its patch to the covering rules, so- /// only this stronger cover justifies forgetting a route's contribution or a walk's diff- /// outright.- #[must_use]- pub fn is_covered_by_full_subtree(&self, region: ImpactRegion, tree: &StyleNodeTree) -> bool {- if self.covers_document() {- return true;- }- let (ImpactRegion::Node(node)- | ImpactRegion::Children(node)- | ImpactRegion::Subtree(node)- | ImpactRegion::StrictSubtree(node)) = region- else {- return false;- };- if let Some(position) = self- .topology- .as_ref()- .and_then(|topology| topology.preorder_position(node))- {- let index = self- .full_covered_subtrees- .partition_point(|interval| interval.end <= position);- return self- .full_covered_subtrees- .get(index)- .is_some_and(|interval| interval.start <= position);- }- self.unattributed.contains(&ImpactRegion::Subtree(node))- || tree- .ancestors(node)- .any(|ancestor| self.unattributed.contains(&ImpactRegion::Subtree(ancestor)))- }-- #[must_use]- pub fn region_contains_node(&self, region: ImpactRegion, node: StyleNodeID, tree: &StyleNodeTree) -> bool {- region.contains_node_with_topology(node, tree, self.topology.as_ref())- }-- /// Order pending nodes so popping the vector visits every parent before its descendants.- ///- /// A wide transaction already paid for preorder coordinates. Reverse preorder in the backing- /// vector gives the same top-down pop order as sorting by depth, without walking every node's- /// ancestors again.- ///- /// Small transactions have no coordinates, but a rightward-propagating walk still needs- /// exact document order, so the pending set derives it directly: each node keys by its- /// ancestor path of sibling ordinals, making an ancestor's key a strict prefix of its- /// descendants' and ordering siblings by ordinal. The ordinal memo bounds sibling counting- /// to one walk per distinct prefix, so the cost stays proportional to the pending set.- ///- /// Returns whether the order is exact document preorder within every root's subtree.- pub(super) fn sort_nodes_for_top_down_walk(&self, nodes: &mut [StyleNodeID], tree: &StyleNodeTree) -> bool {- if let Some(topology) = &self.topology- && nodes.iter().all(|&node| topology.preorder_position(node).is_some())- {- nodes.sort_unstable_by_key(|&node| std::cmp::Reverse(topology.preorder_position(node).unwrap()));- return true;- }-- // The topology branch above implicitly proved every pending node live in the document- // scope, because only those nodes have preorder positions. The derived order can only- // claim exactness under the same precondition: a detached or shadow-scoped node has no- // place in document order, and the sibling walk must not run over a set containing one.- if !nodes- .iter()- .all(|&node| tree.is_live(node) && tree.tree_scope(node) == TreeScopeID::DOCUMENT)- {- nodes.sort_unstable_by_key(|&node| std::cmp::Reverse(tree.ancestors(node).count()));- return false;- }- let mut ordinals: super::HashMap<StyleNodeID, u32> = super::HashMap::default();- let mut run = Vec::new();- let mut ordinal_of = |node: StyleNodeID| -> u32 {- run.clear();- let mut current = node;- let mut ordinal = loop {- if let Some(&known) = ordinals.get(¤t) {- break known;- }- run.push(current);- match tree.previous_element_sibling(current) {- Some(previous) => current = previous,- None => break u32::MAX,- }- };- while let Some(reached) = run.pop() {- ordinal = ordinal.wrapping_add(1);- ordinals.insert(reached, ordinal);- }- ordinals[&node]- };- let mut keyed: Vec<(Vec<u32>, StyleNodeID)> = nodes- .iter()- .map(|&node| {- let mut path: Vec<u32> = std::iter::once(node)- .chain(tree.ancestors(node))- .map(&mut ordinal_of)- .collect();- path.reverse();- (path, node)- })- .collect();- keyed.sort_unstable_by(|left, right| right.0.cmp(&left.0));- for (slot, (_, node)) in nodes.iter_mut().zip(keyed) {- *slot = node;- }- true- }-- /// Partition subtree roots into the outer roots and those already covered by one.- ///- /// The input order is scratch. Results retain identity order for callers that use binary- /// search after the interval scan.- pub(super) fn partition_subtree_roots(- &self,- nodes: &mut [StyleNodeID],- ) -> Option<(Vec<StyleNodeID>, Vec<StyleNodeID>)> {- let topology = self.topology.as_ref()?;- if !nodes.iter().all(|&node| topology.subtree_interval(node).is_some()) {- return None;- }- nodes.sort_unstable_by_key(|&node| topology.preorder_position(node).unwrap());-- let mut outer = Vec::new();- let mut nested = Vec::new();- let mut covered_end = 0;- for &node in nodes.iter() {- let (start, end) = topology.subtree_interval(node).unwrap();- if start < covered_end {- nested.push(node);- } else {- outer.push(node);- covered_end = end;- }- }- outer.sort_unstable();- nested.sort_unstable();- Some((outer, nested))- }-- /// Collect the complement of the subtree intervals already covered by the plan.- ///- /// The topology's backing nodes are in preorder, so every uncovered range is one contiguous- /// slice. Callers must first prove that the topology covers every tree they need to inspect.- pub(super) fn nodes_outside_covered_subtrees(&self) -> Option<Vec<StyleNodeID>> {- let topology = self.topology.as_ref()?;- let covered_nodes: usize = self- .covered_subtrees- .iter()- .map(|interval| (interval.end - interval.start) as usize)- .sum();- let mut nodes = Vec::with_capacity(topology.nodes.len().saturating_sub(covered_nodes));- let mut cursor = 0;- for interval in &self.covered_subtrees {- nodes.extend_from_slice(&topology.nodes[cursor..interval.start as usize]);- cursor = interval.end as usize;- }- nodes.extend_from_slice(&topology.nodes[cursor..]);- Some(nodes)- }-- pub fn add_if_not_covered(&mut self, region: ImpactRegion, tree: &StyleNodeTree) {- if self.is_covered_by_subtree(region, tree) {- return;- }- self.add(region);- }-- /// Normalize: drop duplicates and regions contained in another. The relation each surviving- /// region was named with is preserved.- pub fn normalize(&mut self, tree: &StyleNodeTree) {- self.regions.sort_unstable();- self.regions.dedup();- if self.regions.len() > MAX_PAIRWISE_COALESCE {- self.invalidate_exact_node_history();- return;- }- let mut kept: Vec<ImpactRegion> = Vec::with_capacity(self.regions.len());- for ®ion in &self.regions {- let absorbed = kept- .iter()- .any(|&other| other.contains_with_topology(region, tree, self.topology.as_ref()));- if absorbed {- continue;- }- kept.retain(|&other| !region.contains_with_topology(other, tree, self.topology.as_ref()));- kept.push(region);- }- self.regions = kept;- self.rebuild_indexes();- }-- pub fn widen_to_document(&mut self, counters: &Counters) {- counters.bump(Counter::DocumentWidenings);- self.regions.clear();- self.region_index.clear();- self.covered_subtrees.clear();- self.full_covered_subtrees.clear();- self.invalidate_exact_node_history();- self.regions.push(ImpactRegion::Document);- self.region_index.insert(ImpactRegion::Document);- }-- #[must_use]- pub fn regions(&self) -> &[ImpactRegion] {- &self.regions- }-- /// Whether no narrower contribution can change the plan any further.- #[must_use]- pub fn covers_document(&self) -> bool {- self.regions.first() == Some(&ImpactRegion::Document)- }-- pub fn for_each(&self, tree: &StyleNodeTree, document_root: Option<StyleNodeID>, visit: impl FnMut(StyleNodeID)) {- self.for_each_union(&self.regions, tree, document_root, visit);- }-- /// Stream a union of regions once.- ///- /// A transaction topology compiles the union into disjoint preorder intervals, so a subtree is- /// represented by two coordinates and overlapping routes disappear before any node is visited.- /// Small transactions without a topology retain the relation-walking fallback.- pub(super) fn for_each_union(- &self,- regions: &[ImpactRegion],- tree: &StyleNodeTree,- document_root: Option<StyleNodeID>,- mut visit: impl FnMut(StyleNodeID),- ) {- let batch = self.compile_union(regions, tree, document_root);- self.for_each_batch(&batch, &mut visit);- }-- #[must_use]- /// Compile the transaction's patch coverage: the unattributed regions as the full- /// re-derivation trigger, and the attributed emissions as stabbable preorder intervals- /// carrying rule keys. Extents without coordinates are materialized once and indexed by- /// identity, rather than testing their tree relationships again for every candidate.- pub(super) fn compile_patch_cover(&self, tree: &StyleNodeTree, document_root: Option<StyleNodeID>) -> PatchCover {- let mut keys: Vec<(RuleID, EntryID)> = Vec::new();- let mut key_indices: super::HashMap<(RuleID, EntryID), u32> = super::HashMap::default();- let mut intervals: Vec<(u32, u32, u32)> = Vec::new();- let mut document_keys = Vec::new();- let mut scope_keys = Vec::new();- let mut exact_nodes = Vec::new();- let mut scratch: Vec<PreorderInterval> = Vec::new();- for &(region, key) in &self.attributions {- scratch.clear();- if !self- .topology- .as_ref()- .is_some_and(|topology| topology.collect_region_intervals(region, tree, document_root, &mut scratch))- {- // OPTIMIZATION: Resolve fallback coverage once, not once per candidate node.- // Document and scope coverage remain compact even for large trees.- match region {- ImpactRegion::Document => document_keys.push(key),- ImpactRegion::TreeScope(scope) => scope_keys.push((scope, key)),- // Preserve the membership predicate for hosted forests and parentless sibling- // sequences, whose coverage differs from the region's streaming traversal.- ImpactRegion::HostedSubtrees(_) => {- exact_nodes.extend(- tree.live_nodes().filter_map(|node| {- self.region_contains_node(region, node, tree).then_some((node, key))- }),- );- }- ImpactRegion::SiblingSequence(member) if tree.parent(member).is_none() => {- exact_nodes.extend(- tree.live_nodes()- .filter_map(|node| tree.parent(node).is_none().then_some((node, key))),- );- }- ImpactRegion::FollowingSiblingSubtrees(anchor) if tree.parent(anchor).is_none() => {}- _ => region.for_each(tree, |node| exact_nodes.push((node, key))),- }- continue;- }- let key_index = match key_indices.get(&key).copied() {- Some(index) => index,- None => {- let index = u32::try_from(keys.len()).expect("patch attribution key space exhausted");- keys.push(key);- key_indices.insert(key, index);- index- }- };- for interval in &scratch {- intervals.push((interval.start, interval.end, key_index));- }- }- document_keys.sort_unstable();- document_keys.dedup();- scope_keys.sort_unstable();- scope_keys.dedup();- exact_nodes.sort_unstable();- exact_nodes.dedup();- intervals.sort_unstable();- intervals.dedup();- let mut prefix_max_end = Vec::with_capacity(intervals.len());- let mut max_end = 0u32;- for &(_, end, _) in &intervals {- max_end = max_end.max(end);- prefix_max_end.push(max_end);- }- PatchCover {- full: self.compile_union(&self.unattributed, tree, document_root),- intervals,- prefix_max_end,- keys,- document_keys,- scope_keys,- exact_nodes,- }- }-- /// Collect the rule keys of every attributed region covering `node` into `out`, deduplicated.- /// Returns `false` when the node has no preorder position, in which case the caller must fall- /// back to full re-derivation.- ///- /// The batch walk visits nodes in nondecreasing preorder position, so coverage is answered by- /// a sweep that consumes each interval once: route-extent attributions can stack thousands of- /// intervals per transaction, and a per-node backward stab would rescan the dead ones behind- /// every long-lived interval. A node visited out of order falls back to a direct stab without- /// disturbing the sweep.- pub(super) fn covering_attributions(- &self,- cover: &PatchCover,- tree: &StyleNodeTree,- sweep: &mut AttributionSweep,- node: StyleNodeID,- out: &mut Vec<(RuleID, EntryID)>,- ) -> bool {- out.clear();- let first = cover.exact_nodes.partition_point(|&(candidate, _)| candidate < node);- out.extend(- cover.exact_nodes[first..]- .iter()- .take_while(|&&(candidate, _)| candidate == node)- .map(|&(_, key)| key),- );- out.extend_from_slice(&cover.document_keys);- let scope = tree.tree_scope(node);- let first = cover.scope_keys.partition_point(|&(candidate, _)| candidate < scope);- out.extend(- cover.scope_keys[first..]- .iter()- .take_while(|&&(candidate, _)| candidate == scope)- .map(|&(_, key)| key),- );- if cover.intervals.is_empty() {- out.sort_unstable();- out.dedup();- return true;- }- let Some(topology) = &self.topology else {- return false;- };- let Some(position) = topology.preorder_position(node) else {- return false;- };- if sweep.last_position.is_some_and(|last| position < last) {- self.stab_covering_attributions(cover, position, out);- } else {- sweep.last_position = Some(position);- while let Some(&(start, end, key_index)) = cover.intervals.get(sweep.cursor) {- if start > position {- break;- }- if end > position {- sweep.active.push((end, key_index));- }- sweep.cursor += 1;- }- sweep.active.retain(|&(end, _)| end > position);- out.extend(- sweep- .active- .iter()- .map(|&(_, key_index)| cover.keys[key_index as usize]),- );- }- // Route-extent attributions can stack many covering rules on one node, so dedup by sort- // instead of a quadratic membership scan.- out.sort_unstable();- out.dedup();- true- }-- fn stab_covering_attributions(&self, cover: &PatchCover, position: u32, out: &mut Vec<(RuleID, EntryID)>) {- let mut index = cover.intervals.partition_point(|&(start, _, _)| start <= position);- while index > 0 {- index -= 1;- if cover.prefix_max_end[index] <= position {- break;- }- let (start, end, key_index) = cover.intervals[index];- if start <= position && position < end {- out.push(cover.keys[key_index as usize]);- }- }- }-- pub(super) fn compile_union(- &self,- regions: &[ImpactRegion],- tree: &StyleNodeTree,- document_root: Option<StyleNodeID>,- ) -> ImpactRegionBatch {- if let Some(topology) = &self.topology- && let Some(intervals) = topology.canonical_intervals(regions, tree, document_root)- {- return ImpactRegionBatch(ImpactRegionBatchStorage::PreorderIntervals(intervals.into()));- }-- let mut seen: Vec<StyleNodeID> = Vec::new();- for ®ion in regions {- region.for_each(tree, |node| seen.push(node));- }- seen.sort_unstable();- seen.dedup();- ImpactRegionBatch(ImpactRegionBatchStorage::Nodes(seen.into()))- }-- pub(super) fn for_each_batch(&self, batch: &ImpactRegionBatch, mut visit: impl FnMut(StyleNodeID)) {- match &batch.0 {- ImpactRegionBatchStorage::PreorderIntervals(intervals) => {- let topology = self- .topology- .as_ref()- .expect("preorder intervals require transaction topology");- for &interval in intervals {- topology.for_each_interval(interval, &mut visit);- }- }- ImpactRegionBatchStorage::Nodes(nodes) => nodes.iter().copied().for_each(visit),- }- }-- #[must_use]- pub(super) fn batch_contains_node(&self, batch: &ImpactRegionBatch, node: StyleNodeID) -> bool {- match &batch.0 {- ImpactRegionBatchStorage::PreorderIntervals(intervals) => {- let topology = self- .topology- .as_ref()- .expect("preorder intervals require transaction topology");- let Some(position) = topology.preorder_position(node) else {- return false;- };- let index = intervals.partition_point(|interval| interval.end <= position);- intervals.get(index).is_some_and(|interval| interval.start <= position)- }- ImpactRegionBatchStorage::Nodes(nodes) => nodes.binary_search(&node).is_ok(),- }- }-- #[must_use]- pub(super) fn union_contains_node(- &self,- regions: &[ImpactRegion],- node: StyleNodeID,- tree: &StyleNodeTree,- ) -> bool {- regions- .iter()- .any(|®ion| region.contains_node_with_topology(node, tree, self.topology.as_ref()))- }-}--/// Which way to evaluate a region.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub enum Plan {- /// Drive from a candidate source of known exact size, proving region membership per candidate.- Selective { candidates: usize },- /// Sweep the region once, reading local facts directly.- ExactBatch { nodes: usize },- /// Keep the routed region because neither exact execution strategy is available.- Conservative,-}--/// A selective plan is only worth its per-candidate membership proofs while the candidate source is-/// substantially smaller than the region. Past a quarter of the region, sweeping is cheaper.-pub const SELECTIVE_SHARE_DIVISOR: usize = 4;--/// Choose between a selective walk and an exact batch sweep.-///-/// `candidate_cardinality` is `None` when no exact count is available. That is deliberately not an-/// invitation to estimate: without an exact number an available batch plan is chosen, because-/// guessing low commits to a selective walk over a scope that a single sweep would have handled.-/// If neither exact strategy is executable, the routed region remains conservative.-#[must_use]-pub fn choose_plan(region_nodes: usize, candidate_cardinality: Option<usize>, exact_batch_available: bool) -> Plan {- let Some(candidates) = candidate_cardinality else {- return match exact_batch_available {- true => Plan::ExactBatch { nodes: region_nodes },- false => Plan::Conservative,- };- };- if exact_batch_available && candidates.saturating_mul(SELECTIVE_SHARE_DIVISOR) > region_nodes {- return Plan::ExactBatch { nodes: region_nodes };- }- Plan::Selective { candidates }-}--#[cfg(test)]-mod tests {- use super::*;-- /// `root > [a > [a1, a2], b > b1, c > c1]`- struct Fixture {- tree: StyleNodeTree,- nodes: Vec<StyleNodeID>,- counters: Counters,- }-- impl Fixture {- fn new() -> Self {- let mut tree = StyleNodeTree::new();- let nodes: Vec<StyleNodeID> = (0..8).map(|_| tree.allocate_element()).collect();- // root=0, children a=1, b=2, c=3; a's children a1=4, a2=5- tree.set_first_element_child(nodes[0], Some(nodes[1]));- for index in 1..4 {- tree.set_parent(nodes[index], Some(nodes[0]));- tree.set_next_element_sibling(nodes[index], nodes.get(index + 1).filter(|_| index < 3).copied());- }- tree.set_first_element_child(nodes[1], Some(nodes[4]));- tree.set_parent(nodes[4], Some(nodes[1]));- tree.set_parent(nodes[5], Some(nodes[1]));- tree.set_next_element_sibling(nodes[4], Some(nodes[5]));- for (parent, child) in [(nodes[2], nodes[6]), (nodes[3], nodes[7])] {- tree.set_first_element_child(parent, Some(child));- tree.set_parent(child, Some(parent));- }-- Self {- tree,- nodes,- counters: Counters::new(),- }- }-- fn collect(&self, region: ImpactRegion) -> Vec<usize> {- let mut visited = Vec::new();- region.for_each(&self.tree, |node| {- visited.push(self.nodes.iter().position(|other| *other == node).unwrap());- });- visited- }- }-- #[test]- fn each_region_streams_the_relation_it_was_named_with() {- let fixture = Fixture::new();- assert_eq!(fixture.collect(ImpactRegion::Node(fixture.nodes[1])), vec![1]);- assert_eq!(fixture.collect(ImpactRegion::Children(fixture.nodes[0])), vec![1, 2, 3]);- assert_eq!(fixture.collect(ImpactRegion::Subtree(fixture.nodes[1])), vec![1, 4, 5]);- assert_eq!(fixture.collect(ImpactRegion::NextSibling(fixture.nodes[1])), vec![2]);- assert_eq!(- fixture.collect(ImpactRegion::FollowingSiblings(fixture.nodes[1])),- vec![2, 3]- );- assert_eq!(- fixture.collect(ImpactRegion::FollowingSiblingSubtrees(fixture.nodes[1])),- vec![2, 6, 3, 7]- );- assert_eq!(- fixture.collect(ImpactRegion::SiblingSequence(fixture.nodes[2])),- vec![1, 2, 3]- );- assert_eq!(- fixture.collect(ImpactRegion::Document),- vec![0, 1, 2, 3, 4, 5, 6, 7],- "the document region streams every live identity"- );- }-- #[test]- fn a_document_region_includes_shadow_tree_scopes() {- let mut tree = StyleNodeTree::new();- let document_root = tree.allocate_element();- let host = tree.allocate_element();- let shadow_root = tree.allocate_element();- let shadow_child = tree.allocate_element();- tree.set_first_element_child(document_root, Some(host));- tree.set_parent(host, Some(document_root));- tree.set_first_element_child(shadow_root, Some(shadow_child));- tree.set_parent(shadow_child, Some(shadow_root));- tree.enable_tree_scopes();- tree.set_tree_scope(shadow_root, TreeScopeID(1));- tree.set_tree_scope(shadow_child, TreeScopeID(1));- tree.set_shadow_root(host, shadow_root);-- let mut visited = Vec::new();- ImpactRegion::Document.for_each(&tree, |node| visited.push(node));- assert_eq!(visited, vec![document_root, host, shadow_root, shadow_child]);-- visited.clear();- ImpactRegion::TreeScope(TreeScopeID(1)).for_each(&tree, |node| visited.push(node));- assert_eq!(visited, vec![shadow_root, shadow_child]);- }-- #[test]- fn a_transpose_path_folds_into_one_region() {- let fixture = Fixture::new();- let node = fixture.nodes[0];-- assert_eq!(- ImpactRegion::follow(node, &[InverseStep::Descendants], &fixture.tree),- ImpactRegion::StrictSubtree(node)- );- assert_eq!(- ImpactRegion::follow(node, &[InverseStep::Children], &fixture.tree),- ImpactRegion::Children(node)- );- // `.a > .b .c`: children, then their descendants, which stays below the node.- assert_eq!(- ImpactRegion::follow(node, &[InverseStep::Children, InverseStep::Descendants], &fixture.tree),- ImpactRegion::StrictSubtree(node)- );- // An empty path is the changed node itself.- assert_eq!(ImpactRegion::follow(node, &[], &fixture.tree), ImpactRegion::Node(node));- }-- #[test]- fn descendants_of_following_siblings_keep_their_forest_boundary() {- let fixture = Fixture::new();- let region = ImpactRegion::follow(- fixture.nodes[1],- &[InverseStep::FollowingSiblings, InverseStep::Descendants],- &fixture.tree,- );- assert_eq!(region, ImpactRegion::FollowingSiblingSubtrees(fixture.nodes[1]));- assert!(region.contains_node(fixture.nodes[2], &fixture.tree));- assert!(region.contains_node(fixture.nodes[3], &fixture.tree));- assert!(region.contains_node(fixture.nodes[6], &fixture.tree));- assert!(region.contains_node(fixture.nodes[7], &fixture.tree));- assert!(!region.contains_node(fixture.nodes[1], &fixture.tree));- assert!(!region.contains_node(fixture.nodes[4], &fixture.tree));- assert!(region.contains_with_topology(ImpactRegion::Subtree(fixture.nodes[6]), &fixture.tree, None));- assert!(!region.contains_with_topology(ImpactRegion::Subtree(fixture.nodes[4]), &fixture.tree, None));- assert_eq!(- region.step(InverseStep::FollowingSiblings, &fixture.tree),- region,- "a following-sibling step cannot leave the forest"- );- assert_eq!(- region.step(InverseStep::SiblingSequence, &fixture.tree),- ImpactRegion::Subtree(fixture.nodes[0]),- "a whole-sequence step can cross the forest's leading boundary"- );-- assert_eq!(- ImpactRegion::follow(- fixture.nodes[1],- &[InverseStep::NextSibling, InverseStep::Descendants],- &fixture.tree,- ),- ImpactRegion::Subtree(fixture.nodes[2])- );- assert!(- ImpactRegion::Subtree(fixture.nodes[2]).contains_node(fixture.nodes[6], &fixture.tree),- "the adjacent sibling's descendants remain reachable"- );- }-- #[test]- fn a_sibling_step_out_of_a_subtree_widens_to_the_parent() {- let fixture = Fixture::new();- // Siblings of `a` itself lie outside `a`, so the region climbs.- assert_eq!(- ImpactRegion::Subtree(fixture.nodes[1]).step(InverseStep::FollowingSiblings, &fixture.tree),- ImpactRegion::Subtree(fixture.nodes[0])- );- }-- #[test]- fn a_sibling_step_below_a_node_stays_below_it() {- let fixture = Fixture::new();- let a = fixture.nodes[1];- // `.a .b ~ .c` and `.a > .b + .c`: siblings of something below `a` share a parent below or at `a`.- assert_eq!(- ImpactRegion::follow(- a,- &[InverseStep::Descendants, InverseStep::FollowingSiblings],- &fixture.tree- ),- ImpactRegion::StrictSubtree(a)- );- assert_eq!(- ImpactRegion::follow(a, &[InverseStep::Children, InverseStep::NextSibling], &fixture.tree),- ImpactRegion::Children(a)- );- // `.a > * > .b + .c`: the shape of `li.done > div > .toggle + label`.- assert_eq!(- ImpactRegion::follow(- a,- &[InverseStep::Children, InverseStep::Children, InverseStep::NextSibling],- &fixture.tree- ),- ImpactRegion::StrictSubtree(a)- );- assert_eq!(fixture.collect(ImpactRegion::StrictSubtree(a)), vec![4, 5]);- }-- #[test]- fn normalization_absorbs_contained_regions_and_keeps_the_relation() {- let fixture = Fixture::new();- let mut regions = ImpactRegions::new();- regions.add(ImpactRegion::Subtree(fixture.nodes[1]));- regions.add(ImpactRegion::Node(fixture.nodes[4]));- regions.add(ImpactRegion::Node(fixture.nodes[2]));- regions.add(ImpactRegion::Subtree(fixture.nodes[1]));- regions.normalize(&fixture.tree);-- assert_eq!(regions.regions().len(), 2);- assert!(regions.regions().contains(&ImpactRegion::Subtree(fixture.nodes[1])));- assert!(regions.regions().contains(&ImpactRegion::Node(fixture.nodes[2])));- }-- #[test]- fn duplicate_nodes_are_discarded_as_the_plan_is_built() {- let fixture = Fixture::new();- let mut regions = ImpactRegions::new();- regions.add(ImpactRegion::Node(fixture.nodes[1]));- regions.add(ImpactRegion::Node(fixture.nodes[1]));-- assert_eq!(regions.regions(), &[ImpactRegion::Node(fixture.nodes[1])]);- assert!(regions.contains_node(fixture.nodes[1]));- }-- #[test]- fn dense_region_index_distinguishes_region_kinds_for_one_node() {- let fixture = Fixture::new();- let mut regions = ImpactRegions::new();- let node = fixture.nodes[1];- let node_regions = [- ImpactRegion::Node(node),- ImpactRegion::Children(node),- ImpactRegion::Subtree(node),- ImpactRegion::StrictSubtree(node),- ImpactRegion::NextSibling(node),- ImpactRegion::FollowingSiblings(node),- ImpactRegion::FollowingSiblingSubtrees(node),- ImpactRegion::SiblingSequence(node),- ImpactRegion::Ancestors(node),- ImpactRegion::PreviousSibling(node),- ImpactRegion::PrecedingSiblings(node),- ];-- for region in node_regions {- regions.add(region);- regions.add(region);- }-- assert_eq!(regions.regions(), node_regions);- }-- #[test]- fn dense_region_index_allocates_only_touched_element_pages() {- let mut index = ImpactRegionIndex::default();- let element = StyleNodeID::element(1_000_000);-- assert!(index.insert(ImpactRegion::Node(element)));- assert!(index.insert(ImpactRegion::Subtree(element)));- assert!(!index.insert(ImpactRegion::Node(element)));- assert!(index.contains(ImpactRegion::Node(element)));- assert!(index.contains(ImpactRegion::Subtree(element)));- }-- #[test]- fn a_document_region_absorbs_everything_after_it() {- let fixture = Fixture::new();- let mut regions = ImpactRegions::new();- regions.add(ImpactRegion::Node(fixture.nodes[4]));- regions.add(ImpactRegion::Document);- regions.add(ImpactRegion::Subtree(fixture.nodes[1]));- assert_eq!(regions.regions(), &[ImpactRegion::Document]);- }-- #[test]- fn widening_replaces_the_plan_rather_than_adding_to_it() {- let fixture = Fixture::new();- let mut regions = ImpactRegions::new();- regions.add(ImpactRegion::Node(fixture.nodes[4]));- regions.widen_to_document(&fixture.counters);- assert_eq!(regions.regions(), &[ImpactRegion::Document]);- assert_eq!(fixture.counters.get(Counter::DocumentWidenings), 1);- }-- #[test]- fn a_plan_is_selective_only_while_its_candidate_source_is_small() {- assert_eq!(choose_plan(1000, Some(100), true), Plan::Selective { candidates: 100 });- // A quarter of the region is the cutoff.- assert_eq!(choose_plan(1000, Some(250), true), Plan::Selective { candidates: 250 });- assert_eq!(choose_plan(1000, Some(251), true), Plan::ExactBatch { nodes: 1000 });- }-- #[test]- fn an_unknown_cardinality_chooses_the_batch_rather_than_guessing() {- assert_eq!(choose_plan(1000, None, true), Plan::ExactBatch { nodes: 1000 });- }-- #[test]- fn an_unavailable_batch_plan_is_never_selected() {- assert_eq!(choose_plan(1000, Some(999), false), Plan::Selective { candidates: 999 });- assert_eq!(choose_plan(1000, None, false), Plan::Conservative);- }-- #[test]- fn transaction_topology_answers_subtree_queries_and_streams_regions() {- let fixture = Fixture::new();- let topology = TransactionTopology::new(&fixture.tree, fixture.nodes[0]);-- assert_eq!(topology.node_count(), 8);- assert_eq!(- topology.is_in_subtree_of(fixture.nodes[4], fixture.nodes[1]),- Some(true)- );- assert_eq!(- topology.is_in_subtree_of(fixture.nodes[2], fixture.nodes[1]),- Some(false)- );-- let regions = [- ImpactRegion::Empty,- ImpactRegion::Node(fixture.nodes[1]),- ImpactRegion::Children(fixture.nodes[0]),- ImpactRegion::Subtree(fixture.nodes[1]),- ImpactRegion::StrictSubtree(fixture.nodes[1]),- ImpactRegion::StrictSubtree(fixture.nodes[4]),- ImpactRegion::NextSibling(fixture.nodes[1]),- ImpactRegion::NextSibling(fixture.nodes[3]),- ImpactRegion::FollowingSiblings(fixture.nodes[1]),- ImpactRegion::FollowingSiblings(fixture.nodes[3]),- ImpactRegion::FollowingSiblingSubtrees(fixture.nodes[1]),- ImpactRegion::FollowingSiblingSubtrees(fixture.nodes[3]),- ImpactRegion::SiblingSequence(fixture.nodes[2]),- ImpactRegion::Ancestors(fixture.nodes[4]),- ImpactRegion::Ancestors(fixture.nodes[0]),- ImpactRegion::PreviousSibling(fixture.nodes[2]),- ImpactRegion::PreviousSibling(fixture.nodes[1]),- ImpactRegion::PrecedingSiblings(fixture.nodes[3]),- ImpactRegion::PrecedingSiblings(fixture.nodes[1]),- ImpactRegion::Document,- ];- for region in regions {- let mut intervals = Vec::new();- assert!(topology.collect_region_intervals(region, &fixture.tree, Some(fixture.nodes[0]), &mut intervals));- let mut actual = Vec::new();- for interval in intervals {- topology.for_each_interval(interval, &mut |node| {- actual.push(fixture.nodes.iter().position(|other| *other == node).unwrap());- });- }- let mut expected = fixture.collect(region);- if region == ImpactRegion::Document {- actual.sort_unstable();- expected.sort_unstable();- }- assert_eq!(actual, expected, "{region:?}");- }-- let mut intervals = Vec::new();- assert!(!topology.collect_region_intervals(- ImpactRegion::TreeScope(TreeScopeID::DOCUMENT),- &fixture.tree,- Some(fixture.nodes[0]),- &mut intervals,- ));- }-- #[test]- fn transaction_topology_orders_pending_nodes_without_depth_walks() {- let fixture = Fixture::new();- let regions = ImpactRegions::with_topology(&fixture.tree, fixture.nodes[0]);- let mut pending = vec![- fixture.nodes[7],- fixture.nodes[1],- fixture.nodes[4],- fixture.nodes[0],- fixture.nodes[2],- ];-- regions.sort_nodes_for_top_down_walk(&mut pending, &fixture.tree);-- assert_eq!(- pending.into_iter().rev().collect::<Vec<_>>(),- vec![- fixture.nodes[0],- fixture.nodes[1],- fixture.nodes[4],- fixture.nodes[2],- fixture.nodes[7],- ]- );- }-- #[test]- fn transaction_topology_partitions_nested_subtree_roots() {- let fixture = Fixture::new();- let regions = ImpactRegions::with_topology(&fixture.tree, fixture.nodes[0]);- let mut roots = vec![fixture.nodes[7], fixture.nodes[4], fixture.nodes[2], fixture.nodes[1]];-- let (outer, nested) = regions.partition_subtree_roots(&mut roots).unwrap();-- assert_eq!(outer, vec![fixture.nodes[1], fixture.nodes[2], fixture.nodes[7]]);- assert_eq!(nested, vec![fixture.nodes[4]]);- }-- #[test]- fn transaction_topology_collects_the_complement_of_covered_subtrees() {- let fixture = Fixture::new();- let mut regions = ImpactRegions::with_topology(&fixture.tree, fixture.nodes[0]);- regions.add(ImpactRegion::Subtree(fixture.nodes[1]));- regions.add(ImpactRegion::Subtree(fixture.nodes[7]));-- assert_eq!(- regions.nodes_outside_covered_subtrees().unwrap(),- vec![fixture.nodes[0], fixture.nodes[2], fixture.nodes[6], fixture.nodes[3]]- );- }-- #[test]- fn transaction_topology_merges_overlapping_regions_into_intervals() {- let fixture = Fixture::new();- let topology = TransactionTopology::new(&fixture.tree, fixture.nodes[0]);- let intervals = topology- .canonical_intervals(- &[- ImpactRegion::Subtree(fixture.nodes[1]),- ImpactRegion::Node(fixture.nodes[4]),- ImpactRegion::FollowingSiblingSubtrees(fixture.nodes[1]),- ],- &fixture.tree,- Some(fixture.nodes[0]),- )- .unwrap();-- assert_eq!(intervals, vec![PreorderInterval { start: 1, end: 8 }]);- }-- #[test]- fn compiled_region_batches_iterate_and_test_membership_without_node_arrays() {- let fixture = Fixture::new();- let plan = ImpactRegions::with_topology(&fixture.tree, fixture.nodes[0]);- let regions = [- ImpactRegion::Subtree(fixture.nodes[1]),- ImpactRegion::Node(fixture.nodes[4]),- ImpactRegion::FollowingSiblingSubtrees(fixture.nodes[1]),- ];- let batch = plan.compile_union(®ions, &fixture.tree, Some(fixture.nodes[0]));-- assert_eq!(batch.interval_count(), Some(1));- assert_eq!(batch.node_count(), 7);-- let mut actual = Vec::new();- plan.for_each_batch(&batch, |node| actual.push(node));- assert_eq!(- actual,- vec![- fixture.nodes[1],- fixture.nodes[4],- fixture.nodes[5],- fixture.nodes[2],- fixture.nodes[6],- fixture.nodes[3],- fixture.nodes[7],- ]- );- for &node in &fixture.nodes[1..] {- assert!(plan.batch_contains_node(&batch, node));- }- assert!(!plan.batch_contains_node(&batch, fixture.nodes[0]));- }-- #[test]- fn impact_regions_use_transaction_topology_for_subtree_membership() {- let fixture = Fixture::new();- let regions = ImpactRegions::with_topology(&fixture.tree, fixture.nodes[0]);- let region = ImpactRegion::Subtree(fixture.nodes[1]);-- assert!(regions.region_contains_node(region, fixture.nodes[4], &fixture.tree));- assert!(!regions.region_contains_node(region, fixture.nodes[2], &fixture.tree));- }-- #[test]- fn covered_subtree_queries_use_coalesced_preorder_intervals() {- let fixture = Fixture::new();- let mut regions = ImpactRegions::with_topology(&fixture.tree, fixture.nodes[0]);- regions.add(ImpactRegion::Subtree(fixture.nodes[1]));- regions.add(ImpactRegion::Subtree(fixture.nodes[4]));-- assert_eq!(regions.covered_subtrees, [PreorderInterval { start: 1, end: 4 }]);-- assert!(regions.is_covered_by_subtree(ImpactRegion::Node(fixture.nodes[4]), &fixture.tree));- assert!(regions.is_covered_by_subtree(ImpactRegion::Children(fixture.nodes[5]), &fixture.tree));- assert!(!regions.is_covered_by_subtree(ImpactRegion::Subtree(fixture.nodes[2]), &fixture.tree));- }-- #[test]- fn fallback_patch_attributions_match_region_membership() {- let fixture = Fixture::new();- let nodes = &fixture.nodes;- let extents = [- ImpactRegion::Node(nodes[1]),- ImpactRegion::Children(nodes[0]),- ImpactRegion::Subtree(nodes[1]),- ImpactRegion::StrictSubtree(nodes[1]),- ImpactRegion::NextSibling(nodes[1]),- ImpactRegion::FollowingSiblings(nodes[1]),- ImpactRegion::FollowingSiblingSubtrees(nodes[1]),- ImpactRegion::SiblingSequence(nodes[2]),- ImpactRegion::SiblingSequence(nodes[0]),- ImpactRegion::Ancestors(nodes[4]),- ImpactRegion::PreviousSibling(nodes[2]),- ImpactRegion::PrecedingSiblings(nodes[3]),- ImpactRegion::TreeScope(TreeScopeID::DOCUMENT),- ImpactRegion::Document,- ];- let mut regions = ImpactRegions::new();- for (index, ®ion) in extents.iter().enumerate() {- let key = (RuleID(index as u32 + 1), EntryID(index as u32 + 1));- regions.attribute_extent(region, key);- regions.attribute_extent(region, key);- }- let cover = regions.compile_patch_cover(&fixture.tree, Some(nodes[0]));- assert!(cover.intervals.is_empty());- assert_eq!(cover.document_keys.len(), 1);- assert_eq!(cover.scope_keys.len(), 1);- let mut sweep = AttributionSweep::default();- let mut covering = Vec::new();- for &node in nodes.iter().rev() {- assert!(regions.covering_attributions(&cover, &fixture.tree, &mut sweep, node, &mut covering));- let expected: Vec<_> = extents- .iter()- .enumerate()- .filter_map(|(index, ®ion)| {- region- .contains_node(node, &fixture.tree)- .then_some((RuleID(index as u32 + 1), EntryID(index as u32 + 1)))- })- .collect();- assert_eq!(covering, expected);- }- }-- #[test]- fn patch_attributions_are_indexed_without_preorder_coordinates() {- let mut tree = StyleNodeTree::new();- let root = tree.allocate_element();- let host = tree.allocate_element();- let shadow_root = tree.allocate_element();- tree.set_first_element_child(root, Some(host));- tree.set_parent(host, Some(root));- tree.enable_tree_scopes();- tree.set_tree_scope(shadow_root, TreeScopeID(1));- tree.set_shadow_root(host, shadow_root);- let nodes: Vec<_> = (0..128).map(|_| tree.allocate_element()).collect();- tree.set_first_element_child(shadow_root, Some(nodes[0]));- for (index, &node) in nodes.iter().enumerate() {- tree.set_parent(node, Some(shadow_root));- tree.set_tree_scope(node, TreeScopeID(1));- tree.set_next_element_sibling(node, nodes.get(index + 1).copied());- }- let descendants: Vec<_> = nodes- .iter()- .map(|&node| {- let child = tree.allocate_element();- tree.set_parent(child, Some(node));- tree.set_tree_scope(child, TreeScopeID(1));- tree.set_first_element_child(node, Some(child));- child- })- .collect();- for with_topology in [false, true] {- let mut regions = if with_topology {- ImpactRegions::with_topology(&tree, root)- } else {- ImpactRegions::new()- };- for (index, &node) in nodes.iter().enumerate() {- let key = (RuleID(index as u32 + 1), EntryID(index as u32 + 1));- regions.attribute_extent(ImpactRegion::Subtree(node), key);- regions.attribute_extent(ImpactRegion::Node(node), key);- }- let cover = regions.compile_patch_cover(&tree, Some(root));- assert_eq!(cover.exact_nodes.len(), nodes.len() + descendants.len());- let mut sweep = AttributionSweep::default();- let mut covering = Vec::new();- for (index, &node) in nodes.iter().enumerate().rev() {- assert!(regions.covering_attributions(&cover, &tree, &mut sweep, node, &mut covering));- assert_eq!(covering, [(RuleID(index as u32 + 1), EntryID(index as u32 + 1))]);- assert!(regions.covering_attributions(&cover, &tree, &mut sweep, descendants[index], &mut covering));- assert_eq!(covering, [(RuleID(index as u32 + 1), EntryID(index as u32 + 1))]);- }- assert!(regions.covering_attributions(&cover, &tree, &mut sweep, host, &mut covering));- assert!(covering.is_empty());-- let hosted_key = (RuleID(1000), EntryID(1000));- regions.attribute_extent(ImpactRegion::HostedSubtrees(host), hosted_key);- let cover = regions.compile_patch_cover(&tree, Some(root));- for node in tree.live_nodes() {- assert!(regions.covering_attributions(&cover, &tree, &mut sweep, node, &mut covering));- assert_eq!(- covering.contains(&hosted_key),- ImpactRegion::HostedSubtrees(host).contains_node(node, &tree),- );- }- }- }-}diff --git a/Libraries/LibWeb/Rust/src/css/style/index.rs b/Libraries/LibWeb/Rust/src/css/style/index.rsindex ca0a523efe5..659e460ae47 100644--- a/Libraries/LibWeb/Rust/src/css/style/index.rs+++ b/Libraries/LibWeb/Rust/src/css/style/index.rs@@ -9,7 +9,7 @@//! An atom is a document-local `u32` standing for a tag/namespace pair, an ID, a class, an//! attribute name, an attribute value, a namespace, or a state fact. C++ assigns the identities//! because it owns the authoritative string payloads; Rust stores only the `u32` in bytecode,-//! postings, and journal keys, and never a duplicate of the string. Interning a name on the C+++//! postings, and input keys, and never a duplicate of the string. Interning a name on the C++//! side is a hash lookup plus a reference count bump on a string that already exists, so a feature//! comparison costs an integer compare and no conversion.//!@@ -19,6021 +19,11 @@//! attribute and not the shape of the test applied to it. Only those tests need the value as text,//! and only for the attributes an attached program actually mentions.-use super::AncestorDispatchShape;-use super::column::BitColumn;-use super::column::Column;-use super::column::EpochColumn;-use super::column::PagedColumn;-use super::column::PagedColumnPage;-use super::column::PagedValuePage;-use super::column::RemovablePagedColumnPage;-use super::column::advance_epoch;-use super::fast_hash::FastMap as HashMap;-use super::fast_hash::FastSet as HashSet;-use super::shared_vector::{SharedVector, SharedVectorPool};-use crate::css::style_value::RetainedStyleValueData;-use std::cmp::Reverse;-use std::num::NonZeroU32;-use std::sync::Arc;--use super::partial_view::Lookup;-use super::prefix::PrefixAutomaton;-use super::program::CustomDeclaration;-use super::program::DeclaredProperty;-use super::program::EntryID;-use super::program::RuleID;-use super::program::SelectorProgramID;-use super::sorted_merge::SortedMergeEntry;-use super::sorted_merge::merge_sorted_by;-use super::transaction::ElementDeclarationKind;-use super::transaction::StateFact;-use super::tree::StyleNodeID;--define_id! {- /// Document-local identity of an interned selector-mentioned feature. Obeys the same generation- /// and non-reuse rules as [`super::tree::StyleNodeID`].- 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- }-}--/// 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,- /// Every fact an element announced while it was arriving, as one key.- ///- /// An element publishes its tag, its id, its classes, its attributes and its states as it- /// connects, and journalling each of them separately is what a page of a few thousand elements- /// spends its whole transaction budget on. They all describe the same event, so the journal- /// keeps one entry per arriving element and routing reads the facts back off the element.- ArrivingFacts,-}--/// 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)]-pub struct AttributeFact {- pub name: StyleAtomID,- pub value: StyleAtomID,-}--/// 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,-}--#[derive(Clone)]-struct PagedCopyColumn<T: Copy + Default> {- values: PagedColumn<PagedValuePage<T>>,- indices: Vec<usize>,-}--impl<T: Copy + Default> Default for PagedCopyColumn<T> {- fn default() -> Self {- Self {- values: PagedColumn::default(),- indices: Vec::new(),- }- }-}--impl<T: Copy + Default> PagedCopyColumn<T> {- fn get(&self, index: usize) -> Option<T> {- self.values.get(index)- }-- fn insert(&mut self, index: usize, value: T) {- let (previous, _) = self.values.insert(index, value);- if previous.is_none() {- self.indices.push(index);- }- }-- fn indexed_iter(&self) -> impl Iterator<Item = (usize, T)> + '_ {- self.indices.iter().copied().map(|index| {- (- index,- self.values.get(index).expect("paged column index must remain present"),- )- })- }-}--#[derive(Clone)]-struct PagedOwnedColumn<T: Clone + Default> {- handles: PagedColumn<PagedValuePage<u32>>,- values: Vec<T>,- indices: Vec<usize>,-}--impl<T: Clone + Default> Default for PagedOwnedColumn<T> {- fn default() -> Self {- Self {- handles: PagedColumn::default(),- values: Vec::new(),- indices: Vec::new(),- }- }-}--impl<T: Clone + Default> PagedOwnedColumn<T> {- fn get(&self, index: usize) -> Option<&T> {- let handle = self.handles.get(index)? as usize;- self.values.get(handle)- }-- fn get_mut(&mut self, index: usize) -> Option<&mut T> {- let handle = self.handles.get(index)? as usize;- self.values.get_mut(handle)- }-- fn entry(&mut self, index: usize) -> &mut T {- let handle = match self.handles.get(index) {- Some(handle) => handle,- None => {- let handle = u32::try_from(self.values.len()).expect("paged owned column handle overflow");- self.values.push(T::default());- self.indices.push(index);- self.handles.insert(index, handle);- handle- }- };- &mut self.values[handle as usize]- }-- fn insert(&mut self, index: usize, value: T) {- *self.entry(index) = value;- }-- #[cfg(test)]- fn iter(&self) -> impl Iterator<Item = &T> {- self.values.iter()- }-- fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> {- self.values.iter_mut()- }-- fn indexed_iter_mut(&mut self) -> impl Iterator<Item = (usize, &mut T)> {- self.indices.iter().copied().zip(self.values.iter_mut())- }-}--#[derive(Clone, Default)]-struct AttributeCatalogs {- name_forms: PagedCopyColumn<AttributeNameForms>,- /// The local name an `attr()` reads an attribute by, kept only for an attribute in no- /// namespace, which is the only kind substitution reads.- substitution_names: PagedOwnedColumn<Option<Box<[u16]>>>,- value_texts: PagedOwnedColumn<Option<Box<[u16]>>>,- language_texts: PagedOwnedColumn<Option<Box<[u16]>>>,-}--const NO_ROW: u32 = u32::MAX;--#[derive(Clone, Copy, Default)]-struct PayloadHandle {- offset: u32,- length: u32,-}--impl PayloadHandle {- fn appended_to<T>(payload: &mut Vec<T>, values: &[T]) -> Self- where- T: Clone,- {- let offset = u32::try_from(payload.len()).expect("fact payload offset overflow");- payload.extend_from_slice(values);- Self {- offset,- length: u32::try_from(values.len()).expect("fact payload length overflow"),- }- }-- fn slice<T>(self, payload: &[T]) -> &[T] {- let start = self.offset as usize;- &payload[start..start + self.length as usize]- }-}--#[derive(Clone, Copy, Default)]-struct RareFacts {- heading_level: u8,- part_exposure: StyleAtomID,- custom_states: PayloadHandle,- parts: PayloadHandle,-}--#[derive(Clone, Copy)]-struct PrimaryFactSnapshot {- tag: StyleAtomID,- folded_tag: StyleAtomID,- id: StyleAtomID,- states: StateSet,- directionality: StyleAtomID,- language: StyleAtomID,- has_text_content: bool,- namespace: StyleAtomID,- rare_facts: Option<RareFacts>,- class_handle: PayloadHandle,- attribute_handle: PayloadHandle,-}--const RARE_FACT_PAGE_SHIFT: usize = 6;-const RARE_FACT_PAGE_SIZE: usize = 1 << RARE_FACT_PAGE_SHIFT;--#[derive(Clone)]-struct RareFactPage {- rows: [Option<RareFacts>; RARE_FACT_PAGE_SIZE],-}--impl Default for RareFactPage {- fn default() -> Self {- Self {- rows: [None; RARE_FACT_PAGE_SIZE],- }- }-}--impl PagedColumnPage for RareFactPage {- type Value = RareFacts;-- const SHIFT: usize = RARE_FACT_PAGE_SHIFT;-- fn get(&self, index: usize) -> Option<Self::Value> {- self.rows[index]- }-- fn insert(&mut self, index: usize, value: Self::Value) {- self.rows[index] = Some(value);- }-}--impl RemovablePagedColumnPage for RareFactPage {- fn remove(&mut self, index: usize) -> Option<Self::Value> {- self.rows[index].take()- }-}--/// The next unique batch-row-space name; see `StyleNodeFacts::generation`.-fn next_batch_generation() -> u64 {- static NEXT: std::sync::atomic::AtomicU64 = std::sync::atomic::AtomicU64::new(1);- NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)-}--/// Columnar local facts for style nodes.-///-/// `ElementFactStore` owns one instance as the required document projection. Bounded before-side-/// and selective-evaluation batches reuse the same physical row format without becoming another-/// source of truth.-///-/// Rows are addressed by element index so that following a tree relation into another row is an-/// array lookup rather than a search. That directness is the point: relation steps have to stay-/// inside the evaluator.-#[derive(Clone, Default)]-pub struct StyleNodeFacts {- attribute_catalogs: Arc<AttributeCatalogs>,- primary: bool,- resident: BitColumn,- rare_facts: PagedColumn<RareFactPage>,- nodes: Vec<StyleNodeID>,- row_by_element_index: Vec<u32>,- /// Bloom summary of every dispatch key carried by a row, excluding document-root status.- dispatch_bloom: Vec<u64>,- /// Rows no longer reachable through the element mapping. The primary arrangement repoints an- /// element to a freshly packed row when its facts move; the old row stays as garbage until- /// its measured carrying cost makes one rebuild cheaper than retaining it.- stale_rows: u32,- /// Payload bytes no live primary row references any more. Replacing or forgetting a row leaves- /// its old payload in the shared payload arrays until enough of it is stale to repack them.- stale_payload_bytes: u64,- live_rows: usize,- /// Names this batch's row space. Consumers holding row indices across calls compare it:- /// clearing a batch renumbers every row, so anything indexed by row is stale the moment the- /// generation moves. Appending keeps the generation, since existing rows keep their places.- /// Zero marks a default-constructed batch whose consumers must never trust held rows.- generation: u64,-- tag: Vec<StyleAtomID>,- /// The ASCII-lowercase folding of `tag`, or none when the name is already lowercase. Dispatch- /// buckets rules under a type selector's folded form, so a candidate has to probe both.- folded_tag: Vec<StyleAtomID>,- id: Vec<StyleAtomID>,- states: Vec<StateSet>,- /// Values the parameterized state operators test: the element's resolved directionality, its- /// resolved language, and its heading level where it has one.- directionality: Vec<StyleAtomID>,- language: Vec<StyleAtomID>,- /// Whether the element holds a text or comment child that keeps it from being `:empty`.- has_text_content: Vec<bool>,- /// The element's resolved language tag as a range into `text`. `:lang()` compares extended- /// language ranges against it, and a range is not a name, so the atom cannot answer the test.- language_text: Vec<(u32, u32)>,- /// The element's namespace URI, keyed by its text. A type or universal selector constrains it- /// whenever it was written with a prefix or its sheet declared a default namespace.- namespace: Vec<StyleAtomID>,- heading_level: Vec<u8>,- custom_state_handles: Vec<PayloadHandle>,- custom_states: Vec<StyleAtomID>,- /// The part names the element is exposed under. `::part()` dispatches on one, so a row that did- /// not carry them would make every such rule unreachable rather than merely slower.- part_handles: Vec<PayloadHandle>,- parts: Vec<StyleAtomID>,- /// The host a `::part()` rule addresses the element from, which `exportparts` moves outwards.- /// The outer compound of such a rule describes that host and not the one the part sits under.- part_exposure: Vec<StyleAtomID>,-- class_handles: Vec<PayloadHandle>,- classes: Vec<StyleAtomID>,- attribute_handles: Vec<PayloadHandle>,- attributes: Vec<AttributeFact>,-- /// Batch-local UTF-16 for language tags and non-interned attribute values.- text: Vec<u16>,-}--#[derive(Clone)]--pub(super) struct MatchingFactBatch {- facts: Arc<StyleNodeFacts>,-}--impl MatchingFactBatch {- fn owned(facts: StyleNodeFacts) -> Self {- Self { facts: Arc::new(facts) }- }-- fn primary_view(facts: Arc<StyleNodeFacts>) -> Self {- Self { facts }- }-}--impl std::ops::Deref for MatchingFactBatch {- type Target = StyleNodeFacts;-- fn deref(&self) -> &Self::Target {- &self.facts- }-}--impl From<StyleNodeFacts> for MatchingFactBatch {- fn from(facts: StyleNodeFacts) -> Self {- Self::owned(facts)- }-}--impl StyleNodeFacts {- #[must_use]- pub fn new() -> Self {- Self {- generation: next_batch_generation(),- ..Self::default()- }- }-- fn new_primary() -> Self {- Self {- primary: true,- generation: next_batch_generation(),- ..Self::default()- }- }-- /// Append one row. Rows must be appended in the order the batch reports them.- pub fn push_row(- &mut self,- node: StyleNodeID,- tag: StyleAtomID,- id: StyleAtomID,- states: StateSet,- classes: &[StyleAtomID],- attributes: &[AttributeFact],- ) {- assert!(!self.primary, "cannot append a batch row to primary facts");- let row = u32::try_from(self.nodes.len()).expect("fact batch row space exhausted");- self.nodes.push(node);- self.tag.push(tag);- self.folded_tag.push(StyleAtomID::NONE);- self.id.push(id);- self.states.push(states);- self.directionality.push(StyleAtomID::NONE);- self.language.push(StyleAtomID::NONE);- self.has_text_content.push(false);- self.language_text.push((0, 0));- self.namespace.push(StyleAtomID::NONE);- self.heading_level.push(0);- self.custom_state_handles.push(PayloadHandle::default());- self.part_handles.push(PayloadHandle::default());- self.part_exposure.push(StyleAtomID::NONE);- self.class_handles- .push(PayloadHandle::appended_to(&mut self.classes, classes));- self.attribute_handles- .push(PayloadHandle::appended_to(&mut self.attributes, attributes));- self.dispatch_bloom.push(0);- self.dispatch_bloom[row as usize] = self.compute_dispatch_bloom_of(row);-- self.map_row(node, row);- }-- /// Append one row from another packed fact arrangement without materializing an owned row.- fn push_row_from(&mut self, node: StyleNodeID, source: &Self, source_row: u32) {- assert!(!self.primary, "cannot append a batch row to primary facts");- let row = u32::try_from(self.nodes.len()).expect("fact batch row space exhausted");- self.nodes.push(node);- self.tag.push(source.tag_of(source_row));- self.folded_tag.push(source.folded_tag_of(source_row));- self.id.push(source.id_of(source_row));- self.states.push(source.states_of(source_row));- self.directionality.push(source.directionality_of(source_row));- self.language.push(source.language_of(source_row));- self.has_text_content.push(source.has_text_content_of(source_row));- let language_text = source.language_tag_of(source_row);- let language_offset = u32::try_from(self.text.len()).expect("fact text space exhausted");- self.text.extend_from_slice(language_text);- self.language_text.push((- language_offset,- u32::try_from(language_text.len()).expect("fact text space exhausted"),- ));- self.namespace.push(source.namespace_of(source_row));- self.heading_level.push(source.heading_level_of(source_row));- self.custom_state_handles.push(PayloadHandle::appended_to(- &mut self.custom_states,- source.custom_states_of(source_row),- ));- self.part_handles- .push(PayloadHandle::appended_to(&mut self.parts, source.parts_of(source_row)));- self.part_exposure.push(source.part_exposure_of(source_row));- self.class_handles.push(PayloadHandle::appended_to(- &mut self.classes,- source.classes_of(source_row),- ));- let attribute_start = u32::try_from(self.attributes.len()).expect("attribute payload offset overflow");- self.attributes.extend_from_slice(source.attributes_of(source_row));- self.attribute_handles.push(PayloadHandle {- offset: attribute_start,- length: u32::try_from(self.attributes.len()).expect("attribute payload overflow") - attribute_start,- });- self.dispatch_bloom.push(0);- self.dispatch_bloom[row as usize] = self.compute_dispatch_bloom_of(row);-- self.map_row(node, row);- }-- fn primary_snapshot(&self, row: u32) -> PrimaryFactSnapshot {- assert!(self.primary);- PrimaryFactSnapshot {- tag: self.tag_of(row),- folded_tag: self.folded_tag_of(row),- id: self.id_of(row),- states: self.states_of(row),- directionality: self.directionality_of(row),- language: self.language_of(row),- has_text_content: self.has_text_content_of(row),- namespace: self.namespace_of(row),- rare_facts: self.rare_facts.get(row as usize),- class_handle: self.class_handles[row as usize],- attribute_handle: self.attribute_handles[row as usize],- }- }-- fn push_row_from_primary_snapshot(&mut self, node: StyleNodeID, source: &Self, snapshot: PrimaryFactSnapshot) {- assert!(!self.primary);- assert!(source.primary);- let rare_facts = snapshot.rare_facts.unwrap_or_default();- self.push_row(- node,- snapshot.tag,- snapshot.id,- snapshot.states,- snapshot.class_handle.slice(&source.classes),- snapshot.attribute_handle.slice(&source.attributes),- );- self.set_row_folded_tag(snapshot.folded_tag);- self.set_row_namespace(snapshot.namespace);- self.set_row_part_exposure(rare_facts.part_exposure);- self.set_row_has_text_content(snapshot.has_text_content);- let row = u32::try_from(self.row_count() - 1).expect("fact batch row space exhausted");- self.set_row_parameters(- row,- snapshot.directionality,- snapshot.language,- rare_facts.heading_level,- rare_facts.custom_states.slice(&source.custom_states),- rare_facts.parts.slice(&source.parts),- );- }-- fn map_row(&mut self, node: StyleNodeID, row: u32) {- debug_assert!(!self.primary);- let Some(index) = node.element_index() else {- return;- };- let index = index as usize;- if index >= self.row_by_element_index.len() {- self.row_by_element_index.resize(index + 1, NO_ROW);- }- if self.row_by_element_index[index] != NO_ROW {- self.stale_rows += 1;- } else {- self.live_rows += 1;- }- self.row_by_element_index[index] = row;- }-- #[must_use]- pub fn row_count(&self) -> usize {- if self.primary { self.tag.len() } else { self.nodes.len() }- }-- #[must_use]- pub fn node_at(&self, row: u32) -> StyleNodeID {- if self.primary {- assert!(self.resident.contains(row as usize));- StyleNodeID::element(row)- } else {- self.nodes[row as usize]- }- }-- #[must_use]- pub fn has_row(&self, row: u32) -> bool {- let row = row as usize;- if self.primary {- self.resident.contains(row)- } else {- row < self.nodes.len() && self.row_of(self.nodes[row]) == u32::try_from(row).ok()- }- }-- /// The row holding `node`'s facts, or `None` when the batch does not cover it. A miss is not a- /// negative answer: it means the evaluator has to widen or ask for a different batch.- /// Detach one element's row from the mapping, leaving the packed row as garbage.- pub fn forget_row(&mut self, node: StyleNodeID) {- let Some(index) = node.element_index() else {- return;- };- if self.primary {- if !self.resident.contains(index as usize) {- return;- }- self.stale_payload_bytes += self.payload_bytes_of_row(index);- self.resident.set(index as usize, false);- self.live_rows -= 1;- self.rare_facts.remove(index as usize);- self.class_handles[index as usize] = PayloadHandle::default();- self.attribute_handles[index as usize] = PayloadHandle::default();- return;- }- if let Some(slot) = self.row_by_element_index.get_mut(index as usize)- && *slot != NO_ROW- {- *slot = NO_ROW;- self.stale_rows += 1;- self.live_rows -= 1;- }- }-- #[must_use]- #[cfg(test)]- pub fn stale_rows(&self) -> u32 {- if self.primary { 0 } else { self.stale_rows }- }-- #[must_use]- pub fn generation(&self) -> u64 {- self.generation- }-- #[must_use]- pub fn row_of(&self, node: StyleNodeID) -> Option<u32> {- let index = node.element_index()? as usize;- if self.primary {- return self- .resident- .contains(index)- .then(|| u32::try_from(index).expect("element fact row exceeds u32"));- }- match self.row_by_element_index.get(index) {- Some(&NO_ROW) | None => None,- Some(&row) => Some(row),- }- }-- #[must_use]- pub fn live_row_count(&self) -> usize {- self.live_rows- }-- fn set_primary_row(&mut self, node: StyleNodeID, facts: &StagedFactRow) {- assert!(self.primary, "cannot index a primary row in a batch");- let row = node.element_index().expect("fact row must be an element") as usize;- let was_resident = self.resident.contains(row);- self.live_rows += usize::from(!was_resident);- let old_rare_facts = was_resident.then(|| self.rare_facts.get(row)).flatten();- let old_class_handle = was_resident.then(|| self.class_handles[row]);- let old_attribute_handle = was_resident.then(|| self.attribute_handles[row]);- let mut stale_payload_bytes = 0_u64;- if row >= self.tag.len() {- let length = row.checked_add(1).expect("element fact row space exhausted");- self.tag.resize(length, StyleAtomID::NONE);- self.folded_tag.resize(length, StyleAtomID::NONE);- self.id.resize(length, StyleAtomID::NONE);- self.states.resize(length, StateSet::default());- self.directionality.resize(length, StyleAtomID::NONE);- self.language.resize(length, StyleAtomID::NONE);- self.has_text_content.resize(length, false);- self.language_text.resize(length, (0, 0));- self.namespace.resize(length, StyleAtomID::NONE);- self.class_handles.resize(length, PayloadHandle::default());- self.attribute_handles.resize(length, PayloadHandle::default());- self.dispatch_bloom.resize(length, 0);- }-- self.tag[row] = facts.tag;- self.folded_tag[row] = facts.folded_tag;- self.id[row] = facts.id;- self.states[row] = facts.states;- self.directionality[row] = facts.directionality;- self.language[row] = facts.language;- self.has_text_content[row] = facts.has_text_content;- self.language_text[row] = (0, 0);- self.namespace[row] = facts.namespace;- if facts.heading_level != 0- || !facts.custom_states.is_empty()- || !facts.parts.is_empty()- || !facts.part_exposure.is_none()- {- let custom_states = old_rare_facts- .filter(|old| old.custom_states.slice(&self.custom_states) == facts.custom_states)- .map_or_else(- || {- stale_payload_bytes += old_rare_facts.map_or(0, |old| {- size_of_val(old.custom_states.slice(&self.custom_states)) as u64- });- PayloadHandle::appended_to(&mut self.custom_states, &facts.custom_states)- },- |old| old.custom_states,- );- let parts = old_rare_facts- .filter(|old| old.parts.slice(&self.parts) == facts.parts)- .map_or_else(- || {- stale_payload_bytes +=- old_rare_facts.map_or(0, |old| size_of_val(old.parts.slice(&self.parts)) as u64);- PayloadHandle::appended_to(&mut self.parts, &facts.parts)- },- |old| old.parts,- );- self.rare_facts.insert(- row,- RareFacts {- heading_level: facts.heading_level,- part_exposure: facts.part_exposure,- custom_states,- parts,- },- );- } else {- stale_payload_bytes += old_rare_facts.map_or(0, |old| {- (size_of_val(old.custom_states.slice(&self.custom_states)) + size_of_val(old.parts.slice(&self.parts)))- as u64- });- self.rare_facts.remove(row);- }- self.class_handles[row] = old_class_handle- .filter(|old| old.slice(&self.classes) == facts.classes)- .unwrap_or_else(|| {- stale_payload_bytes += old_class_handle.map_or(0, |old| size_of_val(old.slice(&self.classes)) as u64);- PayloadHandle::appended_to(&mut self.classes, &facts.classes)- });- let attributes_are_unchanged = old_attribute_handle.is_some_and(|old| {- old.slice(&self.attributes)- .iter()- .map(|attribute| (attribute.name, attribute.value))- .eq(facts.attributes.iter().copied())- });- if !attributes_are_unchanged {- stale_payload_bytes +=- old_attribute_handle.map_or(0, |old| size_of_val(old.slice(&self.attributes)) as u64);- let offset = u32::try_from(self.attributes.len()).expect("fact payload offset overflow");- self.attributes.extend(- facts- .attributes- .iter()- .map(|&(name, value)| AttributeFact { name, value }),- );- self.attribute_handles[row] = PayloadHandle {- offset,- length: u32::try_from(facts.attributes.len()).expect("fact payload length overflow"),- };- }- self.resident.set(row, true);- self.dispatch_bloom[row] = self.compute_dispatch_bloom_of(row as u32);- self.stale_payload_bytes += stale_payload_bytes;- }-- /// Record the folded name of the row just pushed. Only a name that is not already lowercase- /// has one.- pub fn set_row_folded_tag(&mut self, folded: StyleAtomID) {- let row = self.folded_tag.len() - 1;- self.folded_tag[row] = folded;- if !folded.is_none() {- self.dispatch_bloom[row] |= dispatch_bloom_bit(DispatchKey::TagName(folded));- }- }-- /// Set the namespace of the row just pushed.- pub fn set_row_namespace(&mut self, namespace: StyleAtomID) {- let row = self.namespace.len() - 1;- self.namespace[row] = namespace;- }-- pub fn set_row_part_exposure(&mut self, exposure: StyleAtomID) {- let row = self.part_exposure.len() - 1;- self.part_exposure[row] = exposure;- }-- #[must_use]- pub fn tag_of(&self, row: u32) -> StyleAtomID {- self.tag[row as usize]- }-- #[must_use]- pub fn folded_tag_of(&self, row: u32) -> StyleAtomID {- self.folded_tag[row as usize]- }-- #[must_use]- pub fn id_of(&self, row: u32) -> StyleAtomID {- self.id[row as usize]- }-- #[must_use]- pub fn states_of(&self, row: u32) -> StateSet {- self.states[row as usize]- }-- /// Set the values the parameterized state operators read for the row just pushed.- pub fn set_row_parameters(- &mut self,- row: u32,- directionality: StyleAtomID,- language: StyleAtomID,- heading_level: u8,- custom_states: &[StyleAtomID],- parts: &[StyleAtomID],- ) {- self.directionality[row as usize] = directionality;- self.language[row as usize] = language;- self.heading_level[row as usize] = heading_level;- // Custom states are appended for the last row only, which is the order rows are built in.- self.custom_state_handles[row as usize] = PayloadHandle::appended_to(&mut self.custom_states, custom_states);- self.part_handles[row as usize] = PayloadHandle::appended_to(&mut self.parts, parts);- let mut bloom = self.dispatch_bloom[row as usize];- if !directionality.is_none() {- bloom |= dispatch_bloom_bit(DispatchKey::Directionality(directionality));- }- if heading_level != 0 {- bloom |= dispatch_bloom_bit(DispatchKey::Heading);- }- for &state in custom_states {- bloom |= dispatch_bloom_bit(DispatchKey::CustomState(state));- }- for &part in parts {- bloom |= dispatch_bloom_bit(DispatchKey::Part(part));- }- self.dispatch_bloom[row as usize] = bloom;- }-- #[must_use]- pub fn directionality_of(&self, row: u32) -> StyleAtomID {- self.directionality[row as usize]- }-- #[must_use]- pub fn language_of(&self, row: u32) -> StyleAtomID {- self.language[row as usize]- }-- #[must_use]- pub fn namespace_of(&self, row: u32) -> StyleAtomID {- self.namespace[row as usize]- }-- #[must_use]- pub fn has_text_content_of(&self, row: u32) -> bool {- self.has_text_content[row as usize]- }-- /// Set whether the row just pushed holds text or comment content.- pub fn set_row_has_text_content(&mut self, has_text_content: bool) {- let row = self.has_text_content.len() - 1;- self.has_text_content[row] = has_text_content;- }-- /// The element's resolved language tag, empty when it has none.- #[must_use]- pub fn language_tag_of(&self, row: u32) -> &[u16] {- let (offset, length) = self.language_text[row as usize];- if length != 0 {- return &self.text[offset as usize..(offset + length) as usize];- }- self.attribute_catalogs- .language_texts- .get(self.language_of(row).0 as usize)- .and_then(Option::as_deref)- .unwrap_or_default()- }-- #[must_use]- pub fn heading_level_of(&self, row: u32) -> u8 {- if self.primary {- self.rare_facts.get(row as usize).map_or(0, |facts| facts.heading_level)- } else {- self.heading_level[row as usize]- }- }-- #[must_use]- pub fn part_exposure_of(&self, row: u32) -> StyleAtomID {- if self.primary {- self.rare_facts- .get(row as usize)- .map_or(StyleAtomID::NONE, |facts| facts.part_exposure)- } else {- self.part_exposure[row as usize]- }- }-- #[must_use]- pub fn custom_states_of(&self, row: u32) -> &[StyleAtomID] {- let handle = if self.primary {- self.rare_facts- .get(row as usize)- .map_or(PayloadHandle::default(), |facts| facts.custom_states)- } else {- self.custom_state_handles[row as usize]- };- handle.slice(&self.custom_states)- }-- #[must_use]- pub fn parts_of(&self, row: u32) -> &[StyleAtomID] {- let handle = if self.primary {- self.rare_facts- .get(row as usize)- .map_or(PayloadHandle::default(), |facts| facts.parts)- } else {- self.part_handles[row as usize]- };- handle.slice(&self.parts)- }-- #[must_use]- pub fn classes_of(&self, row: u32) -> &[StyleAtomID] {- self.class_handles[row as usize].slice(&self.classes)- }-- #[must_use]- pub fn attributes_of(&self, row: u32) -> &[AttributeFact] {- self.attribute_handles[row as usize].slice(&self.attributes)- }-- #[must_use]- #[cfg(test)]- pub fn attribute_of(&self, row: u32, name: StyleAtomID) -> Option<AttributeFact> {- self.attributes_of(row)- .iter()- .copied()- .find(|attribute| attribute.name == name)- }-- /// Visit every dispatch probe this row carries.- ///- /// Attribute probes retain the value of the attribute that supplied the name. A selector- /// dispatch can therefore reject value-constrained entries without allocating an intermediate- /// name-to-value table. Other probes carry no value.- pub fn for_each_dispatch_probe(- &self,- row: u32,- is_document_root: bool,- mut visit: impl FnMut(DispatchKey, Option<StyleAtomID>),- ) {- visit(DispatchKey::Universal, None);- for fact in self.states_of(row).facts() {- visit(DispatchKey::State(fact), None);- }- if is_document_root {- visit(DispatchKey::Root, None);- }- if self.heading_level_of(row) != 0 {- visit(DispatchKey::Heading, None);- }- visit(DispatchKey::TagName(self.tag_of(row)), None);- let folded_tag = self.folded_tag_of(row);- if !folded_tag.is_none() {- visit(DispatchKey::TagName(folded_tag), None);- }- let id = self.id_of(row);- if !id.is_none() {- visit(DispatchKey::Id(id), None);- }- for &class in self.classes_of(row) {- visit(DispatchKey::Class(class), None);- }- let directionality = self.directionality_of(row);- if !directionality.is_none() {- visit(DispatchKey::Directionality(directionality), None);- }- for &state in self.custom_states_of(row) {- visit(DispatchKey::CustomState(state), None);- }- for &part in self.parts_of(row) {- visit(DispatchKey::Part(part), None);- }- for attribute in self.attributes_of(row) {- // 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.- visit(DispatchKey::AttributeName(attribute.name), Some(attribute.value));- let forms = self.attribute_name_forms(attribute.name);- let aliases = [forms.local, forms.folded_name, forms.folded_local];- for (index, &other) in aliases.iter().enumerate() {- if !other.is_none() && other != attribute.name && !aliases[..index].contains(&other) {- visit(DispatchKey::AttributeName(other), Some(attribute.value));- }- }- }- }-- /// Visit every dispatch key this row carries.- pub fn for_each_dispatch_key(&self, row: u32, is_document_root: bool, mut visit: impl FnMut(DispatchKey)) {- self.for_each_dispatch_probe(row, is_document_root, |key, _| visit(key));- }-- #[must_use]- fn compute_dispatch_bloom_of(&self, row: u32) -> u64 {- let mut bloom = 0;- self.for_each_dispatch_key(row, false, |key| bloom |= dispatch_bloom_bit(key));- bloom- }-- #[must_use]- pub fn dispatch_bloom_of(&self, row: u32, is_document_root: bool) -> u64 {- self.dispatch_bloom[row as usize]- | if is_document_root {- dispatch_bloom_bit(DispatchKey::Root)- } else {- 0- }- }-- #[must_use]- pub fn carries_dispatch_key(&self, row: u32, key: DispatchKey, is_root: bool) -> bool {- match key {- DispatchKey::Part(part) => self.parts_of(row).contains(&part),- DispatchKey::CustomState(state) => self.custom_states_of(row).contains(&state),- DispatchKey::Id(id) => self.id_of(row) == id,- DispatchKey::Class(class) => self.classes_of(row).contains(&class),- DispatchKey::AttributeName(name) => self.attributes_of(row).iter().any(|attribute| {- if attribute.name == name {- return true;- }- let forms = self.attribute_name_forms(attribute.name);- forms.local == name || forms.folded_name == name || forms.folded_local == name- }),- DispatchKey::TagName(tag) => self.tag_of(row) == tag || self.folded_tag_of(row) == tag,- DispatchKey::Directionality(direction) => self.directionality_of(row) == direction,- DispatchKey::Root => is_root,- DispatchKey::State(state) => self.states_of(row).contains(state),- DispatchKey::Heading => self.heading_level_of(row) != 0,- DispatchKey::Universal => true,- _ => unreachable!("non-dispatch feature key"),- }- }-- #[cfg(test)]- pub fn set_attribute_value_text_for_test(&mut self, value: StyleAtomID, text: &[u16]) {- Arc::make_mut(&mut self.attribute_catalogs)- .value_texts- .insert(value.0 as usize, Some(text.into()));- }-- #[must_use]- pub fn text_of(&self, attribute: AttributeFact) -> Option<&[u16]> {- self.attribute_catalogs- .value_texts- .get(attribute.value.0 as usize)- .and_then(Option::as_deref)- }-- #[must_use]- pub fn attribute_name_forms(&self, name: StyleAtomID) -> AttributeNameForms {- let mut forms = self- .attribute_catalogs- .name_forms- .get(name.0 as usize)- .unwrap_or_default();- if forms.folded_name.is_none() {- forms.folded_name = name;- }- if forms.folded_local.is_none() {- forms.folded_local = forms.local;- }- forms- }-- #[cfg(test)]- pub fn note_attribute_name_forms(&mut self, name: StyleAtomID, forms: AttributeNameForms) {- Arc::make_mut(&mut self.attribute_catalogs)- .name_forms- .insert(name.0 as usize, forms);- }-- fn payload_bytes_of_row(&self, row: u32) -> u64 {- (size_of_val(self.custom_states_of(row))- + size_of_val(self.parts_of(row))- + size_of_val(self.classes_of(row))- + size_of_val(self.attributes_of(row))) as u64- }-- /// Repack the payload arrays once more of them is stale than live.- fn compact_primary_payloads_if_mostly_stale(&mut self) {- let payload_bytes = size_of_val(self.custom_states.as_slice())- + size_of_val(self.parts.as_slice())- + size_of_val(self.classes.as_slice())- + size_of_val(self.attributes.as_slice());- if self.stale_payload_bytes * 2 > payload_bytes as u64 {- self.compact_primary_payloads();- }- }-- fn compact_primary_payloads(&mut self) {- assert!(self.primary);- self.stale_payload_bytes = 0;- let mut custom_states = Vec::new();- let mut parts = Vec::new();- let mut classes = Vec::new();- let mut attributes = Vec::new();- for row in 1..self.row_count() {- if !self.resident.contains(row) {- continue;- }- if let Some(mut rare_facts) = self.rare_facts.get(row) {- rare_facts.custom_states =- PayloadHandle::appended_to(&mut custom_states, rare_facts.custom_states.slice(&self.custom_states));- rare_facts.parts = PayloadHandle::appended_to(&mut parts, rare_facts.parts.slice(&self.parts));- self.rare_facts.insert(row, rare_facts);- }- self.class_handles[row] =- PayloadHandle::appended_to(&mut classes, self.class_handles[row].slice(&self.classes));- self.attribute_handles[row] =- PayloadHandle::appended_to(&mut attributes, self.attribute_handles[row].slice(&self.attributes));- }- self.custom_states = custom_states;- self.parts = parts;- self.classes = classes;- self.attributes = attributes;- self.text.clear();- self.text.shrink_to_fit();- }-- pub fn clear(&mut self) {- self.generation = next_batch_generation();- // Sparse batches can name high-index elements, so clearing their individual slots avoids- // writing the holes below them. Once enough of the directory is live, one contiguous fill- // is cheaper than scattered stores.- if self.nodes.len() < self.row_by_element_index.len() / 4 {- for &node in &self.nodes {- let Some(index) = node.element_index() else {- continue;- };- self.row_by_element_index[index as usize] = NO_ROW;- }- } else {- self.row_by_element_index.fill(NO_ROW);- }- self.nodes.clear();- self.stale_rows = 0;- self.live_rows = 0;- self.dispatch_bloom.clear();- self.tag.clear();- self.folded_tag.clear();- self.id.clear();- self.states.clear();- self.directionality.clear();- self.language.clear();- self.has_text_content.clear();- self.language_text.clear();- self.namespace.clear();- self.heading_level.clear();- self.custom_states.clear();- self.parts.clear();- self.part_handles.clear();- self.part_exposure.clear();- self.custom_state_handles.clear();- self.classes.clear();- self.class_handles.clear();- self.attributes.clear();- self.attribute_handles.clear();- self.text.clear();- }-}--/// Members per posting chunk. Insertion and removal shift at most this many identities, so a-/// posting stays cheap to maintain without giving up sorted order.-const MAX_POSTING_CHUNK: usize = 256;--/// One feature's candidate set: chunked and sorted by `StyleNodeID`.-#[derive(Clone, Default)]-pub(super) struct Posting {- chunks: Vec<Vec<StyleNodeID>>,- length: usize,-}--impl Posting {- pub(super) fn candidates(&self) -> impl Iterator<Item = StyleNodeID> + '_ {- self.chunks.iter().flat_map(|chunk| chunk.iter().copied())- }-- pub(super) fn append_candidates_to(&self, candidates: &mut Vec<StyleNodeID>) {- candidates.reserve(self.length);- for chunk in &self.chunks {- candidates.extend_from_slice(chunk);- }- }-- #[must_use]- pub(super) fn len(&self) -> usize {- self.length- }-- fn chunk_for(&self, node: StyleNodeID) -> usize {- match self.chunks.binary_search_by(|chunk| chunk[0].cmp(&node)) {- Ok(index) => index,- Err(0) => 0,- Err(index) => index - 1,- }- }-- fn insert(&mut self, node: StyleNodeID) -> Option<u64> {- if self.chunks.is_empty() {- let chunks_capacity_before = self.chunks.capacity();- let chunk = vec![node];- let chunk_capacity = chunk.capacity();- self.chunks.push(chunk);- self.length = 1;- return Some(- ((self.chunks.capacity() - chunks_capacity_before) * size_of::<Vec<StyleNodeID>>()- + chunk_capacity * size_of::<StyleNodeID>()) as u64,- );- }- if node > *self.chunks.last().unwrap().last().unwrap() {- let last = self.chunks.len() - 1;- let added_bytes = if self.chunks[last].len() < MAX_POSTING_CHUNK {- let capacity_before = self.chunks[last].capacity();- self.chunks[last].push(node);- ((self.chunks[last].capacity() - capacity_before) * size_of::<StyleNodeID>()) as u64- } else {- let chunks_capacity_before = self.chunks.capacity();- let chunk = vec![node];- let chunk_capacity = chunk.capacity();- self.chunks.push(chunk);- ((self.chunks.capacity() - chunks_capacity_before) * size_of::<Vec<StyleNodeID>>()- + chunk_capacity * size_of::<StyleNodeID>()) as u64- };- self.length += 1;- return Some(added_bytes);- }- let index = self.chunk_for(node);- let chunk_capacity_before = self.chunks[index].capacity();- let moved = {- let chunk = &mut self.chunks[index];- let Err(position) = chunk.binary_search(&node) else {- return None;- };- if chunk.len() == MAX_POSTING_CHUNK {- let middle = chunk.len() / 2;- let mut moved = Vec::with_capacity(chunk.len() - middle + 1);- moved.extend_from_slice(&chunk[middle..]);- chunk.truncate(middle);- if position < middle {- chunk.insert(position, node);- } else {- moved.insert(position - middle, node);- }- Some(moved)- } else {- chunk.insert(position, node);- None- }- };- let mut added_bytes =- ((self.chunks[index].capacity() - chunk_capacity_before) * size_of::<StyleNodeID>()) as u64;- self.length += 1;- if let Some(moved) = moved {- let chunks_capacity_before = self.chunks.capacity();- let moved_capacity = moved.capacity();- self.chunks.insert(index + 1, moved);- added_bytes += ((self.chunks.capacity() - chunks_capacity_before) * size_of::<Vec<StyleNodeID>>()- + moved_capacity * size_of::<StyleNodeID>()) as u64;- }- Some(added_bytes)- }-- fn remove(&mut self, node: StyleNodeID) -> Option<u64> {- if self.chunks.is_empty() {- return None;- }- let index = self.chunk_for(node);- let chunk = &mut self.chunks[index];- let Ok(position) = chunk.binary_search(&node) else {- return None;- };- chunk.remove(position);- self.length -= 1;- let released_bytes = if chunk.is_empty() {- let chunk = self.chunks.remove(index);- (chunk.capacity() * size_of::<StyleNodeID>()) as u64- } else {- 0- };- Some(released_bytes)- }-- pub(super) fn contains(&self, node: StyleNodeID) -> bool {- if self.chunks.is_empty() {- return false;- }- self.chunks[self.chunk_for(node)].binary_search(&node).is_ok()- }-}--/// One compact key for selector routing, dispatch, and postings.-///-/// 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,- /// An element whose style resolution called a custom function.- ///- /// Which function it called is not reported by the substitution machinery, so an `@function` rule- /// changing reaches the elements that called one at all - bounded by that, rather than by the- /// document.- AnyCustomFunction,- /// An element whose style resolution consulted custom properties whose names are not all known.- ///- /// The bulk cascade substitutes `var()` inside the Rust value path, which does not report the- /// names it looked up, so an element resolved that way can only be indexed as using something.- /// A registration reaches these as well as the ones indexed by name - far narrower than the- /// document, and sound where naming only what is known would not be.- AnyCustomProperty,- /// One custom property an element declares or references.- ///- /// Registering a property changes how every element that declares or references it computes, and- /// what it inherits. Which elements those are is not something selector matching can say.- CustomPropertySet(u32),- /// One `animation-name` an element's computed style references.- ///- /// Unlike the others this is not a fact a selector matches on: it is how a `@keyframes` rule- /// finds the elements it decides for. A keyframes rule reaches animations referencing its name- /// rather than anything its position in the cascade implies, and without this the elements- /// running an animation whose keyframes changed are unreachable.- AnimationName(StyleAtomID),-}--impl FeatureKey {- #[must_use]- pub fn has_selector_posting(self) -> bool {- match self {- Self::Part(_)- | Self::CustomState(_)- | Self::TagName(_)- | Self::Id(_)- | Self::Class(_)- | Self::AttributeName(_)- | Self::Directionality(_) => true,- Self::State(fact) => fact.has_selector_posting(),- _ => false,- }- }-- 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)- | Self::AnimationName(atom) => Some(atom),- Self::Root- | Self::State(_)- | Self::Heading- | Self::Universal- | Self::Structural- | Self::Language- | Self::AnyCustomFunction- | Self::AnyCustomProperty- | Self::CustomPropertySet(_) => None,- }- }-}--pub type SelectorPostingKey = FeatureKey;-pub type DependencyPostingKey = FeatureKey;-pub type PostingKey = FeatureKey;--/// Candidate sets for observed element features.-///-/// This is acceleration and nothing more. A missing posting never changes which transpose entry-/// points run and never changes an answer: the routed program reads authoritative DOM facts or runs-/// an exact scope batch instead. Fact setters populate postings eagerly, independent of which-/// selector programs are attached, and they remain until their facts disappear. A selector-/// posting that outgrows its cardinality limit is dropped and stays missing for its key. This-/// global arrangement avoids program-lifetime registration and first-use fact scans.-#[derive(Clone)]-pub struct FeaturePostings {- postings: HashMap<PostingKey, Posting>,- cardinality_limited: HashSet<PostingKey>,- grown_selector_postings: HashSet<PostingKey>,- selector_posting_limit: usize,-}--impl Default for FeaturePostings {- fn default() -> Self {- Self {- postings: HashMap::default(),-- cardinality_limited: HashSet::default(),- grown_selector_postings: HashSet::default(),- selector_posting_limit: usize::MAX,- }- }-}--impl FeaturePostings {- #[must_use]- #[cfg(test)]- pub fn new() -> Self {- Self::default()- }-- /// Add `node` to a feature's candidate set. A key whose posting outgrew its limit stays missing.- pub fn insert(&mut self, key: PostingKey, node: StyleNodeID) -> bool {- if self.cardinality_limited.contains(&key) {- return false;- }- let posting = self.postings.entry(key).or_default();- if posting.insert(node).is_none() {- return true;- }- let posting_length = posting.length;- if key.has_selector_posting() && posting_length > 4096 {- self.remember_grown_selector_posting(key);- }- let exceeds_limit = key.has_selector_posting() && posting_length > self.selector_posting_limit;- if exceeds_limit {- self.remove_posting(key);- self.remember_cardinality_limited(key);- return false;- }- true- }-- pub fn remove(&mut self, key: PostingKey, node: StyleNodeID) {- if let Some(posting) = self.postings.get_mut(&key) {- posting.remove(node);- if posting.length == 0 {- self.remove_posting(key);- }- }- }-- /// Look up one feature's complete candidate set.- ///- /// An absent key is known empty unless that exact posting outgrew its limit.- #[must_use]- pub(super) fn lookup(&self, key: PostingKey) -> Lookup<&Posting, PostingKey> {- match self.postings.get(&key) {- Some(posting) => Lookup::Known(posting),- None if self.cardinality_limited.contains(&key) => Lookup::Missing(key),- None => Lookup::KnownAbsent,- }- }-- #[cfg(test)]- pub(crate) fn drop_posting(&mut self, key: PostingKey) {- self.cardinality_limited.insert(key);- self.remove_posting(key);- }-- fn remove_posting(&mut self, key: PostingKey) {- if self.postings.remove(&key).is_none() {- return;- }- if self.postings.is_empty() {- self.postings = HashMap::default();- }- }-- fn remember_cardinality_limited(&mut self, key: PostingKey) {- self.cardinality_limited.insert(key);- }-- fn remember_grown_selector_posting(&mut self, key: PostingKey) {- self.grown_selector_postings.insert(key);- }-- fn set_selector_posting_limit(&mut self, maximum_candidates: usize) {- let first_limit = self.selector_posting_limit == usize::MAX;- self.selector_posting_limit = maximum_candidates;- if !first_limit {- return;- }- let keys: Vec<_> = self- .postings- .iter()- .filter_map(|(&key, posting)| {- (key.has_selector_posting() && posting.length > maximum_candidates).then_some(key)- })- .collect();- for key in keys {- self.remove_posting(key);- self.remember_cardinality_limited(key);- }- }-- fn update_selector_posting_limit(&mut self, live_element_count: usize) {- self.set_selector_posting_limit((live_element_count / 4).max(4096));- let mut grown = std::mem::take(&mut self.grown_selector_postings);- for key in grown.drain() {- if self- .postings- .get(&key)- .is_some_and(|posting| posting.length > self.selector_posting_limit)- {- self.remove_posting(key);- self.remember_cardinality_limited(key);- }- }- self.grown_selector_postings = grown;- }-- #[must_use]- #[cfg(test)]- pub fn feature_count(&self) -> usize {- self.postings.len()- }-- fn forget_atoms(&mut self, atoms: &HashSet<StyleAtomID>) {- self.postings- .retain(|key, _| !key.atom().is_some_and(|atom| atoms.contains(&atom)));- if self.postings.is_empty() {- self.postings = HashMap::default();- }-- self.cardinality_limited- .retain(|key| !key.atom().is_some_and(|atom| atoms.contains(&atom)));- self.grown_selector_postings- .retain(|key| !key.atom().is_some_and(|atom| atoms.contains(&atom)));- }-}--/// 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)-}--/// One attached selector entry, reachable from its dispatch key.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub struct DispatchEntry {- /// Document identity of the compiled selector entry this scope-local rule row joins.- pub identity: EntryID,- pub rule: RuleID,- pub program: SelectorProgramID,- /// Index into the selector program's entry list.- pub entry: u32,- /// This entry's normal-declaration cascade rank within the dispatch. A rule outside `@scope`- /// can copy it into its match, so every element need not reconstruct the same priority.- pub cascade_order: u32,- /// For an entry in an attribute bucket, the value its subject requires by identity, or none.- /// An attribute that is on every element puts its whole bucket in front of every candidate, and- /// comparing two atoms rejects most of them without evaluating a selector.- pub required_attribute_value: StyleAtomID,- /// A required feature of the subject's parent, when a child combinator names one.- pub required_parent: Option<DispatchKey>,- /// A required feature of some ancestor, when a descendant combinator names one.- pub required_ancestor: Option<DispatchKey>,- /// The exact bit assigned to `required_ancestor` in this dispatch.- pub required_ancestor_index: Option<u32>,- /// Bloom summary of independently necessary subject features.- pub required_subject_bloom: u64,- /// Whether the top-down prefix program answers this entry exactly.- pub prefix_matched: bool,- /// Whether this entry is inserted under several keys - one per branch of its subject's- /// disjunction - so a candidate walk carrying more than one of those keys must evaluate it- /// once, not once per key. Copies of one entry share a cascade_order, which is the dedup key.- pub multi_key: bool,-}--/// Selector-derived half of a dispatch row, shared by scopes with the same topology.-#[derive(Clone, Copy)]-struct DispatchEntryMetadata {- identity: EntryID,- program: SelectorProgramID,- entry: u32,- required_attribute_value: StyleAtomID,- required_parent: Option<DispatchKey>,- required_ancestor: Option<DispatchKey>,- required_ancestor_index: Option<u32>,- required_subject_bloom: u64,- prefix_matched: bool,- multi_key: bool,- next_for_identity: Option<NonZeroU32>,-}--#[derive(Clone, Copy, PartialEq, Eq, Hash)]-struct DispatchEntryBinding {- rule: RuleID,- cascade_order_index: u32,-}--#[derive(Default)]-struct RuleDispatchEntries {- rows: Vec<DispatchEntryMetadata>,- entry_heads: Vec<Option<NonZeroU32>>,- // Only construction appends to these chains. Rebuild their tails when extending a template.- entry_tails: Vec<Option<NonZeroU32>>,-}--impl Clone for RuleDispatchEntries {- fn clone(&self) -> Self {- Self {- rows: self.rows.clone(),- entry_heads: self.entry_heads.clone(),- entry_tails: self.entry_tails.clone(),- }- }-}--impl RuleDispatchEntries {- fn prepare_entry_tails(&mut self) {- if !self.entry_tails.is_empty() || self.rows.is_empty() {- return;- }- self.entry_tails.resize(self.entry_heads.len(), None);- for (index, row) in self.rows.iter().enumerate() {- if row.next_for_identity.is_none() {- let index = u32::try_from(index).expect("dispatch row space exhausted");- self.entry_tails[row.identity.0 as usize] =- NonZeroU32::new(index.checked_add(1).expect("dispatch row space exhausted"));- }- }- }-}--define_id! {- /// Physical row in one scope-local selector dispatch.- pub(super) struct DispatchRow();-}--impl DispatchRow {- pub(super) fn from_index(index: usize) -> Self {- Self(u32::try_from(index).expect("dispatch entry space exhausted"))- }-- pub(super) fn index(self) -> usize {- self.0 as usize- }-}--/// Direct cascade projection metadata indexed by an entry's dense cascade order.-#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]-struct CascadeEntryData {- property_start: u32,- property_count: u16,- prunable: bool,- pruning_blocker: bool,-}--/// Transaction-local duplicate suppression for candidate dispatch.-#[derive(Clone, Default)]-pub struct DispatchCandidateWorkspace {- seen_at_epoch: EpochColumn,- candidates: Vec<DispatchRow>,- cascade_sort: Vec<(Reverse<(bool, u32)>, DispatchRow)>,- epoch: u32,-}--#[derive(Clone, Copy, PartialEq, Eq)]-pub enum CandidateEntries {- All,- NonPrefix,-}--impl DispatchCandidateWorkspace {- pub(super) fn with_entry_capacity(entry_count: usize) -> Self {- Self {- seen_at_epoch: {- let mut column = EpochColumn::default();- column.ensure_len(entry_count);- column- },- candidates: Vec::with_capacity(entry_count),- cascade_sort: Vec::with_capacity(entry_count),- epoch: 0,- }- }-- fn begin(&mut self, entry_count: usize) {- self.seen_at_epoch.ensure_len(entry_count);- self.candidates.clear();- self.cascade_sort.clear();- advance_epoch(&mut self.epoch, 1, &mut [&mut self.seen_at_epoch]);- }-- fn admit(&mut self, id: DispatchRow) -> bool {- self.seen_at_epoch.mark(id.index(), self.epoch)- }-}--/// What exact parent facts candidate dispatch can consult.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub enum ParentDispatchFacts {- /// The node has no element parent. A child combinator cannot match it.- NoElementParent,- /// The parent is an element whose complete local facts are in this batch.- Known { row: u32, is_document_root: bool },- /// The parent is an element, but this batch cannot answer what it carries.- Unknown,-}--/// Exact ancestry facts candidate dispatch can consult.-#[derive(Clone, Copy)]-pub struct AncestorDispatchFacts<'a> {- words: &'a [u64],- unbounded: bool,-}--impl<'a> AncestorDispatchFacts<'a> {- #[must_use]- pub fn new(words: &'a [u64], unbounded: bool) -> Self {- Self { words, unbounded }- }-- #[must_use]- fn contains(self, index: u32) -> bool {- if self.unbounded {- return true;- }- let index = index as usize;- self.words[index / u64::BITS as usize] & (1_u64 << (index % u64::BITS as usize)) != 0- }-}--#[derive(Clone, Copy, Default)]-struct DispatchBucketRange {- start: u32,- length: u32,-}--const DISPATCH_ATOM_KIND_COUNT: usize = 7;--#[derive(Clone, Default)]-struct SegmentedDispatchBucketDirectory {- ranges: PagedCopyColumn<DispatchBucketRange>,-}--impl SegmentedDispatchBucketDirectory {- fn get(&self, index: usize) -> DispatchBucketRange {- self.ranges.get(index).unwrap_or_default()- }-- fn insert(&mut self, index: usize, range: DispatchBucketRange) {- self.ranges.insert(index, range);- }-}--#[derive(Clone, Default)]-struct DispatchBucketDirectory {- atoms: [SegmentedDispatchBucketDirectory; DISPATCH_ATOM_KIND_COUNT],- states: Vec<DispatchBucketRange>,- fixed: [DispatchBucketRange; 3],- rows: Vec<DispatchRow>,-}--impl DispatchBucketDirectory {- fn build(buckets: HashMap<DispatchKey, Vec<DispatchRow>>) -> Self {- let mut entries: Vec<_> = buckets.into_iter().collect();- entries.sort_unstable_by_key(|&(key, _)| key);- let row_count = entries.iter().map(|(_, rows)| rows.len()).sum();- let mut directory = Self {- states: vec![DispatchBucketRange::default(); StateFact::ALL.len()],- rows: Vec::with_capacity(row_count),- ..Self::default()- };- for (key, rows) in entries {- let range = DispatchBucketRange {- start: u32::try_from(directory.rows.len()).expect("dispatch bucket space exhausted"),- length: u32::try_from(rows.len()).expect("dispatch bucket space exhausted"),- };- directory.insert_range(key, range);- directory.rows.extend(rows);- }- directory- }-- fn get(&self, key: DispatchKey) -> &[DispatchRow] {- let range = self.range(key);- let start = range.start as usize;- &self.rows[start..start + range.length as usize]- }-- fn range(&self, key: DispatchKey) -> DispatchBucketRange {- if let Some((kind, atom)) = dispatch_atom_bucket(key) {- return self.atoms[kind].get(atom);- }- match key {- DispatchKey::State(state) => self.states.get(state as usize).copied().unwrap_or_default(),- DispatchKey::Root => self.fixed[0],- DispatchKey::Heading => self.fixed[1],- DispatchKey::Universal => self.fixed[2],- _ => unreachable!("non-dispatch feature key"),- }- }-- fn insert_range(&mut self, key: DispatchKey, range: DispatchBucketRange) {- if let Some((kind, atom)) = dispatch_atom_bucket(key) {- self.atoms[kind].insert(atom, range);- return;- }- match key {- DispatchKey::State(state) => self.states[state as usize] = range,- DispatchKey::Root => self.fixed[0] = range,- DispatchKey::Heading => self.fixed[1] = range,- DispatchKey::Universal => self.fixed[2] = range,- _ => unreachable!("non-dispatch feature key"),- }- }-- fn to_buckets(&self) -> HashMap<DispatchKey, Vec<DispatchRow>> {- let mut buckets = HashMap::default();- for (kind, directory) in self.atoms.iter().enumerate() {- for (atom, range) in directory.ranges.indexed_iter() {- if range.length != 0 {- buckets.insert(dispatch_atom_bucket_key(kind, atom), self.slice(range).to_vec());- }- }- }- for (index, &range) in self.states.iter().enumerate() {- if range.length != 0 {- buckets.insert(DispatchKey::State(StateFact::ALL[index]), self.slice(range).to_vec());- }- }- for (key, range) in [- (DispatchKey::Root, self.fixed[0]),- (DispatchKey::Heading, self.fixed[1]),- (DispatchKey::Universal, self.fixed[2]),- ] {- if range.length != 0 {- buckets.insert(key, self.slice(range).to_vec());- }- }- buckets- }-- fn filtered(&self, mut retain: impl FnMut(DispatchRow) -> bool) -> Self {- let mut buckets = self.to_buckets();- buckets.retain(|_, rows| {- rows.retain(|&row| retain(row));- !rows.is_empty()- });- Self::build(buckets)- }-- fn slice(&self, range: DispatchBucketRange) -> &[DispatchRow] {- let start = range.start as usize;- &self.rows[start..start + range.length as usize]- }-}--fn dispatch_atom_bucket(key: DispatchKey) -> Option<(usize, usize)> {- match key {- DispatchKey::Part(atom) => Some((0, atom.0 as usize)),- DispatchKey::CustomState(atom) => Some((1, atom.0 as usize)),- DispatchKey::TagName(atom) => Some((2, atom.0 as usize)),- DispatchKey::Id(atom) => Some((3, atom.0 as usize)),- DispatchKey::Class(atom) => Some((4, atom.0 as usize)),- DispatchKey::AttributeName(atom) => Some((5, atom.0 as usize)),- DispatchKey::Directionality(atom) => Some((6, atom.0 as usize)),- _ => None,- }-}--fn dispatch_atom_bucket_key(kind: usize, atom: usize) -> DispatchKey {- let atom = StyleAtomID(u32::try_from(atom).expect("dispatch atom exceeds u32"));- match kind {- 0 => DispatchKey::Part(atom),- 1 => DispatchKey::CustomState(atom),- 2 => DispatchKey::TagName(atom),- 3 => DispatchKey::Id(atom),- 4 => DispatchKey::Class(atom),- 5 => DispatchKey::AttributeName(atom),- 6 => DispatchKey::Directionality(atom),- _ => unreachable!("dispatch atom kind out of range"),- }-}--/// Buckets attached selector entries by their rightmost distinguishing feature.-///-/// A candidate probes only the buckets its own facts name, plus the universal bucket, so a document-/// full of `.item` elements never considers a rule whose subject compound requires `#header`. This-/// is program-derived dispatch rather than acceleration over elements: it is rebuilt with the-/// program and never dropped independently of it.-#[derive(Default)]-pub(super) struct AncestorDispatchTopology {- key_indices: HashMap<DispatchKey, u32>,-}--impl AncestorDispatchTopology {- pub(super) fn shape(&self) -> AncestorDispatchShape {- let mut keys = vec![DispatchKey::Universal; self.key_indices.len()];- for (&key, &index) in &self.key_indices {- keys[index as usize] = key;- }- AncestorDispatchShape(keys)- }-}--impl Clone for AncestorDispatchTopology {- fn clone(&self) -> Self {- Self {- key_indices: self.key_indices.clone(),- }- }-}--#[derive(Clone)]--struct RuleDispatchTopology {- /// Mutable construction form, consumed when the directory is finalized.- buckets: HashMap<DispatchKey, Vec<DispatchRow>>,- bucket_directory: DispatchBucketDirectory,- non_prefix_bucket_directory: DispatchBucketDirectory,- /// Universal-subject entries that have no exact parent requirement.- universal_without_parent_filter: Vec<DispatchRow>,- /// Universal-subject entries indexed by the one feature their parent must carry.- universal_by_parent: HashMap<DispatchKey, Vec<DispatchRow>>,- universal_parent_directory: DispatchBucketDirectory,- non_prefix_universal_parent_directory: DispatchBucketDirectory,- /// The same parent-filtered entries as a conservative fallback when parent facts are absent.- universal_with_parent_filter: Vec<DispatchRow>,- non_prefix_universal_without_parent_filter: Vec<DispatchRow>,- non_prefix_universal_with_parent_filter: Vec<DispatchRow>,- finalized: bool,- ancestors: Arc<AncestorDispatchTopology>,- prefixes: PrefixAutomaton,-}--impl Default for RuleDispatchTopology {- fn default() -> Self {- Self {- buckets: HashMap::default(),- bucket_directory: DispatchBucketDirectory::default(),- non_prefix_bucket_directory: DispatchBucketDirectory::default(),- universal_without_parent_filter: Vec::new(),- universal_by_parent: HashMap::default(),- universal_parent_directory: DispatchBucketDirectory::default(),- non_prefix_universal_parent_directory: DispatchBucketDirectory::default(),- universal_with_parent_filter: Vec::new(),- non_prefix_universal_without_parent_filter: Vec::new(),- non_prefix_universal_with_parent_filter: Vec::new(),- finalized: false,- ancestors: Arc::new(AncestorDispatchTopology::default()),- prefixes: PrefixAutomaton::default(),- }- }-}--/// The identity of one shared ancestor-dispatch topology: the address of the allocation, held-/// as an integer.-///-/// Nothing follows it — it exists only to say "the same topology as last time" — and an integer-/// says exactly that, while a raw pointer would make every container holding one unshareable.-#[derive(Clone, Copy, PartialEq, Eq)]-pub(super) struct AncestorDispatchTopologyID(usize);--/// The pools for the rule bindings and cascade projections of dispatches.-#[derive(Default)]-pub(super) struct DispatchStoragePools {- cascade_rule_pages: SharedVectorPool<CascadeOrderRule>,- dispatch_bindings: SharedVectorPool<DispatchEntryBinding>,- cascade_orders: SharedVectorPool<u32>,- cascade_properties: SharedVectorPool<u16>,- cascade_entries: SharedVectorPool<CascadeEntryData>,- pub(super) prefixes: super::prefix::PrefixPools,-}--pub struct RuleDispatch {- entries: Arc<RuleDispatchEntries>,- entry_bindings: SharedVector<DispatchEntryBinding>,- /// Direct cascade-order projection for every rule represented in this dispatch. Rule- /// identities are program indices, so retained answers can restore an entry's order without- /// searching the dispatch's much larger candidate table. Sparse pages keep a scope containing- /// one late-created rule from allocating rows for every preceding rule in the document.- cascade_order_rule_pages: Vec<Option<SharedVector<CascadeOrderRule>>>,- cascade_orders_by_rule_entry: SharedVector<u32>,- cascade_properties: SharedVector<u16>,- cascade_entries: SharedVector<CascadeEntryData>,- topology: Arc<RuleDispatchTopology>,-}--/// Weak references to the actual shared storage, independent of a particular scope wrapper.-pub(super) struct WeakRuleDispatch {- entries: std::sync::Weak<RuleDispatchEntries>,- topology: std::sync::Weak<RuleDispatchTopology>,-}--impl WeakRuleDispatch {- pub(super) fn is_alive(&self) -> bool {- self.entries.strong_count() != 0 && self.topology.strong_count() != 0- }-- pub(super) fn upgrade(&self) -> Option<RuleDispatch> {- Some(RuleDispatch {- entries: self.entries.upgrade()?,- topology: self.topology.upgrade()?,- entry_bindings: SharedVector::default(),- cascade_order_rule_pages: Vec::new(),- cascade_orders_by_rule_entry: SharedVector::default(),- cascade_properties: SharedVector::default(),- cascade_entries: SharedVector::default(),- })- }-}--impl Default for RuleDispatch {- fn default() -> Self {- Self {- entries: Arc::new(RuleDispatchEntries::default()),- entry_bindings: SharedVector::default(),- cascade_order_rule_pages: Vec::new(),- cascade_orders_by_rule_entry: SharedVector::default(),- cascade_properties: SharedVector::default(),- cascade_entries: SharedVector::default(),- topology: Arc::new(RuleDispatchTopology::default()),- }- }-}--const CASCADE_ORDER_RULE_PAGE_SIZE: usize = 256;--#[derive(Clone, Copy, PartialEq, Eq, Hash)]-struct CascadeOrderRule {- program: SelectorProgramID,- entry_start: u32,- entry_count: u32,-}--impl Default for CascadeOrderRule {- fn default() -> Self {- Self {- program: SelectorProgramID(u32::MAX),- entry_start: 0,- entry_count: 0,- }- }-}--impl RuleDispatch {- pub(super) fn downgrade(&self) -> WeakRuleDispatch {- WeakRuleDispatch {- entries: Arc::downgrade(&self.entries),- topology: Arc::downgrade(&self.topology),- }- }-- #[must_use]- pub fn new() -> Self {- Self::default()- }-- fn topology_mut(&mut self) -> &mut RuleDispatchTopology {- Arc::make_mut(&mut self.topology)- }-- fn entries_mut(&mut self) -> &mut Vec<DispatchEntryMetadata> {- &mut Arc::make_mut(&mut self.entries).rows- }-- fn entry(&self, row: DispatchRow) -> DispatchEntry {- let metadata = self.entries.rows[row.index()];- let binding = self.entry_bindings[row.index()];- let cascade_order = if binding.cascade_order_index == u32::MAX {- 0- } else {- self.cascade_orders_by_rule_entry[binding.cascade_order_index as usize]- };- DispatchEntry {- identity: metadata.identity,- rule: binding.rule,- program: metadata.program,- entry: metadata.entry,- cascade_order,- required_attribute_value: metadata.required_attribute_value,- required_parent: metadata.required_parent,- required_ancestor: metadata.required_ancestor,- required_ancestor_index: metadata.required_ancestor_index,- required_subject_bloom: metadata.required_subject_bloom,- prefix_matched: metadata.prefix_matched,- multi_key: metadata.multi_key,- }- }-- pub(super) fn rebind_rules(template: &Self, rules: &[RuleID]) -> Self {- assert_eq!(template.entries.rows.len(), rules.len());- Self {- entries: Arc::clone(&template.entries),- entry_bindings: rules- .iter()- .copied()- .map(|rule| DispatchEntryBinding {- rule,- cascade_order_index: u32::MAX,- })- .collect(),- cascade_order_rule_pages: Vec::new(),- cascade_orders_by_rule_entry: SharedVector::default(),- cascade_properties: SharedVector::default(),- cascade_entries: SharedVector::default(),- topology: Arc::clone(&template.topology),- }- }-- pub(super) fn rebind_rules_for_extension(template: &Self, rules: &[RuleID]) -> Self {- let mut dispatch = Self::rebind_rules(template, rules);- let topology = &template.topology;- dispatch.topology = Arc::new(RuleDispatchTopology {- buckets: match topology.finalized {- true => topology.bucket_directory.to_buckets(),- false => topology.buckets.clone(),- },- bucket_directory: DispatchBucketDirectory::default(),- non_prefix_bucket_directory: DispatchBucketDirectory::default(),- universal_without_parent_filter: topology.universal_without_parent_filter.clone(),- universal_by_parent: match topology.finalized {- true => topology.universal_parent_directory.to_buckets(),- false => topology.universal_by_parent.clone(),- },- universal_parent_directory: DispatchBucketDirectory::default(),- non_prefix_universal_parent_directory: DispatchBucketDirectory::default(),- universal_with_parent_filter: topology.universal_with_parent_filter.clone(),- non_prefix_universal_without_parent_filter: Vec::new(),- non_prefix_universal_with_parent_filter: Vec::new(),- finalized: false,- ancestors: Arc::new((*topology.ancestors).clone()),- prefixes: topology.prefixes.clone(),- });- dispatch.topology_mut().prefixes.prepare_to_extend();- dispatch- }-- #[cfg(test)]- pub(super) fn shares_topology_with(&self, other: &Self) -> bool {- Arc::ptr_eq(&self.topology, &other.topology)- }-- #[cfg(test)]- pub(super) fn shares_entries_with(&self, other: &Self) -> bool {- Arc::ptr_eq(&self.entries, &other.entries)- }-- pub(super) fn ancestor_topology_id(&self) -> AncestorDispatchTopologyID {- AncestorDispatchTopologyID(Arc::as_ptr(&self.topology.ancestors).addr())- }-- pub(super) fn ancestor_dispatch_shape(&self) -> AncestorDispatchShape {- self.topology.ancestors.shape()- }-- pub(super) fn ancestor_topology(&self) -> Arc<AncestorDispatchTopology> {- Arc::clone(&self.topology.ancestors)- }-- pub(super) fn share_ancestor_topology_with(&mut self, template: &Arc<AncestorDispatchTopology>) {- if Arc::ptr_eq(&self.topology.ancestors, template) {- return;- }- debug_assert_eq!(self.topology.ancestors.key_indices, template.key_indices);- self.topology_mut().ancestors = Arc::clone(template);- }-- pub(super) fn insert(&mut self, key: DispatchKey, mut entry: DispatchEntry) -> DispatchRow {- debug_assert!(- !self.topology.finalized,- "extend a finalized dispatch through the extension path"- );- entry.required_ancestor_index = entry.required_ancestor.map(|required| {- let topology = self.topology_mut();- let ancestors = Arc::make_mut(&mut topology.ancestors);- let next = u32::try_from(ancestors.key_indices.len()).expect("ancestor requirement space exhausted");- *ancestors.key_indices.entry(required).or_insert(next)- });- let id = DispatchRow::from_index(self.entries.rows.len());- Arc::make_mut(&mut self.entries).prepare_entry_tails();- self.entries_mut().push(DispatchEntryMetadata {- identity: entry.identity,- program: entry.program,- entry: entry.entry,- required_attribute_value: entry.required_attribute_value,- required_parent: entry.required_parent,- required_ancestor: entry.required_ancestor,- required_ancestor_index: entry.required_ancestor_index,- required_subject_bloom: entry.required_subject_bloom,- prefix_matched: entry.prefix_matched,- multi_key: entry.multi_key,- next_for_identity: None,- });- self.entry_bindings.make_mut().push(DispatchEntryBinding {- rule: entry.rule,- cascade_order_index: u32::MAX,- });- let entries = Arc::make_mut(&mut self.entries);- if entries.entry_heads.len() <= entry.identity.0 as usize {- entries.entry_heads.resize(entry.identity.0 as usize + 1, None);- entries.entry_tails.resize(entry.identity.0 as usize + 1, None);- }- let row = NonZeroU32::new(id.0.checked_add(1).expect("dispatch row space exhausted")).unwrap();- if let Some(previous) = entries.entry_tails[entry.identity.0 as usize].replace(row) {- entries.rows[(previous.get() - 1) as usize].next_for_identity = Some(row);- } else {- entries.entry_heads[entry.identity.0 as usize] = Some(row);- }- self.topology_mut().buckets.entry(key).or_default().push(id);- if key == DispatchKey::Universal {- self.index_universal_entry(id);- }- id- }-- pub(super) fn add_prefix_entry(- &mut self,- programs: &super::selector::SelectorPrograms,- program: SelectorProgramID,- chain: &[super::selector::SelectorPrefixStep],- row: DispatchRow,- structural_tests_admissible: bool,- ) {- // Registration can refuse a chain whose structural tests would overflow the automaton's- // truth bit space or whose origin does not admit them; the entry then stays a candidate- // for the exact evaluator.- let entry = self.entries.rows[row.index()].identity;- if self- .topology_mut()- .prefixes- .add_entry(programs, program, chain, entry, structural_tests_admissible)- {- self.entries_mut()[row.index()].prefix_matched = true;- }- }-- pub(super) fn finish_prefixes(&mut self, pools: &mut super::prefix::PrefixPools) {- debug_assert!(!self.topology.finalized, "a dispatch can only be finalized once");- // Finished templates are cloned before extension, so their spare builder capacity- // does not contribute to subsequent edits.- if self.entries.rows.capacity() != self.entries.rows.len()- || self.entries.entry_heads.capacity() != self.entries.entry_heads.len()- || self.entries.entry_tails.capacity() != 0- {- let entries = Arc::make_mut(&mut self.entries);- entries.rows.shrink_to_fit();- entries.entry_heads.shrink_to_fit();- entries.entry_tails = Vec::new();- }- self.entry_bindings.make_mut().shrink_to_fit();- self.topology_mut().prefixes.finish(pools);- self.finalize_bucket_directories();- self.rebuild_universal_with_parent_filter();- self.rebuild_non_prefix_index();- }-- #[must_use]- pub(super) fn prefixes(&self) -> &PrefixAutomaton {- &self.topology.prefixes- }-- pub(super) fn entries_for_identity(&self, entry: EntryID) -> impl Iterator<Item = DispatchEntry> + '_ {- let first = self.entries.entry_heads.get(entry.0 as usize).copied().flatten();- std::iter::successors(first, |row| {- self.entries.rows[(row.get() - 1) as usize].next_for_identity- })- .map(|row| self.entry(DispatchRow(row.get() - 1)))- }-- #[must_use]- #[cfg(test)]- pub(super) fn entry_at(&self, index: usize) -> DispatchEntry {- self.entry(DispatchRow::from_index(index))- }-- fn index_universal_entry(&mut self, id: DispatchRow) {- let entry = self.entry(id);- let topology = self.topology_mut();- match entry.required_parent {- Some(parent) => {- topology.universal_by_parent.entry(parent).or_default().push(id);- }- None => topology.universal_without_parent_filter.push(id),- }- }-- fn rebuild_universal_with_parent_filter(&mut self) {- let entries = self- .bucket_ids(DispatchKey::Universal, CandidateEntries::All)- .iter()- .copied()- .filter(|row| self.entries.rows[row.index()].required_parent.is_some())- .collect();- self.topology_mut().universal_with_parent_filter = entries;- }-- fn finalize_bucket_directories(&mut self) {- let topology = self.topology_mut();- topology.bucket_directory = DispatchBucketDirectory::build(std::mem::take(&mut topology.buckets));- topology.universal_parent_directory =- DispatchBucketDirectory::build(std::mem::take(&mut topology.universal_by_parent));- topology.finalized = true;- }-- fn rebuild_non_prefix_index(&mut self) {- let entries = Arc::clone(&self.entries);- let topology = self.topology_mut();- topology.non_prefix_bucket_directory = topology- .bucket_directory- .filtered(|row| !entries.rows[row.index()].prefix_matched);- topology.non_prefix_universal_parent_directory = topology- .universal_parent_directory- .filtered(|row| !entries.rows[row.index()].prefix_matched);- topology.non_prefix_universal_without_parent_filter = topology- .universal_without_parent_filter- .iter()- .copied()- .filter(|row| !entries.rows[row.index()].prefix_matched)- .collect();- topology.non_prefix_universal_with_parent_filter = topology- .universal_with_parent_filter- .iter()- .copied()- .filter(|row| !entries.rows[row.index()].prefix_matched)- .collect();- }-- /// Assign a dense rank to the static cascade priority of every selector entry.- ///- /// The dispatch is program data, so a rule or ordering change rebuilds these ranks along- /// with the buckets. Dynamic `@scope` proximity is deliberately absent and makes the consumer- /// fall back to constructing the complete priority.- ///- /// A subject whose disjunction has selective branches is inserted once per branch key, and- /// those copies are one selector entry. They therefore share one rank, which is what the- /// candidate walk deduplicates them by.- pub fn assign_cascade_order<K: Ord>(&mut self, mut priority_of: impl FnMut(DispatchEntry) -> K) {- let mut ordered: Vec<(K, RuleID, SelectorProgramID, u32, DispatchRow)> = (0..self.entry_count())- .map(|index| {- let entry = self.entry(DispatchRow::from_index(index));- (- priority_of(entry),- entry.rule,- entry.program,- entry.entry,- DispatchRow::from_index(index),- )- })- .collect();- ordered.sort_unstable();-- let mut cascade_orders_by_row = vec![0; self.entry_count()];- let mut group_end = 0;- for group in ordered- .chunk_by(|left, right| left.0 == right.0 && left.1 == right.1 && left.2 == right.2 && left.3 == right.3)- {- group_end += group.len();- let cascade_order = u32::try_from(group_end - 1).expect("dispatch entry space exhausted");- for ordered_entry in group {- cascade_orders_by_row[ordered_entry.4.index()] = cascade_order;- }- }-- self.rebuild_cascade_order_projection(&cascade_orders_by_row);- }-- pub(super) fn reuse_cascade_order(&mut self, template: &Self) {- assert_eq!(self.entry_count(), template.entry_count());- let mut same_bindings = true;- for index in 0..self.entry_count() {- let entry = self.entries.rows[index];- let template_entry = template.entries.rows[index];- assert_eq!(entry.program, template_entry.program);- assert_eq!(entry.entry, template_entry.entry);- same_bindings &= self.entry_bindings[index].rule == template.entry_bindings[index].rule;- }- if same_bindings {- // The cache already proves the cascade priorities agree. With the same rule- // bindings, its direct lookup tables need no document-local reconstruction.- self.entry_bindings = template.entry_bindings.clone();- self.cascade_order_rule_pages = template.cascade_order_rule_pages.clone();- self.cascade_orders_by_rule_entry = template.cascade_orders_by_rule_entry.clone();- return;- }- let cascade_orders_by_row: Vec<_> = (0..self.entry_count())- .map(|index| template.entry(DispatchRow::from_index(index)).cascade_order)- .collect();- self.rebuild_cascade_order_projection(&cascade_orders_by_row);- }-- fn rebuild_cascade_order_projection(&mut self, cascade_orders_by_row: &[u32]) {- assert_eq!(cascade_orders_by_row.len(), self.entry_count());- let mut entries_by_identity: Vec<_> = (0..self.entry_count()).map(DispatchRow::from_index).collect();- entries_by_identity.sort_unstable_by_key(|&id| {- let metadata = self.entries.rows[id.index()];- (self.entry_bindings[id.index()].rule, metadata.program, metadata.entry)- });- entries_by_identity.dedup_by_key(|id| {- let metadata = self.entries.rows[id.index()];- (self.entry_bindings[id.index()].rule, metadata.program, metadata.entry)- });- self.cascade_order_rule_pages.clear();- self.cascade_orders_by_rule_entry.clear();- self.cascade_orders_by_rule_entry- .make_mut()- .reserve(entries_by_identity.len());- for id in entries_by_identity {- let metadata = self.entries.rows[id.index()];- let binding = self.entry_bindings[id.index()];- let rule_index = binding.rule.0 as usize;- let page_index = rule_index / CASCADE_ORDER_RULE_PAGE_SIZE;- if self.cascade_order_rule_pages.len() <= page_index {- self.cascade_order_rule_pages.resize_with(page_index + 1, || None);- }- let page = self.cascade_order_rule_pages[page_index].get_or_insert_with(|| {- (0..CASCADE_ORDER_RULE_PAGE_SIZE)- .map(|_| CascadeOrderRule::default())- .collect()- });- let rule = &mut page.make_mut()[rule_index % CASCADE_ORDER_RULE_PAGE_SIZE];- if rule.entry_count == 0 {- rule.program = metadata.program;- rule.entry_start =- u32::try_from(self.cascade_orders_by_rule_entry.len()).expect("dispatch entry space exhausted");- }- assert_eq!(- rule.program, metadata.program,- "one rule cannot have multiple selector programs"- );- assert_eq!(- rule.entry_count, metadata.entry,- "a rule's selector entries must form a dense identity space"- );- rule.entry_count = rule.entry_count.checked_add(1).expect("selector entry space exhausted");- self.cascade_orders_by_rule_entry- .make_mut()- .push(cascade_orders_by_row[id.index()]);- }- for (row, binding) in self.entry_bindings.make_mut().iter_mut().enumerate() {- let metadata = self.entries.rows[row];- let rule_index = binding.rule.0 as usize;- let page = self.cascade_order_rule_pages[rule_index / CASCADE_ORDER_RULE_PAGE_SIZE]- .as_deref()- .expect("a dispatch binding must have a cascade-order page");- let rule = &page[rule_index % CASCADE_ORDER_RULE_PAGE_SIZE];- binding.cascade_order_index = rule.entry_start + metadata.entry;- }- }-- #[must_use]- pub(super) fn cascade_order_for_entry(- &self,- rule: RuleID,- program: SelectorProgramID,- selector_entry: u32,- ) -> Option<u32> {- let rule_index = rule.0 as usize;- let page = self- .cascade_order_rule_pages- .get(rule_index / CASCADE_ORDER_RULE_PAGE_SIZE)?- .as_deref()?;- let rule = &page[rule_index % CASCADE_ORDER_RULE_PAGE_SIZE];- if rule.program != program || selector_entry >= rule.entry_count {- return None;- }- self.cascade_orders_by_rule_entry- .get(rule.entry_start as usize + selector_entry as usize)- .copied()- }-- /// Publish each entry's complete normal author declaration inventory beside the dispatch.- ///- /// Cascade matching reads this directly while walking candidates. Keeping it in the immutable- /// dispatch avoids looking the rule up through several program maps for every element.- pub(super) fn assign_cascade_properties<Properties: ExactSizeIterator<Item = u16>>(- &mut self,- pools: &mut DispatchStoragePools,- mut blocks_pruning: impl FnMut(DispatchEntry) -> bool,- mut properties_of: impl FnMut(DispatchEntry) -> Option<Properties>,- ) {- self.cascade_properties.clear();- self.cascade_entries.clear();- let entry_count = self.entry_count();- self.cascade_entries- .make_mut()- .resize(entry_count, CascadeEntryData::default());- let mut configured = vec![false; self.entry_count()];- for index in 0..self.entry_count() {- let entry = self.entry(DispatchRow::from_index(index));- let order = entry.cascade_order as usize;- if configured[order] {- continue;- }- configured[order] = true;- let data = &mut self.cascade_entries.make_mut()[order];- data.pruning_blocker = blocks_pruning(entry);- data.property_start =- u32::try_from(self.cascade_properties.len()).expect("cascade property space exhausted");- let Some(properties) = properties_of(entry) else {- continue;- };- data.property_count =- u16::try_from(properties.len()).expect("a rule cannot declare more than u16::MAX longhands");- self.cascade_properties.make_mut().extend(properties);- data.prunable = true;- }- // These complete projections retain only numeric identities and declaration inventories.- // Equal bindings can share across scopes while their mutable match results stay separate.- for page in self.cascade_order_rule_pages.iter_mut().flatten() {- page.share(&mut pools.cascade_rule_pages);- }- self.entry_bindings.share(&mut pools.dispatch_bindings);- self.cascade_orders_by_rule_entry.share(&mut pools.cascade_orders);- self.cascade_properties.share(&mut pools.cascade_properties);- self.cascade_entries.share(&mut pools.cascade_entries);- }-- #[must_use]- pub fn cascade_properties(&self, entry: DispatchEntry) -> Option<&[u16]> {- let data = self.cascade_entries.get(entry.cascade_order as usize)?;- if !data.prunable {- return None;- }- let start = data.property_start as usize;- Some(&self.cascade_properties[start..start + data.property_count as usize])- }-- #[must_use]- pub fn cascade_properties_for_order(&self, order: u32) -> Option<&[u16]> {- let data = self.cascade_entries.get(order as usize)?;- if !data.prunable {- return None;- }- let start = data.property_start as usize;- Some(&self.cascade_properties[start..start + data.property_count as usize])- }-- #[must_use]- pub fn cascade_pruning_blocker_for_order(&self, order: u32) -> bool {- self.cascade_entries- .get(order as usize)- .is_some_and(|entry| entry.pruning_blocker)- }-- #[must_use]- pub fn cascade_pruning_blocker(&self, entry: DispatchEntry) -> bool {- self.cascade_pruning_blocker_for_order(entry.cascade_order)- }-- fn bucket_ids(&self, key: DispatchKey, entries: CandidateEntries) -> &[DispatchRow] {- if self.topology.finalized {- return match entries {- CandidateEntries::All => self.topology.bucket_directory.get(key),- CandidateEntries::NonPrefix => self.topology.non_prefix_bucket_directory.get(key),- };- }- debug_assert!(entries == CandidateEntries::All);- self.topology.buckets.get(&key).map_or(&[], Vec::as_slice)- }-- fn universal_parent_bucket_ids(&self, key: DispatchKey, entries: CandidateEntries) -> &[DispatchRow] {- if self.topology.finalized {- return match entries {- CandidateEntries::All => self.topology.universal_parent_directory.get(key),- CandidateEntries::NonPrefix => self.topology.non_prefix_universal_parent_directory.get(key),- };- }- debug_assert!(entries == CandidateEntries::All);- self.topology.universal_by_parent.get(&key).map_or(&[], Vec::as_slice)- }-- #[cfg(test)]- pub fn bucket(&self, key: DispatchKey) -> impl ExactSizeIterator<Item = DispatchEntry> + '_ {- self.bucket_ids(key, CandidateEntries::All)- .iter()- .map(|&id| self.entry(id))- }-- #[must_use]- pub fn entry_count(&self) -> usize {- self.entries.rows.len()- }-- #[must_use]- pub fn ancestor_key_count(&self) -> usize {- self.topology.ancestors.key_indices.len()- }-- #[must_use]- pub fn ancestor_key_index(&self, key: DispatchKey) -> Option<u32> {- self.topology.ancestors.key_indices.get(&key).copied()- }-- /// Entries a candidate has to consider, given its local facts.- ///- /// Facts stream their keys directly into the dispatch. `workspace` gives every entry one dense- /// epoch stamp, so aliases and multiple matching attributes cannot emit it twice.- #[allow(clippy::too_many_arguments)]- pub fn candidates_for<'a>(- &'a self,- facts: &'a StyleNodeFacts,- row: u32,- is_document_root: bool,- parent: ParentDispatchFacts,- ancestors: Option<AncestorDispatchFacts<'a>>,- entries: CandidateEntries,- descending_cascade_order: bool,- workspace: &'a mut DispatchCandidateWorkspace,- ) -> impl Iterator<Item = DispatchEntry> + 'a {- workspace.begin(self.entry_count());- debug_assert!(self.topology.finalized || entries == CandidateEntries::All);- let universal_without_parent_filter = match entries {- CandidateEntries::All => &self.topology.universal_without_parent_filter,- CandidateEntries::NonPrefix => &self.topology.non_prefix_universal_without_parent_filter,- };- let universal_with_parent_filter = match entries {- CandidateEntries::All => &self.topology.universal_with_parent_filter,- CandidateEntries::NonPrefix => &self.topology.non_prefix_universal_with_parent_filter,- };- let subject_bloom = facts.dispatch_bloom_of(row, is_document_root);- {- let mut offer = |id: DispatchRow, attribute_value: Option<StyleAtomID>| {- let metadata = self.entries.rows[id.index()];- if !metadata.required_attribute_value.is_none()- && attribute_value != Some(metadata.required_attribute_value)- {- return;- }- if metadata.required_subject_bloom & subject_bloom != metadata.required_subject_bloom {- return;- }- if !workspace.admit(id) {- return;- }- if !match (metadata.required_parent, parent) {- (None, _) => true,- (Some(_), ParentDispatchFacts::NoElementParent) => false,- (Some(required), ParentDispatchFacts::Known { row, is_document_root }) => {- facts.carries_dispatch_key(row, required, is_document_root)- }- (Some(_), ParentDispatchFacts::Unknown) => true,- } {- return;- }- if !match (metadata.required_ancestor_index, ancestors) {- (Some(index), Some(ancestors)) => ancestors.contains(index),- _ => true,- } {- return;- }- workspace.candidates.push(id);- };-- for &id in universal_without_parent_filter {- offer(id, None);- }- match parent {- ParentDispatchFacts::Known { row, is_document_root } => {- facts.for_each_dispatch_probe(row, is_document_root, |key, _| {- for &id in self.universal_parent_bucket_ids(key, entries) {- offer(id, None);- }- });- }- ParentDispatchFacts::Unknown => {- for &id in universal_with_parent_filter {- offer(id, None);- }- }- ParentDispatchFacts::NoElementParent => {}- }- facts.for_each_dispatch_probe(row, is_document_root, |key, attribute_value| {- if key == DispatchKey::Universal {- return;- }- for &id in self.bucket_ids(key, entries) {- offer(id, attribute_value);- }- });- }- if descending_cascade_order && workspace.candidates.len() > 1 {- workspace.cascade_sort.extend(workspace.candidates.iter().map(|&id| {- let binding = self.entry_bindings[id.index()];- let cascade_order = if binding.cascade_order_index == u32::MAX {- 0- } else {- self.cascade_orders_by_rule_entry[binding.cascade_order_index as usize]- };- (- Reverse((self.cascade_pruning_blocker_for_order(cascade_order), cascade_order)),- id,- )- }));- // Rows with the same rank are copies of one selector entry and are deduplicated by- // cascade order at consumption, so their relative order is unobservable.- workspace.cascade_sort.sort_unstable_by_key(|&(key, _)| key);- for (candidate, &(_, sorted)) in workspace.candidates.iter_mut().zip(&workspace.cascade_sort) {- *candidate = sorted;- }- }- workspace.candidates.iter().map(|&id| self.entry(id))- }-}--/// 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. They are built from one list of pairs, so every-/// declaration has its written value.-#[derive(Clone, Default)]-pub struct ElementDeclarations {- declared: Box<[DeclaredProperty]>,- written: Box<[RetainedStyleValueData]>,- checks: Box<[super::publication::WrittenValueChecks]>,- /// Whether no declaration reads anything beyond the cascade (see `written_value_reads`), decided the first time- /// it is asked.- read_nothing: std::sync::OnceLock<bool>,-}--impl ElementDeclarations {- fn new(declarations: Vec<(DeclaredProperty, RetainedStyleValueData)>) -> Self {- let checks = declarations- .iter()- .map(|(declared, written)| super::publication::WrittenValueChecks::prepare(declared.property, written))- .collect();- let (declared, written): (Vec<_>, Vec<_>) = declarations.into_iter().unzip();- Self {- declared: declared.into_boxed_slice(),- written: written.into_boxed_slice(),- checks,- read_nothing: std::sync::OnceLock::new(),- }- }-- /// Whether no declaration reads anything beyond the cascade: what a winner state reads of one of them is nothing.- pub(super) fn read_nothing(&self) -> bool {- *self.read_nothing.get_or_init(|| {- self.iter()- .all(|(declared, written)| super::publication::written_value_reads(declared.property, written) == 0)- })- }-- /// The value the declaration at `index` of `declared` was written with.- #[must_use]- pub fn written(&self, index: usize) -> &RetainedStyleValueData {- &self.written[index]- }-- pub(super) fn checks(&self, index: usize) -> super::publication::WrittenValueChecks {- self.checks[index]- }-- pub fn iter(- &self,- ) -> std::iter::Zip<std::slice::Iter<'_, DeclaredProperty>, std::slice::Iter<'_, RetainedStyleValueData>> {- self.declared.iter().zip(self.written.iter())- }-- /// The index of the declaration a winner names: the last one of its property, importance and- /// declared value.- #[must_use]- pub fn winner_index(- &self,- property: u16,- important: bool,- value: super::cascade::SpecifiedValueID,- ) -> Option<usize> {- self.declared.iter().rposition(|declared| {- declared.property == property && declared.important == important && declared.value == value- })- }-- /// The value the declaration a winner names was written with.- #[must_use]- pub fn winner_value(- &self,- property: u16,- important: bool,- value: super::cascade::SpecifiedValueID,- ) -> Option<&RetainedStyleValueData> {- self.winner_index(property, important, value)- .map(|index| &self.written[index])- }-- fn storage_bytes(&self) -> usize {- size_of_val(self.declared.as_ref()) + size_of_val(self.written.as_ref()) + size_of_val(self.checks.as_ref())- }-}--/// Declarations standing for their written values with the guaranteed-invalid one, for a test-/// that reads no value.-#[cfg(test)]-pub(super) fn unwritten_declarations(declared: &[DeclaredProperty]) -> Vec<(DeclaredProperty, 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.-#[derive(Clone)]-pub struct ElementCustomDeclarations {- declared: Box<[CustomDeclaration]>,- written: Box<[RetainedStyleValueData]>,-}--impl ElementCustomDeclarations {- #[must_use]- pub fn declared(&self) -> &[CustomDeclaration] {- &self.declared- }-- pub fn iter(&self) -> impl Iterator<Item = (&CustomDeclaration, &RetainedStyleValueData)> {- self.declared.iter().zip(&self.written)- }-- fn storage_bytes(&self) -> usize {- size_of_val(self.declared.as_ref()) + size_of_val(self.written.as_ref())- }-}--#[derive(Clone, Default)]-struct ElementDeclarationRow {- by_kind: [ElementDeclarations; ElementDeclarationKind::COUNT],- /// Only the `style` attribute declares custom properties.- custom: Option<ElementCustomDeclarations>,-}--/// 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: ElementDeclarations,- custom: Option<ElementCustomDeclarations>,-}--impl ElementDeclarationRow {- fn storage_bytes(&self) -> u64 {- (size_of::<Self>()- + self- .by_kind- .iter()- .map(ElementDeclarations::storage_bytes)- .sum::<usize>()- + self.custom.as_ref().map_or(0, ElementCustomDeclarations::storage_bytes)) as u64- }-- fn is_empty(&self) -> bool {- self.by_kind.iter().all(|declarations| declarations.declared.is_empty()) && self.custom.is_none()- }-}--/// Element-declaration rows addressed directly by dense element identity.-///-/// Each directory slot costs one pointer. A populated slot contains the fixed declaration-kind-/// columns, and each property list owns one exact-sized allocation.-#[derive(Clone, Default)]-struct ElementDeclarationRows {- rows: Column<Option<Box<ElementDeclarationRow>>>,- payload_bytes: u64,- /// How many rows hold custom declarations: none means no inline style declares one.- rows_with_custom_declarations: usize,-}--impl ElementDeclarationRows {- fn row(&self, node: StyleNodeID) -> Option<&ElementDeclarationRow> {- let index = node.element_index()? as usize;- self.rows.get(index)?.as_deref()- }-- fn get(&self, node: StyleNodeID, kind: ElementDeclarationKind) -> &[DeclaredProperty] {- self.row(node).map_or(&[], |row| &row.by_kind[kind.index()].declared)- }-- fn declarations(&self, node: StyleNodeID, kind: ElementDeclarationKind) -> Option<&ElementDeclarations> {- self.row(node).map(|row| &row.by_kind[kind.index()])- }-- fn set(- &mut self,- node: StyleNodeID,- kind: ElementDeclarationKind,- declarations: Vec<(DeclaredProperty, RetainedStyleValueData)>,- ) {- let index = node.element_index().expect("only elements carry element declarations") as usize;- if declarations.is_empty() {- self.remove_kind(node, kind);- return;- }- let row = self.rows.entry(index);- let before = row.as_ref().map_or(0, |row| row.storage_bytes());- let row = row.get_or_insert_with(Box::default);- row.by_kind[kind.index()] = ElementDeclarations::new(declarations);- let after = row.storage_bytes();- self.payload_bytes = self.payload_bytes - before + after;- }-- /// The custom properties the node's inline style declares.- fn get_custom(&self, node: StyleNodeID) -> Option<&ElementCustomDeclarations> {- self.row(node)?.custom.as_ref()- }-- fn set_custom(&mut self, node: StyleNodeID, custom_declarations: Vec<(CustomDeclaration, RetainedStyleValueData)>) {- let index = node.element_index().expect("only elements carry element declarations") as usize;- if custom_declarations.is_empty() {- let Some(row) = self.rows.get_mut(index).and_then(Option::as_mut) else {- return;- };- let before = row.storage_bytes();- if row.custom.take().is_some() {- self.rows_with_custom_declarations -= 1;- }- let after = match row.is_empty() {- true => 0,- false => row.storage_bytes(),- };- if after == 0 {- self.rows[index] = None;- }- self.payload_bytes = self.payload_bytes - before + after;- return;- }- let row = self.rows.entry(index);- let before = row.as_ref().map_or(0, |row| row.storage_bytes());- let row = row.get_or_insert_with(Box::default);- let (declared, written): (Vec<_>, Vec<_>) = custom_declarations.into_iter().unzip();- let custom = ElementCustomDeclarations {- declared: declared.into_boxed_slice(),- written: written.into_boxed_slice(),- };- if row.custom.replace(custom).is_none() {- self.rows_with_custom_declarations += 1;- }- let after = row.storage_bytes();- self.payload_bytes = self.payload_bytes - before + after;- }-- fn remove_kind(&mut self, node: StyleNodeID, kind: ElementDeclarationKind) {- let Some(index) = node.element_index().map(|index| index as usize) else {- return;- };- let Some(row) = self.rows.get_mut(index).and_then(Option::as_mut) else {- return;- };- let before = row.storage_bytes();- row.by_kind[kind.index()] = ElementDeclarations::default();- if kind == ElementDeclarationKind::InlineStyle && row.custom.take().is_some() {- self.rows_with_custom_declarations -= 1;- }- let after = match row.is_empty() {- true => 0,- false => row.storage_bytes(),- };- if after == 0 {- self.rows[index] = None;- }- self.payload_bytes = self.payload_bytes - before + after;- }-- fn remove(&mut self, node: StyleNodeID) {- let Some(index) = node.element_index().map(|index| index as usize) else {- return;- };- let Some(row) = self.rows.get_mut(index).and_then(Option::take) else {- return;- };- if row.custom.is_some() {- self.rows_with_custom_declarations -= 1;- }- self.payload_bytes -= row.storage_bytes();- }-}--define_id! { struct CustomPropertyNameSetID(); }--impl super::intern_table::InternIdentity for CustomPropertyNameSetID {- fn index(self) -> usize {- self.0 as usize - 1- }-}--/// The accumulated local facts of the document's style nodes.-///-/// It is built from the same feature and state deltas the journal normalizes, so a fact exists here-/// exactly because a mutation published it. The store's [`StyleNodeFacts`] is both the input-side-/// projection and the current-side evaluation arrangement; bounded batches are temporary views of-/// selected rows.-#[derive(Clone)]-pub struct ElementFactStore {- /// Required primary arrangement. Element identity selects its fixed column slots directly;- /// variable facts are append-only payloads reached through the slots' handles.- rows: Arc<StyleNodeFacts>,- /// Shared dictionaries used by primary rows and materialized batches. Keep this handle outside- /// `rows` so publishing a catalog entry never copies every primary fact column.- attribute_catalogs: Arc<AttributeCatalogs>,- #[cfg(test)]- attribute_catalog_copies: u64,- staging: FactStaging,- metadata: Column<Option<ElementFactMetadata>>,- /// Logical bytes reachable through live primary handles.- /// Candidate sets over the same facts. A rule arriving needs to find the elements it could- /// match without walking the document, and this is what answers that.- postings: crate::fork::ForkShared<FeaturePostings>,- /// Whether fact staging holds edits `apply_staged` has not committed yet.- staging_dirty: bool,- /// One entry per distinct set of declared custom property names, and the sets each name is in.- /// A theme is one set however many elements it decides for, which is what keeps the index- /// proportional to the stylesheet rather than to the document times the stylesheet.- custom_property_name_sets: super::intern_table::InternTable<CustomPropertyNameSetID, Box<[StyleAtomID]>>,- custom_property_name_set_vacancies: Vec<u32>,- custom_property_set_ids_by_name: PagedOwnedColumn<Vec<u32>>,- /// Authoritative semantic references from committed fact rows and per-element metadata. This- /// is indexed by atom so a lifetime sweep visits distinct identities rather than every live- /// element row.- atom_live_counts: PagedCopyColumn<u32>,- language_live_counts: PagedCopyColumn<u32>,- attribute_name_live_counts: PagedCopyColumn<u32>,- attribute_value_live_counts: PagedCopyColumn<u32>,- custom_property_set_live_counts: Vec<u64>,- /// Attribute-name forms and value text shared by the primary and each bounded fact batch.- ///- /// An attribute is keyed by the name that is unique to it - its qualified atom, or its bare local- /// name where it is in no namespace - because an element can carry the same local name in several- /// namespaces at once and each of those is a fact of its own. `[*|x]` asks about all of them- /// together, and the any-namespace atom is the identity they share, so it is held per name rather- /// than per element: one name has one local form however many elements carry it.- /// The longhand properties each element declares itself, by the kind of declaration they came- /// from. An element-attached declaration beats every rule in its context, so the cascade needs- /// to know which properties one covers just as it does for a rule.- element_declared_properties: crate::fork::ForkShared<ElementDeclarationRows>,-}--#[derive(Clone, Debug, Default, PartialEq, Eq)]-struct StagedFactRow {- tag: StyleAtomID,- /// The ASCII-lowercase folding of `tag`, held only when it differs from it. Type selectors- /// dispatch on their folded form, so an element whose local name is not already lowercase is- /// posted under both names and reachable either way.- folded_tag: StyleAtomID,- id: StyleAtomID,- /// The element's resolved language tag.- language: StyleAtomID,- /// The element's namespace URI, keyed by its text.- namespace: StyleAtomID,- /// The outermost host a `::part()` rule can address this element from.- part_exposure: StyleAtomID,- /// The element's resolved directionality.- directionality: StyleAtomID,- /// The element's heading level where it has one, 1 to 6, and zero where it does not.- heading_level: u8,- /// Whether the element holds a text or comment child that keeps it from being `:empty`. Element- /// children are style nodes and answer for themselves; a text node is not, so this is the only- /// thing that can say it is there.- has_text_content: bool,- states: StateSet,- custom_states: Vec<StyleAtomID>,- parts: Vec<StyleAtomID>,- classes: Vec<StyleAtomID>,- /// The attributes the element carries, sorted by name, each with the atom of its value.- attributes: Vec<(StyleAtomID, StyleAtomID)>,-}--impl StagedFactRow {}--#[derive(Clone, Default)]-struct FactStaging {- rows: PagedColumn<FactStagingPage>,- entries: Vec<Option<StagedFactRowPair>>,- touched: Vec<(StyleNodeID, u32)>,- dirty: Vec<(StyleNodeID, u32)>,- live_count: usize,- dirty_count: usize,-}--const FACT_STAGING_PAGE_SHIFT: usize = 6;-const FACT_STAGING_PAGE_SIZE: usize = 1 << FACT_STAGING_PAGE_SHIFT;--#[derive(Clone)]--struct FactStagingPage {- entries: [u32; FACT_STAGING_PAGE_SIZE],-}--impl Default for FactStagingPage {- fn default() -> Self {- Self {- entries: [NO_ROW; FACT_STAGING_PAGE_SIZE],- }- }-}--impl PagedColumnPage for FactStagingPage {- type Value = u32;-- const SHIFT: usize = FACT_STAGING_PAGE_SHIFT;-- fn get(&self, index: usize) -> Option<Self::Value> {- (self.entries[index] != NO_ROW).then_some(self.entries[index])- }-- fn insert(&mut self, index: usize, value: Self::Value) {- self.entries[index] = value;- }-}--impl RemovablePagedColumnPage for FactStagingPage {- fn remove(&mut self, index: usize) -> Option<Self::Value> {- let previous = std::mem::replace(&mut self.entries[index], NO_ROW);- (previous != NO_ROW).then_some(previous)- }-}--#[derive(Clone)]--struct StagedFactRowPair {- before: Option<PrimaryFactSnapshot>,- after: StagedFactRow,- dirty: bool,-}--impl FactStaging {- fn index(node: StyleNodeID) -> usize {- node.element_index().expect("only elements carry fact staging") as usize- }-- fn is_empty(&self) -> bool {- self.live_count == 0- }-- fn has_dirty(&self) -> bool {- self.dirty_count != 0- }-- fn len(&self) -> usize {- self.live_count- }-- fn contains(&self, node: StyleNodeID) -> bool {- self.get(node).is_some()- }-- fn get(&self, node: StyleNodeID) -> Option<&StagedFactRow> {- let entry = self.rows.get(Self::index(node))? as usize;- Some(&self.entries.get(entry)?.as_ref()?.after)- }-- fn edit<R>(&mut self, node: StyleNodeID, edit: impl FnOnce(&mut StagedFactRow) -> R) -> Option<R> {- let entry = self.rows.get(Self::index(node))? as usize;- let pair = self.entries.get_mut(entry)?.as_mut()?;- if !pair.dirty {- pair.dirty = true;- self.dirty_count += 1;- self.dirty.push((node, entry as u32));- }-- let result = edit(&mut pair.after);- Some(result)- }-- fn insert_pair(&mut self, node: StyleNodeID, after: StagedFactRow, before: Option<PrimaryFactSnapshot>) {- let index = Self::index(node);- assert!(self.rows.get(index).is_none());-- let entry = u32::try_from(self.entries.len()).expect("fact staging entry overflow");- self.entries.push(Some(StagedFactRowPair {- before,- after,- dirty: true,- }));- self.rows.insert(index, entry);- self.touched.push((node, entry));- self.dirty.push((node, entry));- self.live_count += 1;- self.dirty_count += 1;- }-- fn insert(&mut self, node: StyleNodeID, row: StagedFactRow, before: Option<PrimaryFactSnapshot>) {- let index = Self::index(node);- if let Some(entry) = self.rows.get(index) {- let pair = self.entries[entry as usize]- .as_mut()- .expect("mapped fact staging entry must be live");-- pair.after = row;- if !pair.dirty {- pair.dirty = true;- self.dirty_count += 1;- self.dirty.push((node, entry));- }- return;- }- self.insert_pair(node, row, before);- }-- fn remove(&mut self, node: StyleNodeID) -> Option<StagedFactRow> {- let entry = self.rows.remove(Self::index(node))? as usize;- let pair = self.entries.get_mut(entry)?.take()?;- self.live_count -= 1;- self.dirty_count -= usize::from(pair.dirty);- Some(pair.after)- }-- fn keys(&self) -> impl Iterator<Item = StyleNodeID> + '_ {- self.touched- .iter()- .filter_map(|&(node, entry)| (self.rows.get(Self::index(node)) == Some(entry)).then_some(node))- }-- fn dirty_rows(&self) -> impl Iterator<Item = (StyleNodeID, &StagedFactRow)> {- self.dirty.iter().filter_map(|&(node, entry)| {- if self.rows.get(Self::index(node)) != Some(entry) {- return None;- }- let pair = self.entries.get(entry as usize)?.as_ref()?;- pair.dirty.then_some((node, &pair.after))- })- }-- fn mark_applied(&mut self) {- for &(node, entry) in &self.dirty {- if self.rows.get(Self::index(node)) == Some(entry)- && let Some(pair) = self.entries[entry as usize].as_mut()- {- pair.dirty = false;- }- }- self.dirty.clear();- self.dirty_count = 0;- }-- fn clear(&mut self) {- for &(node, _) in &self.touched {- self.rows.remove(Self::index(node));- }- const RETAINED_ENTRY_CAPACITY_RATIO: usize = 4;- const MIN_RETAINED_ENTRY_CAPACITY: usize = 64;- let transaction_high_water = self.entries.len();- if self.entries.capacity()- > transaction_high_water- .saturating_mul(RETAINED_ENTRY_CAPACITY_RATIO)- .max(MIN_RETAINED_ENTRY_CAPACITY)- {- self.entries.shrink_to(transaction_high_water);- }- self.entries.clear();- self.touched.clear();- self.dirty.clear();- self.live_count = 0;- self.dirty_count = 0;- }-}--#[derive(Clone, Default)]-struct ElementFactMetadata {- /// The animation names this element's computed style references, sorted.- animation_names: Vec<StyleAtomID>,- /// The custom properties this element declares or references, sorted.- custom_property_set: u32,- uses_unnamed_custom_properties: bool,- uses_custom_functions: bool,- /// 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.- is_slot: bool,-}--impl ElementFactMetadata {}--impl Default for ElementFactStore {- fn default() -> Self {- let attribute_catalogs = Arc::new(AttributeCatalogs::default());- let mut rows = StyleNodeFacts::new_primary();- rows.attribute_catalogs = Arc::clone(&attribute_catalogs);-- Self {- rows: Arc::new(rows),- attribute_catalogs,- #[cfg(test)]- attribute_catalog_copies: 0,- staging: FactStaging::default(),- metadata: Column::default(),- postings: Default::default(),-- staging_dirty: false,- custom_property_name_sets: super::intern_table::InternTable::default(),- custom_property_name_set_vacancies: Vec::new(),- custom_property_set_ids_by_name: PagedOwnedColumn::default(),- atom_live_counts: PagedCopyColumn::default(),- language_live_counts: PagedCopyColumn::default(),- attribute_name_live_counts: PagedCopyColumn::default(),- attribute_value_live_counts: PagedCopyColumn::default(),- custom_property_set_live_counts: vec![0],- element_declared_properties: Default::default(),- }- }-}--impl ElementFactStore {- #[must_use]- pub fn new() -> Self {- Self::default()- }-- fn attribute_catalogs_mut(&mut self) -> &mut AttributeCatalogs {- #[cfg(test)]- if Arc::strong_count(&self.attribute_catalogs) != 1 {- self.attribute_catalog_copies += 1;- }- Arc::make_mut(&mut self.attribute_catalogs)- }-- #[cfg(test)]- fn attribute_catalog_copies(&self) -> u64 {- self.attribute_catalog_copies- }-- pub(super) fn staging_is_empty(&self) -> bool {- self.staging.is_empty()- }-- fn prepare_attribute_catalogs(&mut self) {- if Arc::ptr_eq(&self.rows.attribute_catalogs, &self.attribute_catalogs) {- return;- }- // A retained traversal may still share the old rows and their catalog snapshot.- let rows = Arc::make_mut(&mut self.rows);- rows.attribute_catalogs = Arc::clone(&self.attribute_catalogs);- }-- fn increment_atom_count(counts: &mut PagedCopyColumn<u32>, atom: StyleAtomID) {- if atom.is_none() {- return;- }- let index = atom.0 as usize;- let count = counts.get(index).unwrap_or(0);- counts.insert(index, count.checked_add(1).expect("live fact atom count overflow"));- }-- fn decrement_atom_count(counts: &mut PagedCopyColumn<u32>, atom: StyleAtomID) {- if atom.is_none() {- return;- }- let index = atom.0 as usize;- let count = counts.get(index).expect("a live fact atom must have a count");- counts.insert(index, count.checked_sub(1).expect("live fact atom count underflow"));- }-- fn add_row_catalog_references(&mut self, facts: &StagedFactRow) {- Self::for_each_row_atom(facts, |atom| {- Self::increment_atom_count(&mut self.atom_live_counts, atom);- });- Self::increment_atom_count(&mut self.language_live_counts, facts.language);- for &(name, value) in &facts.attributes {- Self::increment_atom_count(&mut self.attribute_name_live_counts, name);- Self::increment_atom_count(&mut self.attribute_value_live_counts, value);- }- }-- fn remove_row_catalog_references(&mut self, row: u32) {- for atom in [- self.rows.tag_of(row),- self.rows.folded_tag_of(row),- self.rows.id_of(row),- self.rows.language_of(row),- self.rows.namespace_of(row),- self.rows.part_exposure_of(row),- self.rows.directionality_of(row),- ] {- Self::decrement_atom_count(&mut self.atom_live_counts, atom);- }- for atoms in [- self.rows.custom_states_of(row),- self.rows.parts_of(row),- self.rows.classes_of(row),- ] {- for &atom in atoms {- Self::decrement_atom_count(&mut self.atom_live_counts, atom);- }- }- Self::decrement_atom_count(&mut self.language_live_counts, self.rows.language_of(row));- for attribute in self.rows.attributes_of(row) {- Self::decrement_atom_count(&mut self.atom_live_counts, attribute.name);- Self::decrement_atom_count(&mut self.atom_live_counts, attribute.value);- Self::decrement_atom_count(&mut self.attribute_name_live_counts, attribute.name);- Self::decrement_atom_count(&mut self.attribute_value_live_counts, attribute.value);- }- }-- fn for_each_row_atom(facts: &StagedFactRow, mut visit: impl FnMut(StyleAtomID)) {- for atom in [- facts.tag,- facts.folded_tag,- facts.id,- facts.language,- facts.namespace,- facts.part_exposure,- facts.directionality,- ] {- visit(atom);- }- for &atom in &facts.custom_states {- visit(atom);- }- for &atom in &facts.parts {- visit(atom);- }- for &atom in &facts.classes {- visit(atom);- }- for &(name, value) in &facts.attributes {- visit(name);- visit(value);- }- }-- pub(super) fn collect_atoms(&self, atoms: &mut HashSet<StyleAtomID>) -> u64 {- let mut visited = 0_u64;- for row in self.element_declared_properties.rows.iter().flatten() {- visited += 1;- for declaration in row.custom.iter().flat_map(ElementCustomDeclarations::declared) {- visited += 1;- atoms.insert(declaration.name);- }- }- for (index, count) in self.atom_live_counts.indexed_iter() {- visited += 1;- if count != 0 {- atoms.insert(StyleAtomID(u32::try_from(index).expect("fact atom index exceeds u32")));- }- }- for (index, count) in self.attribute_name_live_counts.indexed_iter() {- visited += 1;- if count == 0 {- continue;- }- let forms = self.attribute_name_forms(StyleAtomID(- u32::try_from(index).expect("attribute-name atom index exceeds u32"),- ));- atoms.extend(- [forms.local, forms.folded_name, forms.folded_local]- .into_iter()- .filter(|atom| !atom.is_none()),- );- }- for (index, count) in self.custom_property_set_live_counts.iter().enumerate().skip(1) {- visited += 1;- if *count != 0 {- atoms.extend(- self.custom_property_name_sets- [CustomPropertyNameSetID(u32::try_from(index).expect("custom property set index exceeds u32"))]- .iter()- .copied(),- );- }- }- visited- }-- pub(super) fn extend_live_attribute_name_forms(&self, atoms: &mut HashSet<StyleAtomID>) {- for (index, forms) in self.attribute_catalogs.name_forms.indexed_iter() {- let name = StyleAtomID(u32::try_from(index).expect("attribute-name atom index exceeds u32"));- if !atoms.contains(&name) {- continue;- }- atoms.extend(- [forms.local, forms.folded_name, forms.folded_local]- .into_iter()- .filter(|atom| !atom.is_none()),- );- }- }-- #[must_use]- #[cfg(test)]- pub fn len(&self) -> usize {- self.rows.live_row_count()- }-- #[must_use]- #[cfg(test)]- pub fn is_empty(&self) -> bool {- self.len() == 0- }-- #[must_use]- #[cfg(test)]- pub fn postings_mut(&mut self) -> &mut FeaturePostings {- &mut self.postings- }-- #[must_use]- pub fn postings(&self) -> &FeaturePostings {- &self.postings- }-- #[must_use]- pub fn primary(&self) -> &StyleNodeFacts {- assert!(- !self.has_dirty_staging(),- "cannot evaluate facts while fact staging is unapplied"- );- &self.rows- }-- /// Published answers belong to the committed transaction, even when applying its styles- /// has already staged inputs for the next one. Verify them against those committed facts.- pub(super) fn committed_for_verification(&self) -> &StyleNodeFacts {- &self.rows- }-- pub(super) fn primary_view(&mut self) -> MatchingFactBatch {- assert!(- !self.has_dirty_staging(),- "cannot evaluate facts while fact staging is unapplied"- );- self.prepare_attribute_catalogs();- MatchingFactBatch::primary_view(Arc::clone(&self.rows))- }-- #[must_use]- pub fn has_dirty_staging(&self) -> bool {- self.staging.has_dirty()- }-- #[must_use]- pub fn has_staged_input(&self) -> bool {- !self.staging.is_empty()- }-- #[must_use]- pub fn parts_of(&self, node: StyleNodeID) -> &[StyleAtomID] {- if let Some(row) = self.staging.get(node) {- return &row.parts;- }- self.rows.row_of(node).map_or(&[], |row| self.rows.parts_of(row))- }-- #[must_use]- pub fn custom_states_of(&self, node: StyleNodeID) -> &[StyleAtomID] {- if let Some(row) = self.staging.get(node) {- return &row.custom_states;- }- self.rows- .row_of(node)- .map_or(&[], |row| self.rows.custom_states_of(row))- }-- fn metadata_mut(&mut self, node: StyleNodeID) -> &mut ElementFactMetadata {- self.staging_dirty = true;- let index = node.element_index().expect("only elements carry element facts") as usize;- self.metadata- .entry(index)- .get_or_insert_with(ElementFactMetadata::default)- }-- fn metadata_of(&self, node: StyleNodeID) -> Option<&ElementFactMetadata> {- self.metadata.get(node.element_index()? as usize)?.as_ref()- }-- fn staged_row_from_primary_snapshot(&self, snapshot: PrimaryFactSnapshot) -> StagedFactRow {- let rare_facts = snapshot.rare_facts.unwrap_or_default();- StagedFactRow {- tag: snapshot.tag,- folded_tag: snapshot.folded_tag,- id: snapshot.id,- language: snapshot.language,- namespace: snapshot.namespace,- part_exposure: rare_facts.part_exposure,- directionality: snapshot.directionality,- heading_level: rare_facts.heading_level,- has_text_content: snapshot.has_text_content,- states: snapshot.states,- custom_states: rare_facts.custom_states.slice(&self.rows.custom_states).to_vec(),- parts: rare_facts.parts.slice(&self.rows.parts).to_vec(),- classes: snapshot.class_handle.slice(&self.rows.classes).to_vec(),- attributes: snapshot- .attribute_handle- .slice(&self.rows.attributes)- .iter()- .map(|attribute| (attribute.name, attribute.value))- .collect(),- }- }-- fn edit_staged_row<R>(&mut self, node: StyleNodeID, edit: impl FnOnce(&mut StagedFactRow) -> R) -> R {- self.staging_dirty = true;- if !self.staging.contains(node) {- let before = self.rows.row_of(node).map(|row| self.rows.primary_snapshot(row));- let row = before.map_or_else(StagedFactRow::default, |snapshot| {- self.staged_row_from_primary_snapshot(snapshot)- });- self.staging.insert(node, row, before);- }- self.staging.edit(node, edit).unwrap()- }-- /// Give a node a row of its own without putting a feature in it.- ///- /// A shadow root is a node of the tree and a bearer of no features at all: it is featureless by- /// definition, and nothing publishes anything about it. It still has to be materializable, or a- /// selector that reads it - a relative anchor bound at the root, the leftmost step of a chain- /// that lands there - asks for a row that never arrives and the whole match gives up.- pub fn ensure_row(&mut self, node: StyleNodeID) {- if self.rows.row_of(node).is_none() && !self.staging.contains(node) {- self.staging_dirty = true;- self.staging.insert(node, StagedFactRow::default(), None);- }- }-- pub fn set_tag(&mut self, node: StyleNodeID, tag: StyleAtomID) {- let previous = self.edit_staged_row(node, |facts| std::mem::replace(&mut facts.tag, tag));- if previous != tag {- if !previous.is_none() {- self.postings.remove(SelectorPostingKey::TagName(previous), node);- }- if !tag.is_none() {- self.postings.insert(SelectorPostingKey::TagName(tag), node);- }- }- }-- /// Record the folded form of the element's name as a second name it is posted under. A folding- /// equal to the name itself carries no information and is dropped, so the posting is never- /// inserted twice for one element.- pub fn set_folded_tag(&mut self, node: StyleNodeID, folded: StyleAtomID) {- let (previous, folded) = self.edit_staged_row(node, |facts| {- let folded = if folded == facts.tag { StyleAtomID::NONE } else { folded };- (std::mem::replace(&mut facts.folded_tag, folded), folded)- });- if previous != folded {- if !previous.is_none() {- self.postings.remove(SelectorPostingKey::TagName(previous), node);- }- if !folded.is_none() {- self.postings.insert(SelectorPostingKey::TagName(folded), node);- }- }- }-- pub fn set_id(&mut self, node: StyleNodeID, id: StyleAtomID) {- let previous = self.edit_staged_row(node, |facts| std::mem::replace(&mut facts.id, id));- if previous != id {- if !previous.is_none() {- self.postings.remove(SelectorPostingKey::Id(previous), node);- }- if !id.is_none() {- self.postings.insert(SelectorPostingKey::Id(id), node);- }- }- }-- /// The interned facts an element carries, for routing an arrival that journalled them as one.- #[must_use]- pub fn tag_of_node(&self, node: StyleNodeID) -> StyleAtomID {- self.rows- .row_of(node)- .map_or(StyleAtomID::NONE, |row| self.rows.tag_of(row))- }-- #[must_use]- pub fn folded_tag_of_node(&self, node: StyleNodeID) -> StyleAtomID {- self.rows- .row_of(node)- .map_or(StyleAtomID::NONE, |row| self.rows.folded_tag_of(row))- }-- #[must_use]- pub fn id_of_node(&self, node: StyleNodeID) -> StyleAtomID {- self.rows- .row_of(node)- .map_or(StyleAtomID::NONE, |row| self.rows.id_of(row))- }-- #[must_use]- pub fn classes_of_node(&self, node: StyleNodeID) -> &[StyleAtomID] {- self.rows.row_of(node).map_or(&[][..], |row| self.rows.classes_of(row))- }-- /// Test a dispatch key directly against the authoritative element row when that key is local.- ///- /// Candidate postings are arranged for enumeration. Once a routing batch is already streaming- /// nodes, reading the compact row avoids a second hash lookup followed by a posting membership- /// lookup for every key it tests.- #[must_use]- pub fn carries_local_dispatch_key(&self, node: StyleNodeID, key: DispatchKey) -> Option<bool> {- let row = self.rows.row_of(node);- Some(match key {- DispatchKey::Id(id) => row.is_some_and(|row| self.rows.id_of(row) == id),- DispatchKey::Class(class) => row.is_some_and(|row| self.rows.classes_of(row).binary_search(&class).is_ok()),- DispatchKey::AttributeName(name) => row.is_some_and(|row| {- self.rows.attributes_of(row).iter().any(|attribute| {- let forms = self.rows.attribute_name_forms(attribute.name);- attribute.name == name- || forms.local == name- || forms.folded_name == name- || forms.folded_local == name- })- }),- DispatchKey::TagName(tag) => {- row.is_some_and(|row| self.rows.tag_of(row) == tag || self.rows.folded_tag_of(row) == tag)- }- DispatchKey::Directionality(directionality) => {- row.is_some_and(|row| self.rows.directionality_of(row) == directionality)- }- DispatchKey::Part(_)- | DispatchKey::CustomState(_)- | DispatchKey::Root- | DispatchKey::State(_)- | DispatchKey::Heading- | DispatchKey::Universal => return None,- _ => return None,- })- }-- /// What an `attr()` can read of an element: each of its attributes in no namespace, by its- /// local name, with the text of its value. The host publishes the text of every attribute- /// name an `attr()` may read before a style update or read takes the rules that read it, so- /// an attribute without its text is one no `attr()` reads.- pub fn substitution_attributes(&self, node: StyleNodeID) -> impl Iterator<Item = (&[u16], &[u16])> {- self.rows- .row_of(node)- .map_or(&[][..], |row| self.rows.attributes_of(row))- .iter()- .filter_map(|&attribute| {- Some((- self.attribute_substitution_name(attribute.name)?,- self.rows.text_of(attribute)?,- ))- })- }-- pub fn attributes_of_node(&self, node: StyleNodeID) -> impl Iterator<Item = StyleAtomID> {- self.rows- .row_of(node)- .map_or(&[][..], |row| self.rows.attributes_of(row))- .iter()- .map(|attribute| attribute.name)- }-- #[must_use]- pub fn states_of_node(&self, node: StyleNodeID) -> StateSet {- if let Some(row) = self.staging.get(node) {- return row.states;- }- self.rows- .row_of(node)- .map_or(StateSet::default(), |row| self.rows.states_of(row))- }-- #[must_use]- pub fn part_exposure_of(&self, node: StyleNodeID) -> StyleAtomID {- self.rows- .row_of(node)- .map_or(StyleAtomID::NONE, |row| self.rows.part_exposure_of(row))- }-- pub fn set_part_exposure(&mut self, node: StyleNodeID, exposure: StyleAtomID) {- self.edit_staged_row(node, |facts| facts.part_exposure = exposure);- }-- #[must_use]- pub fn language_of(&self, node: StyleNodeID) -> StyleAtomID {- self.rows- .row_of(node)- .map_or(StyleAtomID::NONE, |row| self.rows.language_of(row))- }-- /// The element's resolved language tag, empty when it has none. A tag is recorded once per- /// language atom, so its casing is the one the first element spelling that language used.- #[must_use]- pub fn language_tag_of(&self, node: StyleNodeID) -> &[u16] {- self.rows.row_of(node).map_or(&[], |row| self.rows.language_tag_of(row))- }-- #[must_use]- pub fn namespace_of(&self, node: StyleNodeID) -> StyleAtomID {- self.rows- .row_of(node)- .map_or(StyleAtomID::NONE, |row| self.rows.namespace_of(row))- }-- #[must_use]- pub fn directionality_of(&self, node: StyleNodeID) -> StyleAtomID {- if let Some(row) = self.staging.get(node) {- return row.directionality;- }- self.rows- .row_of(node)- .map_or(StyleAtomID::NONE, |row| self.rows.directionality_of(row))- }-- pub fn set_has_text_content(&mut self, node: StyleNodeID, has_text_content: bool) {- self.edit_staged_row(node, |facts| facts.has_text_content = has_text_content);- }-- /// An element's heading level follows from what it is, so it is published as it arrives and- /// whenever an `aria-level` that overrides it moves.- pub fn set_is_slot(&mut self, node: StyleNodeID, is_slot: bool) {- self.staging_dirty = true;- if is_slot {- self.metadata_mut(node).is_slot = true;- } else if let Some(metadata) = node- .element_index()- .and_then(|index| self.metadata.get_mut(index as usize))- .and_then(Option::as_mut)- {- metadata.is_slot = false;- }- }-- #[must_use]- pub fn is_slot(&self, node: StyleNodeID) -> bool {- self.metadata_of(node).is_some_and(|metadata| metadata.is_slot)- }-- pub fn set_heading_level(&mut self, node: StyleNodeID, level: u8) {- self.edit_staged_row(node, |facts| facts.heading_level = level);- }-- #[must_use]- pub fn heading_level_of(&self, node: StyleNodeID) -> u8 {- self.rows.row_of(node).map_or(0, |row| self.rows.heading_level_of(row))- }-- /// Record what one language atom spells, so `:lang()` can compare ranges against it.- pub fn set_language_text(&mut self, language: StyleAtomID, text: &[u16]) {- let index = language.0 as usize;- if language.is_none()- || self- .attribute_catalogs- .language_texts- .get(index)- .is_some_and(Option::is_some)- {- return;- }- self.staging_dirty = true;- self.attribute_catalogs_mut()- .language_texts- .insert(index, Some(text.into()));- }-- pub fn set_language(&mut self, node: StyleNodeID, language: StyleAtomID) {- self.edit_staged_row(node, |facts| facts.language = language);- }-- /// An element's namespace is fixed when it is created, so this is published once, on arrival,- /// and is never an input that moves.- pub fn set_namespace(&mut self, node: StyleNodeID, namespace: StyleAtomID) {- self.edit_staged_row(node, |facts| facts.namespace = namespace);- }-- pub fn set_directionality(&mut self, node: StyleNodeID, directionality: StyleAtomID) {- let previous = self.edit_staged_row(node, |facts| {- std::mem::replace(&mut facts.directionality, directionality)- });- if previous != directionality {- if !previous.is_none() {- self.postings.remove(SelectorPostingKey::Directionality(previous), node);- }- if !directionality.is_none() {- self.postings- .insert(SelectorPostingKey::Directionality(directionality), node);- }- }- }-- pub fn set_class(&mut self, node: StyleNodeID, class: StyleAtomID, present: bool) {- let changed = self.edit_staged_row(node, |facts| match (present, facts.classes.binary_search(&class)) {- (true, Err(index)) => {- facts.classes.insert(index, class);- true- }- (false, Ok(index)) => {- facts.classes.remove(index);- true- }- _ => false,- });- if changed {- if present {- self.postings.insert(SelectorPostingKey::Class(class), node);- } else {- self.postings.remove(SelectorPostingKey::Class(class), node);- }- }- }-- /// Replace the set of animation names an element references.- ///- /// This arrives from computed style rather than from the DOM, so it is published as a set rather- /// than one name at a time: an element's `animation-name` is recomputed whole.- pub fn set_animation_names(&mut self, node: StyleNodeID, names: &[StyleAtomID]) {- let previous = self- .metadata_of(node)- .map_or(&[][..], |metadata| &metadata.animation_names);- if previous == names {- return;- }- let mut sorted: Vec<StyleAtomID> = names.to_vec();- sorted.sort_unstable_by_key(|name| name.0);- sorted.dedup();- if previous == sorted {- return;- }- let previous = std::mem::take(&mut self.metadata_mut(node).animation_names);- for entry in merge_sorted_by(&previous, &sorted, |left, right| left.0.cmp(&right.0)) {- match entry {- SortedMergeEntry::Left(&name) => {- self.postings.remove(DependencyPostingKey::AnimationName(name), node);- Self::decrement_atom_count(&mut self.atom_live_counts, name);- }- SortedMergeEntry::Right(&name) => {- self.postings.insert(DependencyPostingKey::AnimationName(name), node);- Self::increment_atom_count(&mut self.atom_live_counts, name);- }- SortedMergeEntry::Both(..) => {}- }- }- self.metadata_mut(node).animation_names = sorted;- }-- /// Whether this element's last style resolution called a custom function.- pub fn uses_custom_functions(&self, node: StyleNodeID) -> bool {- self.metadata_of(node)- .is_some_and(|metadata| metadata.uses_custom_functions)- }-- /// Whether this element's style resolution called a custom function.- pub fn set_uses_custom_functions(&mut self, node: StyleNodeID, uses: bool) {- if self- .metadata_of(node)- .is_some_and(|metadata| metadata.uses_custom_functions)- == uses- {- return;- }- self.metadata_mut(node).uses_custom_functions = uses;- match uses {- true => self.postings.insert(DependencyPostingKey::AnyCustomFunction, node),- false => {- self.postings.remove(DependencyPostingKey::AnyCustomFunction, node);- true- }- };- }-- /// Whether this element used custom properties whose names could not all be enumerated.- pub fn uses_unnamed_custom_properties(&self, node: StyleNodeID) -> bool {- self.metadata_of(node)- .is_some_and(|metadata| metadata.uses_unnamed_custom_properties)- }-- pub fn set_uses_unnamed_custom_properties(&mut self, node: StyleNodeID, uses: bool) {- if self- .metadata_of(node)- .is_some_and(|metadata| metadata.uses_unnamed_custom_properties)- == uses- {- return;- }- self.metadata_mut(node).uses_unnamed_custom_properties = uses;- match uses {- true => self.postings.insert(DependencyPostingKey::AnyCustomProperty, node),- false => {- self.postings.remove(DependencyPostingKey::AnyCustomProperty, node);- true- }- };- }-- /// Replace the set of custom properties an element declares or references.- /// Record which custom properties one element's own cascade declares.- ///- /// The names are held as an interned *set*: a page whose theme declares two thousand names- /// hands the same two thousand to every element it decides for, and one posting entry per name- /// per element is millions of entries for one answer. The set is stored once, the element- /// names it by identity, and a registration asks which sets hold its name.- pub fn set_custom_property_names(&mut self, node: StyleNodeID, names: &[StyleAtomID]) {- self.staging_dirty = true;- // The caller hands these sorted and deduplicated, worked out once for the environment the- // element resolved to.- debug_assert!(names.windows(2).all(|pair| pair[0].0 < pair[1].0));- let set = self.intern_custom_property_name_set(names);- let previous = self- .metadata_of(node)- .map_or(0, |metadata| metadata.custom_property_set);- if previous == set {- return;- }- let required_counts = usize::try_from(previous.max(set)).expect("custom property set index overflow") + 1;- if self.custom_property_set_live_counts.len() < required_counts {- self.custom_property_set_live_counts.resize(required_counts, 0);- }- if previous != 0 {- self.custom_property_set_live_counts[previous as usize] = self.custom_property_set_live_counts- [previous as usize]- .checked_sub(1)- .expect("custom property set live count underflow");- }- if set != 0 {- self.custom_property_set_live_counts[set as usize] = self.custom_property_set_live_counts[set as usize]- .checked_add(1)- .expect("custom property set live count overflow");- }- self.metadata_mut(node).custom_property_set = set;- if previous != 0 {- self.postings- .remove(DependencyPostingKey::CustomPropertySet(previous), node);- }- if set != 0 {- self.postings.insert(DependencyPostingKey::CustomPropertySet(set), node);- }- }-- /// One identity per distinct set of declared names. Zero is the empty set and is never stored.- fn intern_custom_property_name_set(&mut self, names: &[StyleAtomID]) -> u32 {- if names.is_empty() {- return 0;- }- let hash = super::intern_table::content_hash(names);- if let Some(candidate) = self- .custom_property_name_sets- .find(hash, |_identity, candidate| candidate.as_ref() == names)- {- return candidate.0;- }- let id = self.custom_property_name_set_vacancies.pop().unwrap_or_else(|| {- u32::try_from(self.custom_property_name_sets.len() + 1).expect("custom property name set space exhausted")- });- self.custom_property_name_sets- .insert(hash, CustomPropertyNameSetID(id), names.into());- for name in names {- self.custom_property_set_ids_by_name.entry(name.0 as usize).push(id);- }- id- }-- /// The elements whose own cascade declares `name`, which is every element in any set holding it.- pub fn custom_property_candidates(&self, name: StyleAtomID) -> Result<Vec<StyleNodeID>, PostingKey> {- let Some(sets) = self.custom_property_set_ids_by_name.get(name.0 as usize) else {- return Ok(Vec::new());- };- let mut nodes = Vec::new();- for &set in sets {- match self.postings.lookup(DependencyPostingKey::CustomPropertySet(set)) {- Lookup::Known(posting) => posting.append_candidates_to(&mut nodes),- Lookup::KnownAbsent => {}- Lookup::Missing(gap) => return Err(gap),- }- }- Ok(nodes)- }-- pub fn set_attribute(&mut self, node: StyleNodeID, name: StyleAtomID, value: StyleAtomID, present: bool) {- // An attribute is one fact under one key, but it is indexed under every name a selector can- // reach it by: its own, the any-namespace form `[*|x]` dispatches under, and the ASCII- // foldings of both, which is how `[aB]` reaches an attribute written either way. The extra- // names are postings rather than facts, so they say only that at least one attribute of the- // element answers to them.- let changed = self.edit_staged_row(node, |facts| {- let found = facts.attributes.binary_search_by_key(&name, |entry| entry.0);- match (present, found) {- (true, Ok(index)) => {- facts.attributes[index].1 = value;- false- }- (true, Err(index)) => {- facts.attributes.insert(index, (name, value));- true- }- (false, Ok(index)) => {- facts.attributes.remove(index);- true- }- (false, Err(_)) => false,- }- });- if changed && present {- for key in self.attribute_name_keys(name) {- self.postings.insert(SelectorPostingKey::AttributeName(key), node);- }- } else if changed {- // A shared name stays true of the element while another of its attributes still- // answers to it, so only the names nothing implies any more are dropped.- for key in self.attribute_name_keys(name) {- if key == name || !self.node_answers_to_attribute_name(node, key) {- self.postings.remove(SelectorPostingKey::AttributeName(key), node);- }- }- }- }-- /// Whether any attribute the node still carries is indexed under `key`.- #[must_use]- fn node_answers_to_attribute_name(&self, node: StyleNodeID, key: StyleAtomID) -> bool {- self.staging.get(node).is_some_and(|facts| {- facts- .attributes- .iter()- .any(|entry| self.attribute_name_keys(entry.0).any(|candidate| candidate == key))- })- }-- /// Record which longhand properties one of an element's own declarations covers, each with the- /// value it was written with.- pub fn set_element_declared_properties(- &mut self,- node: StyleNodeID,- kind: ElementDeclarationKind,- declarations: Vec<(DeclaredProperty, RetainedStyleValueData)>,- ) {- self.staging_dirty = true;- self.element_declared_properties.set(node, kind, declarations);- }-- /// Record the custom properties the node's inline style declares, each with the value it was- /// written with.- pub fn set_element_custom_declarations(- &mut self,- node: StyleNodeID,- custom_declarations: Vec<(CustomDeclaration, RetainedStyleValueData)>,- ) {- self.staging_dirty = true;- self.element_declared_properties.set_custom(node, custom_declarations);- }-- /// 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_declarations_for_demand(- &mut self,- node: StyleNodeID,- ) -> Option<HiddenInlineDeclarations> {- let index = node.element_index()? as usize;- let rows = &mut *self.element_declared_properties;- let row = rows.rows.get_mut(index)?.as_mut()?;- let before = row.storage_bytes();- let kind = ElementDeclarationKind::InlineStyle.index();- let hidden = HiddenInlineDeclarations {- declarations: std::mem::take(&mut row.by_kind[kind]),- custom: row.custom.take(),- };- if hidden.custom.is_some() {- rows.rows_with_custom_declarations -= 1;- }- rows.payload_bytes = rows.payload_bytes - before + row.storage_bytes();- self.staging_dirty = true;- Some(hidden)- }-- pub(super) fn restore_inline_declarations_after_demand(- &mut self,- node: StyleNodeID,- hidden: HiddenInlineDeclarations,- ) {- let index = node.element_index().expect("only an element has an inline declaration") as usize;- let rows = &mut *self.element_declared_properties;- let row = rows.rows[index]- .as_mut()- .expect("a private demand keeps the element's declaration row");- let before = row.storage_bytes();- let kind = ElementDeclarationKind::InlineStyle.index();- row.by_kind[kind] = hidden.declarations;- row.custom = hidden.custom;- if row.custom.is_some() {- rows.rows_with_custom_declarations += 1;- }- rows.payload_bytes = rows.payload_bytes - before + row.storage_bytes();- self.staging_dirty = true;- }-- /// The custom properties the node's inline style declares, in declaration order.- #[must_use]- pub fn element_custom_declarations(&self, node: StyleNodeID) -> &[CustomDeclaration] {- self.element_declared_properties- .get_custom(node)- .map_or(&[], ElementCustomDeclarations::declared)- }-- /// The custom properties the node's inline style declares, with the values they were written- /// with.- #[must_use]- pub fn element_custom_declarations_written(&self, node: StyleNodeID) -> Option<&ElementCustomDeclarations> {- self.element_declared_properties.get_custom(node)- }-- /// Whether any inline style declares a custom property.- #[must_use]- pub fn any_element_declares_custom_properties(&self) -> bool {- self.element_declared_properties.rows_with_custom_declarations != 0- }-- /// 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 fn element_declarations(- &self,- node: StyleNodeID,- kind: ElementDeclarationKind,- ) -> Option<&ElementDeclarations> {- self.element_declared_properties.declarations(node, kind)- }-- #[must_use]- pub fn element_declared_properties(&self, node: StyleNodeID, kind: ElementDeclarationKind) -> &[DeclaredProperty] {- self.element_declared_properties.get(node, kind)- }-- /// Record that `name` is an attribute name whose any-namespace form is `local`.- ///- /// Published where the two atoms are minted, which is the only place that knows the pair. It is- /// idempotent and total: every attribute name goes through it, including one in no namespace,- /// whose local form is still an atom of its own.- pub fn note_attribute_name_forms(&mut self, name: StyleAtomID, forms: AttributeNameForms) {- self.staging_dirty = true;- self.attribute_catalogs_mut().name_forms.insert(name.0 as usize, forms);- }-- /// Record the local name an `attr()` reads the attribute `name` by, which is in no namespace.- pub fn note_attribute_substitution_name(&mut self, name: StyleAtomID, local_name: &[u16]) {- self.staging_dirty = true;- self.attribute_catalogs_mut()- .substitution_names- .insert(name.0 as usize, Some(local_name.into()));- }-- /// The local name an `attr()` reads an attribute by, if the attribute is in no namespace.- #[must_use]- pub fn attribute_substitution_name(&self, name: StyleAtomID) -> Option<&[u16]> {- self.attribute_catalogs- .substitution_names- .get(name.0 as usize)- .and_then(Option::as_deref)- }-- /// The other names an attribute name answers to, all `NONE` if the name has not been published.- #[must_use]- pub fn attribute_name_forms(&self, name: StyleAtomID) -> AttributeNameForms {- self.attribute_catalogs- .name_forms- .get(name.0 as usize)- .unwrap_or_default()- }-- /// Every atom an attribute of this name is indexed under, without repeats.- pub fn attribute_name_keys(&self, name: StyleAtomID) -> impl Iterator<Item = StyleAtomID> + use<> {- let forms = self.attribute_name_forms(name);- let keys = [name, forms.local, forms.folded_name, forms.folded_local];- keys.into_iter()- .enumerate()- .filter_map(move |(index, key)| (!key.is_none() && !keys[..index].contains(&key)).then_some(key))- }-- /// Record what one attribute-value atom spells, for a value operator to test or an `attr()` to- /// read. Values repeat heavily across a document, so the text is held once per distinct value.- pub fn set_attribute_value_text(&mut self, value: StyleAtomID, text: &[u16]) {- let index = value.0 as usize;- if value.is_none()- || self- .attribute_catalogs- .value_texts- .get(index)- .is_some_and(Option::is_some)- {- return;- }- self.staging_dirty = true;- self.attribute_catalogs_mut()- .value_texts- .insert(index, Some(text.into()));- }-- #[must_use]- #[cfg(test)]- pub fn has_attribute_value_text(&self, value: StyleAtomID) -> bool {- self.attribute_catalogs- .value_texts- .get(value.0 as usize)- .is_some_and(Option::is_some)- }-- pub fn set_state(&mut self, node: StyleNodeID, fact: StateFact, value: bool) {- let changed = self.edit_staged_row(node, |facts| {- if facts.states.contains(fact) == value {- return false;- }- if value {- facts.states.insert(fact);- } else {- facts.states.remove(fact);- }- true- });- if changed && fact.has_selector_posting() {- if value {- self.postings.insert(SelectorPostingKey::State(fact), node);- } else {- self.postings.remove(SelectorPostingKey::State(fact), node);- }- }- }-- pub fn set_parts(&mut self, node: StyleNodeID, parts: &[StyleAtomID]) {- let previous = self.staging.get(node).map_or_else(- || self.rows.row_of(node).map_or(&[][..], |row| self.rows.parts_of(row)),- |facts| facts.parts.as_slice(),- );- for &part in previous.iter().filter(|part| !parts.contains(part)) {- self.postings.remove(SelectorPostingKey::Part(part), node);- }- for &part in parts.iter().filter(|part| !previous.contains(part)) {- self.postings.insert(SelectorPostingKey::Part(part), node);- }- self.edit_staged_row(node, |facts| parts.clone_into(&mut facts.parts));- }-- pub fn set_custom_states(&mut self, node: StyleNodeID, states: &[StyleAtomID]) {- let previous = self.staging.get(node).map_or_else(- || {- self.rows- .row_of(node)- .map_or(&[][..], |row| self.rows.custom_states_of(row))- },- |facts| facts.custom_states.as_slice(),- );- for &state in previous.iter().filter(|state| !states.contains(state)) {- self.postings.remove(SelectorPostingKey::CustomState(state), node);- }- for &state in states.iter().filter(|state| !previous.contains(state)) {- self.postings.insert(SelectorPostingKey::CustomState(state), node);- }- self.edit_staged_row(node, |facts| states.clone_into(&mut facts.custom_states));- }-- pub fn forget(&mut self, node: StyleNodeID) {- self.staging_dirty = true;- self.element_declared_properties.remove(node);- self.staging.remove(node);- let Some(row) = self.rows.row_of(node) else {- return;- };- self.remove_row_catalog_references(row);- let tag = self.rows.tag_of(row);- if !tag.is_none() {- self.postings.remove(SelectorPostingKey::TagName(tag), node);- }- let folded_tag = self.rows.folded_tag_of(row);- if !folded_tag.is_none() {- self.postings.remove(SelectorPostingKey::TagName(folded_tag), node);- }- let id = self.rows.id_of(row);- if !id.is_none() {- self.postings.remove(SelectorPostingKey::Id(id), node);- }- let directionality = self.rows.directionality_of(row);- if !directionality.is_none() {- self.postings- .remove(SelectorPostingKey::Directionality(directionality), node);- }- for &class in self.rows.classes_of(row) {- self.postings.remove(SelectorPostingKey::Class(class), node);- }- for &part in self.rows.parts_of(row) {- self.postings.remove(SelectorPostingKey::Part(part), node);- }- for &state in self.rows.custom_states_of(row) {- self.postings.remove(SelectorPostingKey::CustomState(state), node);- }- for state in self- .rows- .states_of(row)- .facts()- .filter(|state| state.has_selector_posting())- {- self.postings.remove(SelectorPostingKey::State(state), node);- }- for &AttributeFact { name, .. } in self.rows.attributes_of(row) {- for key in self.attribute_name_keys(name) {- self.postings.remove(SelectorPostingKey::AttributeName(key), node);- }- }- Arc::make_mut(&mut self.rows).forget_row(node);- if let Some(metadata) = node- .element_index()- .and_then(|index| self.metadata.get_mut(index as usize))- .and_then(Option::take)- {- if metadata.custom_property_set != 0 {- self.custom_property_set_live_counts[metadata.custom_property_set as usize] = self- .custom_property_set_live_counts[metadata.custom_property_set as usize]- .checked_sub(1)- .expect("custom property set live count underflow");- }- for name in metadata.animation_names {- self.postings.remove(DependencyPostingKey::AnimationName(name), node);- Self::decrement_atom_count(&mut self.atom_live_counts, name);- }- if metadata.custom_property_set != 0 {- self.postings.remove(- DependencyPostingKey::CustomPropertySet(metadata.custom_property_set),- node,- );- }- if metadata.uses_unnamed_custom_properties {- self.postings.remove(DependencyPostingKey::AnyCustomProperty, node);- }- if metadata.uses_custom_functions {- self.postings.remove(DependencyPostingKey::AnyCustomFunction, node);- }- }- }-- /// Whether a borrowed primary view (an active or prepared traversal) shares the fact rows.- #[cfg(test)]- pub(super) fn primary_rows_are_shared(&self) -> bool {- Arc::strong_count(&self.rows) != 1- }-- /// NB: A retained traversal or a fork of the store may share the primary rows. The sweep writes only the store's- /// own catalogs, and `prepare_attribute_catalogs` copies the rows where they are shared.- pub(super) fn sweep_auxiliary_catalogs_without_sync(&mut self) {- self.staging_dirty = true;- let attribute_catalogs = Arc::make_mut(&mut self.attribute_catalogs);- // Language spellings and attribute-name forms are retained until their atom is reclaimed;- // forget_atoms clears them at that authoritative boundary so a reused identity can publish- // different text. Attribute values can be dropped earlier when their last fact leaves.- for (index, text) in attribute_catalogs.value_texts.indexed_iter_mut() {- if self.attribute_value_live_counts.get(index).unwrap_or(0) == 0 {- *text = None;- }- }-- for sets in self.custom_property_set_ids_by_name.iter_mut() {- *sets = Vec::new();- }- self.custom_property_name_set_vacancies.clear();- for id in 1..=self.custom_property_name_sets.len() {- if self.custom_property_set_live_counts.get(id).copied().unwrap_or(0) == 0 {- let identity = CustomPropertyNameSetID(id as u32);- if !self.custom_property_name_sets[identity].is_empty() {- let hash = super::intern_table::content_hash(&self.custom_property_name_sets[identity]);- self.custom_property_name_sets.remove_identity(hash, identity);- self.custom_property_name_sets[identity] = Box::default();- }- self.custom_property_name_set_vacancies.push(id as u32);- continue;- }- let names = &self.custom_property_name_sets[CustomPropertyNameSetID(id as u32)];- for name in names {- self.custom_property_set_ids_by_name- .entry(name.0 as usize)- .push(id as u32);- }- }- }-- pub fn sweep_auxiliary_catalogs(&mut self) {- self.sweep_auxiliary_catalogs_without_sync();- self.prepare_attribute_catalogs();- }-- /// Remove every derived row keyed by an identity before that identity can be reused.- pub(super) fn forget_atoms(&mut self, atoms: &[StyleAtomID]) {- if atoms.is_empty() {- return;- }- self.staging_dirty = true;- let atoms = atoms.iter().copied().collect::<HashSet<_>>();- let catalogs = Arc::make_mut(&mut self.attribute_catalogs);- for atom in &atoms {- let index = atom.0 as usize;- if catalogs.name_forms.get(index).is_some() {- catalogs.name_forms.insert(index, AttributeNameForms::default());- }- if let Some(name) = catalogs.substitution_names.get_mut(index) {- *name = None;- }- if let Some(text) = catalogs.value_texts.get_mut(index) {- *text = None;- }- if let Some(text) = catalogs.language_texts.get_mut(index) {- *text = None;- }- if let Some(sets) = self.custom_property_set_ids_by_name.get_mut(index) {- sets.clear();- }- }- for (_, forms) in catalogs.name_forms.indexed_iter() {- assert!(- ![forms.local, forms.folded_name, forms.folded_local]- .into_iter()- .any(|atom| atoms.contains(&atom)),- "a live attribute name must keep all of its derived forms live"- );- }- self.postings.forget_atoms(&atoms);- self.prepare_attribute_catalogs();- }-- #[must_use]- #[cfg(test)]- pub fn covers(&self, node: StyleNodeID) -> bool {- self.rows.row_of(node).is_some() || self.staging.contains(node)- }-- /// Pack the facts of a bounded set of style nodes into one batch.- ///- /// A node the store has never heard a fact for is skipped rather than given defaults, so the- /// evaluator reports a miss and the caller widens instead of matching against a fiction.- ///- /// Every column an operator can read is filled, not only the ones a compound tests: a row whose- /// parameters were left at their defaults answers `:dir()` and `:state()` as though the element- /// held neither, which is a wrong answer rather than a missing one.- // NB: Commit prepares the resident catalogs. A packed batch takes the current catalog- // owner directly and never needs to mutate the shared primary rows.- pub fn materialize(&self, nodes: impl Iterator<Item = StyleNodeID>, batch: &mut StyleNodeFacts) {- batch.clear();- batch.attribute_catalogs = Arc::clone(&self.attribute_catalogs);- for node in nodes {- self.materialize_row(node, batch);- }- }-- /// Append the rows of `nodes` that the batch does not hold yet, keeping existing rows.- ///- /// One shared batch can serve a whole pass this way: consecutive asks overwhelmingly share- /// their ancestor chains, and each row is packed at most once per pass instead of once per- /// ask.- pub fn materialize_missing(&self, nodes: impl Iterator<Item = StyleNodeID>, batch: &mut StyleNodeFacts) {- batch.attribute_catalogs = Arc::clone(&self.attribute_catalogs);- for node in nodes {- if batch.row_of(node).is_some() {- continue;- }- self.materialize_row(node, batch);- }- }-- fn materialize_row(&self, node: StyleNodeID, batch: &mut StyleNodeFacts) {- let Some(row) = self.rows.row_of(node) else {- return;- };- batch.push_row_from(node, &self.rows, row);- }-- /// Commit every fact-staging edit to the authoritative arrangement.- pub fn apply_staged(&mut self) {- if !self.staging_dirty {- return;- }- self.prepare_attribute_catalogs();- let mut staging = std::mem::take(&mut self.staging);- for (node, facts) in staging.dirty_rows() {- let previous = self.rows.row_of(node);- if let Some(previous) = previous {- self.remove_row_catalog_references(previous);- }- self.add_row_catalog_references(facts);- // A selector-free transaction may retain the active traversal's immutable primary- // view. Preserve that view while advancing the authoritative rows for the next- // transaction.- Arc::make_mut(&mut self.rows).set_primary_row(node, facts);- }- staging.mark_applied();- self.staging = staging;- self.postings.update_selector_posting_limit(self.rows.live_row_count());-- self.staging_dirty = false;- }-- /// Snapshot the committed rows which staged local facts will replace at the barrier.- #[must_use]- pub fn staged_before_facts(&mut self) -> StyleNodeFacts {- self.prepare_attribute_catalogs();- let mut nodes = Vec::with_capacity(self.staging.len());- for node in self.staging.keys() {- nodes.push(node);- }- nodes.sort_unstable();- let mut before = StyleNodeFacts::new();- before.attribute_catalogs = Arc::clone(&self.attribute_catalogs);- for node in nodes {- let pair = self- .staging- .rows- .get(FactStaging::index(node))- .and_then(|entry| self.staging.entries[entry as usize].as_ref())- .expect("fact staging node must have a staged row");- if let Some(snapshot) = pair.before {- before.push_row_from_primary_snapshot(node, &self.rows, snapshot);- } else {- before.push_row(- node,- StyleAtomID::NONE,- StyleAtomID::NONE,- StateSet::default(),- &[],- &[],- );- }- }- before- }-- pub fn release_staging(&mut self) {- self.staging.clear();- Arc::make_mut(&mut self.rows).compact_primary_payloads_if_mostly_stale();- }-}--#[cfg(test)]-mod tests {- use super::super::tree::StyleNodeTree;- use super::*;-- fn known_posting(postings: &FeaturePostings, key: PostingKey) -> &Posting {- match postings.lookup(key) {- Lookup::Known(posting) => posting,- Lookup::KnownAbsent | Lookup::Missing(_) => panic!("expected a retained posting"),- }- }-- #[test]- fn interaction_states_keep_a_posting() {- let mut facts = ElementFactStore::new();- let node = StyleNodeID::element(1);- facts.set_state(node, StateFact::Focus, true);- facts.set_state(node, StateFact::Enabled, true);- facts.apply_staged();- assert!(known_posting(facts.postings(), SelectorPostingKey::State(StateFact::Focus)).contains(node));- assert!(matches!(- facts.postings().lookup(SelectorPostingKey::State(StateFact::Enabled)),- Lookup::KnownAbsent- ));-- facts.set_state(node, StateFact::Focus, false);- assert!(matches!(- facts.postings().lookup(SelectorPostingKey::State(StateFact::Focus)),- Lookup::KnownAbsent- ));-- facts.set_state(node, StateFact::Focus, true);- facts.apply_staged();- facts.forget(node);- assert!(matches!(- facts.postings().lookup(SelectorPostingKey::State(StateFact::Focus)),- Lookup::KnownAbsent- ));- }-- #[test]- fn a_posting_stays_sorted_across_chunk_splits() {- let mut postings = FeaturePostings::new();- let key = SelectorPostingKey::Class(StyleAtomID(1));-- // Insert in order and across enough members to force several append-only chunks.- for index in 1..2000_u32 {- assert!(postings.insert(key, StyleNodeID::element(index)));- }- // Rebuild the same posting out of order to exercise chunk splits as well.- for index in 1..2000_u32 {- postings.remove(key, StyleNodeID::element(index));- }- for index in (1..2000_u32).rev() {- assert!(postings.insert(key, StyleNodeID::element(index)));- }- assert_eq!(known_posting(&postings, key).len(), 1999);-- let candidates: Vec<StyleNodeID> = known_posting(&postings, key).candidates().collect();- assert_eq!(candidates.len(), 1999);- assert!(candidates.windows(2).all(|pair| pair[0] < pair[1]));- assert!(known_posting(&postings, key).contains(StyleNodeID::element(1000)));- assert!(!known_posting(&postings, key).contains(StyleNodeID::element(2500)));-- // Re-inserting a member changes nothing.- assert!(postings.insert(key, StyleNodeID::element(1000)));- assert_eq!(known_posting(&postings, key).len(), 1999);- }-- #[test]- fn removing_the_last_member_reclaims_the_posting() {- let mut postings = FeaturePostings::new();- let key = SelectorPostingKey::Class(StyleAtomID(1));- assert!(matches!(postings.lookup(key), Lookup::KnownAbsent));- for index in 1..500_u32 {- postings.insert(key, StyleNodeID::element(index));- }-- for index in 1..500_u32 {- postings.remove(key, StyleNodeID::element(index));- }- assert!(matches!(postings.lookup(key), Lookup::KnownAbsent));- assert_eq!(postings.feature_count(), 0);- }-- #[test]- fn local_dispatch_keys_read_the_authoritative_element_row() {- let mut facts = ElementFactStore::new();- let node = StyleNodeID::element(1);- let tag = StyleAtomID(10);- let folded_tag = StyleAtomID(11);- let id = StyleAtomID(20);- let class = StyleAtomID(30);- let attribute = StyleAtomID(40);- let local_attribute = StyleAtomID(41);- let directionality = StyleAtomID(50);-- facts.set_tag(node, tag);- facts.set_folded_tag(node, folded_tag);- facts.set_id(node, id);- facts.set_class(node, class, true);- facts.note_attribute_name_forms(- attribute,- AttributeNameForms {- local: local_attribute,- ..Default::default()- },- );- facts.set_attribute(node, attribute, StyleAtomID(42), true);- facts.set_directionality(node, directionality);- facts.apply_staged();-- for key in [- DispatchKey::TagName(tag),- DispatchKey::TagName(folded_tag),- DispatchKey::Id(id),- DispatchKey::Class(class),- DispatchKey::AttributeName(attribute),- DispatchKey::AttributeName(local_attribute),- DispatchKey::Directionality(directionality),- ] {- assert_eq!(facts.carries_local_dispatch_key(node, key), Some(true));- }- assert_eq!(- facts.carries_local_dispatch_key(node, DispatchKey::Class(StyleAtomID(31))),- Some(false)- );- assert_eq!(facts.carries_local_dispatch_key(node, DispatchKey::Universal), None);- }-- #[test]- fn directionality_reads_include_pending_changes() {- let mut facts = ElementFactStore::new();- let node = StyleNodeID::element(1);-- facts.set_directionality(node, StyleAtomID(2));- facts.apply_staged();- facts.set_directionality(node, StyleAtomID(4));-- assert_eq!(facts.directionality_of(node), StyleAtomID(4));- }-- #[test]- fn forgetting_an_element_removes_every_owned_posting() {- let mut facts = ElementFactStore::new();- let node = StyleNodeID::element(1);- let name = StyleAtomID(10);- let part = StyleAtomID(30);- let custom_state = StyleAtomID(31);- let forms = AttributeNameForms {- local: StyleAtomID(11),- folded_name: StyleAtomID(12),- folded_local: StyleAtomID(13),- };- facts.note_attribute_name_forms(name, forms);- facts.set_attribute(node, name, StyleAtomID(20), true);- facts.set_parts(node, &[part]);- facts.set_custom_states(node, &[custom_state]);- facts.apply_staged();-- for key in [name, forms.local, forms.folded_name, forms.folded_local] {- assert!(known_posting(&facts.postings, SelectorPostingKey::AttributeName(key)).contains(node));- }- assert!(known_posting(&facts.postings, SelectorPostingKey::Part(part)).contains(node));- assert!(known_posting(&facts.postings, SelectorPostingKey::CustomState(custom_state)).contains(node));-- facts.forget(node);-- for key in [name, forms.local, forms.folded_name, forms.folded_local] {- assert!(matches!(- facts.postings.lookup(SelectorPostingKey::AttributeName(key)),- Lookup::KnownAbsent- ));- }- assert!(matches!(- facts.postings.lookup(SelectorPostingKey::Part(part)),- Lookup::KnownAbsent- ));- assert!(matches!(- facts.postings.lookup(SelectorPostingKey::CustomState(custom_state)),- Lookup::KnownAbsent- ));- }-- #[test]- fn resident_fact_rows_follow_dense_element_identity_slots() {- let mut facts = ElementFactStore::new();- let first = StyleNodeID::element(3);- let later = StyleNodeID::element(64);-- facts.set_tag(first, StyleAtomID(10));- facts.set_tag(later, StyleAtomID(20));- facts.apply_staged();- assert_eq!(facts.len(), 2);- assert!(facts.rows.row_by_element_index.is_empty());- assert_eq!(facts.rows.row_of(first), Some(3));- assert_eq!(facts.rows.row_of(later), Some(64));- assert_eq!(facts.tag_of_node(first), StyleAtomID(10));- assert_eq!(facts.tag_of_node(later), StyleAtomID(20));-- facts.forget(first);- assert_eq!(facts.len(), 1);- assert!(!facts.covers(first));- facts.ensure_row(first);- facts.apply_staged();- assert_eq!(facts.len(), 2);- assert_eq!(facts.tag_of_node(first), StyleAtomID::NONE);- }-- #[test]- fn primary_fact_rows_replace_element_slots_in_place() {- let mut facts = ElementFactStore::new();- let node = StyleNodeID::element(3);- let first_class = StyleAtomID(20);- let second_class = StyleAtomID(21);- let part = StyleAtomID(30);- let custom_state = StyleAtomID(31);-- facts.set_tag(node, StyleAtomID(10));- facts.set_class(node, first_class, true);- assert!(facts.has_dirty_staging());- facts.apply_staged();- assert!(!facts.has_dirty_staging());- let initial_generation = facts.primary().generation();- assert_eq!(facts.primary().row_count(), 4);- assert_eq!(facts.primary().stale_rows(), 0);-- facts.set_class(node, second_class, true);- facts.set_state(node, StateFact::Hover, true);- facts.set_parts(node, &[part]);- facts.set_custom_states(node, &[custom_state]);- facts.apply_staged();- assert_eq!(facts.primary().generation(), initial_generation);- assert_eq!(facts.primary().row_count(), 4);- assert_eq!(facts.primary().stale_rows(), 0);- assert_eq!(facts.classes_of_node(node), &[first_class, second_class]);- let row = facts.primary().row_of(node).unwrap();- assert_eq!(facts.primary().parts_of(row), &[part]);- assert_eq!(facts.primary().custom_states_of(row), &[custom_state]);-- facts.set_class(node, first_class, false);- facts.apply_staged();- assert_eq!(facts.primary().generation(), initial_generation);- assert_eq!(facts.primary().row_count(), 4);- assert_eq!(facts.primary().stale_rows(), 0);- assert_eq!(facts.classes_of_node(node), &[second_class]);- assert!(facts.states_of_node(node).contains(StateFact::Hover));- }-- #[test]- fn fixed_fact_changes_reuse_primary_payload_handles() {- let mut facts = ElementFactStore::new();- let node = StyleNodeID::element(1);- facts.set_class(node, StyleAtomID(10), true);- facts.set_attribute(node, StyleAtomID(20), StyleAtomID(21), true);- facts.apply_staged();- let payload_lengths = (facts.rows.classes.len(), facts.rows.attributes.len());-- facts.set_state(node, StateFact::Hover, true);- facts.apply_staged();-- assert_eq!((facts.rows.classes.len(), facts.rows.attributes.len()), payload_lengths);- }-- #[test]- fn ordinary_elements_allocate_no_optional_fact_metadata() {- let mut facts = ElementFactStore::new();- let node = StyleNodeID::element(64);-- facts.set_is_slot(node, false);- assert!(facts.metadata.is_empty());-- facts.set_is_slot(node, true);- assert!(facts.is_slot(node));- facts.set_is_slot(node, false);- assert!(!facts.is_slot(node));- }-- #[test]- fn element_fact_capacity_includes_auxiliary_catalogs_and_staging() {- let mut facts = ElementFactStore::new();- let node = StyleNodeID::element(64);-- facts.set_class(node, StyleAtomID(1), true);- facts.set_parts(node, &[StyleAtomID(2), StyleAtomID(3)]);- facts.set_custom_states(node, &[StyleAtomID(4), StyleAtomID(5)]);- facts.set_attribute(node, StyleAtomID(6), StyleAtomID(7), true);-- facts.set_animation_names(node, &[StyleAtomID(8), StyleAtomID(9)]);-- facts.set_language_text(StyleAtomID(10), &[1, 2, 3, 4]);- facts.set_attribute_value_text(StyleAtomID(11), &[5, 6, 7, 8]);- facts.note_attribute_name_forms(- StyleAtomID(12),- AttributeNameForms {- local: StyleAtomID(13),- folded_name: StyleAtomID(14),- folded_local: StyleAtomID(15),- },- );-- facts.set_custom_property_names(node, &[StyleAtomID(16), StyleAtomID(17)]);- facts.apply_staged();- facts.release_staging();- }-- #[test]- fn live_fact_atom_roots_use_incremental_counts() {- let mut facts = ElementFactStore::new();- let node = StyleNodeID::element(1);- facts.set_tag(node, StyleAtomID(1));- facts.set_folded_tag(node, StyleAtomID(2));- facts.set_id(node, StyleAtomID(3));- facts.set_language(node, StyleAtomID(4));- facts.set_namespace(node, StyleAtomID(5));- facts.set_part_exposure(node, StyleAtomID(6));- facts.set_directionality(node, StyleAtomID(7));- facts.set_custom_states(node, &[StyleAtomID(8)]);- facts.set_parts(node, &[StyleAtomID(9)]);- facts.set_class(node, StyleAtomID(10), true);- facts.note_attribute_name_forms(- StyleAtomID(11),- AttributeNameForms {- local: StyleAtomID(13),- folded_name: StyleAtomID(14),- folded_local: StyleAtomID(15),- },- );- facts.set_attribute(node, StyleAtomID(11), StyleAtomID(12), true);- facts.set_animation_names(node, &[StyleAtomID(16)]);- facts.set_custom_property_names(node, &[StyleAtomID(17)]);- facts.apply_staged();-- let mut atoms = HashSet::default();- let visited = facts.collect_atoms(&mut atoms);- assert_eq!(visited, 15);- assert_eq!(atoms, (1..=17).map(StyleAtomID).collect());-- facts.forget(node);- let mut atoms = HashSet::default();- facts.collect_atoms(&mut atoms);- assert!(atoms.is_empty());- }-- #[test]- fn a_copy_of_the_store_sweeps_its_catalogs_apart_from_the_store() {- let mut facts = ElementFactStore::new();- let node = StyleNodeID::element(1);- let attribute_name = StyleAtomID(1);- let attribute_value = StyleAtomID(2);- facts.note_attribute_name_forms(- attribute_name,- AttributeNameForms {- local: StyleAtomID(3),- folded_name: StyleAtomID(4),- folded_local: StyleAtomID(5),- },- );- facts.set_attribute_value_text(attribute_value, &[1]);- facts.set_attribute(node, attribute_name, attribute_value, true);- facts.apply_staged();-- // A fork of the render state copies the store, which then shares the primary rows with it.- let mut copy = facts.clone();- facts.sweep_auxiliary_catalogs();- copy.sweep_auxiliary_catalogs();- for store in [&facts, ©] {- assert_eq!(- store- .rows- .attribute_catalogs- .value_texts- .get(attribute_value.0 as usize),- Some(&Some(Box::from([1_u16])))- );- }- }-- #[test]- fn detached_element_churn_reuses_reclaimable_auxiliary_catalog_storage() {- let mut facts = ElementFactStore::new();- let node = StyleNodeID::element(1);-- for index in 1..128_u32 {- let language = StyleAtomID(index * 4);- let attribute_name = StyleAtomID(index * 4 + 1);- let attribute_value = StyleAtomID(index * 4 + 2);- let custom_property = StyleAtomID(index * 4 + 3);- let name_forms = AttributeNameForms {- local: StyleAtomID(index * 4 + 1000),- folded_name: StyleAtomID(index * 4 + 1001),- folded_local: StyleAtomID(index * 4 + 1002),- };- facts.set_language_text(language, &[index as u16]);- facts.set_language(node, language);- facts.note_attribute_name_forms(attribute_name, name_forms);- facts.set_attribute_value_text(attribute_value, &[index as u16]);- facts.set_attribute(node, attribute_name, attribute_value, true);- facts.set_custom_property_names(node, &[custom_property]);- facts.apply_staged();-- facts.forget(node);- facts.sweep_auxiliary_catalogs();- assert_eq!(- facts.rows.attribute_catalogs.language_texts.get(language.0 as usize),- Some(&Some(Box::from([index as u16])))- );- assert_eq!(- facts.rows.attribute_catalogs.name_forms.get(attribute_name.0 as usize),- Some(name_forms)- );- assert!(facts.rows.attribute_catalogs.value_texts.iter().all(Option::is_none));- assert!(facts.custom_property_name_sets.live_is_empty());- assert!(facts.custom_property_set_ids_by_name.iter().all(Vec::is_empty));- }-- assert_eq!(facts.custom_property_name_sets.len(), 1);- assert_eq!(facts.custom_property_name_set_vacancies, [1]);- }-- #[test]- fn element_declarations_follow_dense_element_identity_slots() {- let mut facts = ElementFactStore::new();- 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, value| DeclaredProperty {- property,- important,- operator: super::super::cascade::CascadeOperator::Declared,- value: super::super::cascade::SpecifiedValueID(value),- };-- facts.set_element_declared_properties(- first,- inline,- unwritten_declarations(&[declared(1, false, 10), declared(2, true, 20)]),- );- facts.set_element_declared_properties(first, hints, unwritten_declarations(&[declared(3, false, 30)]));- facts.set_element_declared_properties(later, svg, unwritten_declarations(&[declared(4, false, 40)]));- facts.set_element_declared_properties(later, inline, Vec::new());- assert_eq!(- facts.element_declared_properties.get(first, inline),- &[declared(1, false, 10), declared(2, true, 20)][..]- );- assert_eq!(- facts.element_declared_properties.get(first, hints),- &[declared(3, false, 30)][..]- );- assert_eq!(- facts.element_declared_properties.get(later, svg),- &[declared(4, false, 40)][..]- );- assert!(facts.element_declared_properties.get(later, inline).is_empty());- assert_eq!(facts.element_declared_properties.rows.len(), 65);- facts.set_element_declared_properties(first, inline, Vec::new());- assert!(facts.element_declared_properties.get(first, inline).is_empty());- assert_eq!(- facts.element_declared_properties.get(first, hints),- &[declared(3, false, 30)][..]- );-- // Declaration rows can exist without a resident selector-fact row. Retirement still has to- // clear them before the dense identity is reused.- facts.forget(first);- assert!(facts.element_declared_properties.get(first, hints).is_empty());- assert_eq!(- facts.element_declared_properties.get(later, svg),- &[declared(4, false, 40)][..]- );- facts.apply_staged();- }-- #[test]- fn high_cardinality_caps_apply_only_to_selector_postings() {- let mut postings = FeaturePostings::new();- let selector = SelectorPostingKey::Class(StyleAtomID(1));- let dependency = DependencyPostingKey::AnimationName(StyleAtomID(2));- postings.set_selector_posting_limit(2);- for index in 1..=3 {- let node = StyleNodeID::element(index);- assert_eq!(postings.insert(selector, node), index <= 2);- assert!(postings.insert(dependency, node));- }-- assert!(matches!(postings.lookup(selector), Lookup::Missing(gap) if gap == selector));- assert_eq!(known_posting(&postings, dependency).length, 3);- assert!(!postings.insert(selector, StyleNodeID::element(4)));- }-- #[test]- fn grown_postings_are_rechecked_against_the_fresh_limit() {- let mut postings = FeaturePostings::new();- let key = SelectorPostingKey::Class(StyleAtomID(1));- postings.set_selector_posting_limit(5000);- for index in 1..=4097 {- assert!(postings.insert(key, StyleNodeID::element(index)));- }-- postings.update_selector_posting_limit(1);-- assert!(matches!(postings.lookup(key), Lookup::Missing(gap) if gap == key));- assert!(postings.grown_selector_postings.is_empty());- }-- #[test]- fn evicting_one_posting_preserves_exact_absence_for_other_keys() {- let mut postings = FeaturePostings::new();- let evicted = SelectorPostingKey::Class(StyleAtomID(1));- let absent = SelectorPostingKey::Class(StyleAtomID(2));- postings.insert(evicted, StyleNodeID::element(1));-- postings.drop_posting(evicted);-- assert!(matches!(postings.lookup(evicted), Lookup::Missing(gap) if gap == evicted));- assert!(matches!(postings.lookup(absent), Lookup::KnownAbsent));- }-- #[test]- fn primary_fact_capacity_matches_its_columns() {- let mut store = ElementFactStore::new();-- // Grow: enough classes and attributes per row to force several reallocations.- for index in 1..40_u32 {- let node = StyleNodeID::element(index);- for name in 1..12_u32 {- store.set_class(node, StyleAtomID(name), true);- store.set_attribute(node, StyleAtomID(name), StyleAtomID::NONE, true);- }- store.apply_staged();- store.release_staging();- }-- // Shrink: removals leave capacity where it was, and forgetting a row gives it all back.- for index in 1..40_u32 {- let node = StyleNodeID::element(index);- for name in 1..6_u32 {- store.set_class(node, StyleAtomID(name), false);- store.set_attribute(node, StyleAtomID(name), StyleAtomID::NONE, false);- }- store.apply_staged();- store.release_staging();- }-- for index in 1..40_u32 {- store.forget(StyleNodeID::element(index));- store.apply_staged();- store.release_staging();- }- assert!(store.is_empty());-- // The retained column capacities remain charged after every live row is forgotten.- store.apply_staged();- store.release_staging();- }-- #[test]- fn cascade_order_projection_handles_duplicate_entries_and_sparse_rules() {- let mut dispatch = RuleDispatch::new();- let entry = |rule: u32, selector_entry: u32, multi_key| DispatchEntry {- identity: EntryID(rule * 10 + selector_entry),- rule: RuleID(rule),- program: SelectorProgramID(rule),- entry: selector_entry,- cascade_order: 0,- required_attribute_value: StyleAtomID::NONE,- required_parent: None,- required_ancestor: None,- required_ancestor_index: None,- required_subject_bloom: 0,- prefix_matched: false,- multi_key,- };- dispatch.insert(DispatchKey::Class(StyleAtomID(10)), entry(1, 0, true));- dispatch.insert(DispatchKey::Class(StyleAtomID(11)), entry(1, 0, true));- dispatch.insert(DispatchKey::Class(StyleAtomID(12)), entry(1, 1, false));- dispatch.insert(DispatchKey::Class(StyleAtomID(13)), entry(1000, 0, false));-- dispatch.assign_cascade_order(|candidate| candidate.rule);-- let first_branch = dispatch.bucket(DispatchKey::Class(StyleAtomID(10))).next().unwrap();- let second_branch = dispatch.bucket(DispatchKey::Class(StyleAtomID(11))).next().unwrap();- let later_entry = dispatch.bucket(DispatchKey::Class(StyleAtomID(12))).next().unwrap();- let sparse_rule = dispatch.bucket(DispatchKey::Class(StyleAtomID(13))).next().unwrap();- assert_eq!(first_branch.cascade_order, second_branch.cascade_order);- assert!(first_branch.cascade_order < later_entry.cascade_order);- assert_eq!(- dispatch.cascade_order_for_entry(first_branch.rule, first_branch.program, first_branch.entry),- Some(first_branch.cascade_order)- );- assert_eq!(- dispatch.cascade_order_for_entry(later_entry.rule, later_entry.program, later_entry.entry),- Some(later_entry.cascade_order)- );- assert_eq!(- dispatch.cascade_order_for_entry(sparse_rule.rule, sparse_rule.program, sparse_rule.entry),- Some(sparse_rule.cascade_order)- );- assert_eq!(- dispatch.cascade_order_for_entry(first_branch.rule, SelectorProgramID(2), first_branch.entry),- None- );- assert_eq!(- dispatch.cascade_order_for_entry(first_branch.rule, first_branch.program, 2),- None- );- assert_eq!(- dispatch.cascade_order_for_entry(RuleID(999), SelectorProgramID(999), 0),- None- );- }-- #[test]- fn shared_dispatch_allocations_are_charged_once() {- let mut dispatch = RuleDispatch::new();- dispatch.insert(- DispatchKey::Class(StyleAtomID(10)),- DispatchEntry {- identity: EntryID(1),- rule: RuleID(1),- program: SelectorProgramID(1),- entry: 0,- cascade_order: 0,- required_attribute_value: StyleAtomID::NONE,- required_parent: None,- required_ancestor: Some(DispatchKey::Class(StyleAtomID(20))),- required_ancestor_index: None,- required_subject_bloom: 0,- prefix_matched: false,- multi_key: false,- },- );-- let rebound = RuleDispatch::rebind_rules(&dispatch, &[RuleID(2)]);-- assert!(dispatch.shares_entries_with(&rebound));-- drop(dispatch);-- drop(rebound);- }-- #[test]- fn a_candidate_probes_only_the_buckets_its_own_facts_name() {- let mut dispatch = RuleDispatch::new();- let entry = |rule: u32| DispatchEntry {- identity: EntryID(rule),- rule: RuleID(rule),- program: SelectorProgramID(rule),- entry: 0,- cascade_order: 0,- required_attribute_value: StyleAtomID::NONE,- required_parent: None,- required_ancestor: None,- required_ancestor_index: None,- required_subject_bloom: 0,- prefix_matched: false,- multi_key: false,- };- dispatch.insert(DispatchKey::Class(StyleAtomID(10)), entry(1));- dispatch.insert(DispatchKey::Id(StyleAtomID(20)), entry(2));- dispatch.insert(DispatchKey::TagName(StyleAtomID(1)), entry(3));- dispatch.insert(DispatchKey::Universal, entry(4));- dispatch.insert(DispatchKey::Class(StyleAtomID(11)), entry(5));- dispatch.insert(DispatchKey::AttributeName(StyleAtomID(30)), entry(6));-- let mut facts = StyleNodeFacts::new();- facts.push_row(- StyleNodeID::element(1),- StyleAtomID(1),- StyleAtomID(20),- StateSet::default(),- &[StyleAtomID(10)],- &[AttributeFact {- name: StyleAtomID(30),- value: StyleAtomID::NONE,- }],- );-- let mut workspace = DispatchCandidateWorkspace::default();- let mut rules: Vec<u32> = dispatch- .candidates_for(- &facts,- 0,- false,- ParentDispatchFacts::Unknown,- None,- CandidateEntries::All,- false,- &mut workspace,- )- .map(|candidate| candidate.rule.0)- .collect();- rules.sort_unstable();- assert_eq!(rules, vec![1, 2, 3, 4, 6], "the .other-class bucket must not be probed");- }-- #[test]- fn attribute_aliases_emit_each_candidate_once_without_hiding_value_matches() {- let mut dispatch = RuleDispatch::new();- let entry = |rule: u32, required_attribute_value| DispatchEntry {- identity: EntryID(rule),- rule: RuleID(rule),- program: SelectorProgramID(rule),- entry: 0,- cascade_order: 0,- required_attribute_value,- required_parent: None,- required_ancestor: None,- required_ancestor_index: None,- required_subject_bloom: 0,- prefix_matched: false,- multi_key: false,- };- let shared_local_name = StyleAtomID(30);- let matching_value = StyleAtomID(40);- dispatch.insert(- DispatchKey::AttributeName(shared_local_name),- entry(1, StyleAtomID::NONE),- );- dispatch.insert(DispatchKey::AttributeName(shared_local_name), entry(2, matching_value));-- let mut facts = StyleNodeFacts::new();- facts.note_attribute_name_forms(- StyleAtomID(31),- AttributeNameForms {- local: shared_local_name,- ..AttributeNameForms::default()- },- );- facts.note_attribute_name_forms(- StyleAtomID(32),- AttributeNameForms {- local: shared_local_name,- ..AttributeNameForms::default()- },- );- facts.push_row(- StyleNodeID::element(1),- StyleAtomID(1),- StyleAtomID::NONE,- StateSet::default(),- &[],- &[- AttributeFact {- name: StyleAtomID(31),- value: StyleAtomID(41),- },- AttributeFact {- name: StyleAtomID(32),- value: matching_value,- },- ],- );-- let mut workspace = DispatchCandidateWorkspace::default();- for _ in 0..2 {- let rules: Vec<u32> = dispatch- .candidates_for(- &facts,- 0,- false,- ParentDispatchFacts::Unknown,- None,- CandidateEntries::All,- false,- &mut workspace,- )- .map(|candidate| candidate.rule.0)- .collect();- assert_eq!(rules, vec![1, 2]);- }- }-- #[test]- fn a_universal_subject_probes_only_the_bucket_its_parent_names() {- let mut dispatch = RuleDispatch::new();- let entry = |rule: u32, required_parent| DispatchEntry {- identity: EntryID(rule),- rule: RuleID(rule),- program: SelectorProgramID(rule),- entry: 0,- cascade_order: 0,- required_attribute_value: StyleAtomID::NONE,- required_parent,- required_ancestor: None,- required_ancestor_index: None,- required_subject_bloom: 0,- prefix_matched: false,- multi_key: false,- };- dispatch.insert(- DispatchKey::Universal,- entry(1, Some(DispatchKey::Class(StyleAtomID(10)))),- );- dispatch.insert(- DispatchKey::Universal,- entry(2, Some(DispatchKey::Class(StyleAtomID(11)))),- );- dispatch.insert(DispatchKey::Universal, entry(3, None));- dispatch.finish_prefixes(&mut Default::default());-- let mut facts = StyleNodeFacts::new();- facts.push_row(- StyleNodeID::element(1),- StyleAtomID(1),- StyleAtomID::NONE,- StateSet::default(),- &[StyleAtomID(10)],- &[],- );- facts.push_row(- StyleNodeID::element(2),- StyleAtomID(1),- StyleAtomID::NONE,- StateSet::default(),- &[],- &[],- );-- let mut workspace = DispatchCandidateWorkspace::default();- let mut rules = |dispatch: &RuleDispatch, parent| {- dispatch- .candidates_for(- &facts,- 1,- false,- parent,- None,- CandidateEntries::All,- false,- &mut workspace,- )- .map(|candidate| candidate.rule.0)- .collect::<Vec<_>>()- };- assert_eq!(- rules(- &dispatch,- ParentDispatchFacts::Known {- row: 0,- is_document_root: true,- }- ),- vec![3, 1]- );- assert_eq!(rules(&dispatch, ParentDispatchFacts::NoElementParent), vec![3]);- assert_eq!(rules(&dispatch, ParentDispatchFacts::Unknown), vec![3, 1, 2]);- }-- #[test]- fn a_local_subject_bucket_respects_its_parent_requirement() {- let mut dispatch = RuleDispatch::new();- let entry = |rule: u32, required_parent| DispatchEntry {- identity: EntryID(rule),- rule: RuleID(rule),- program: SelectorProgramID(rule),- entry: 0,- cascade_order: 0,- required_attribute_value: StyleAtomID::NONE,- required_parent,- required_ancestor: None,- required_ancestor_index: None,- required_subject_bloom: 0,- prefix_matched: false,- multi_key: false,- };- let item = StyleAtomID(20);- dispatch.insert(- DispatchKey::Class(item),- entry(1, Some(DispatchKey::Class(StyleAtomID(10)))),- );- dispatch.insert(- DispatchKey::Class(item),- entry(2, Some(DispatchKey::Class(StyleAtomID(11)))),- );- dispatch.insert(DispatchKey::Class(item), entry(3, None));-- let mut facts = StyleNodeFacts::new();- facts.push_row(- StyleNodeID::element(1),- StyleAtomID(1),- StyleAtomID::NONE,- StateSet::default(),- &[StyleAtomID(10)],- &[],- );- facts.push_row(- StyleNodeID::element(2),- StyleAtomID(1),- StyleAtomID::NONE,- StateSet::default(),- &[item],- &[],- );-- let mut workspace = DispatchCandidateWorkspace::default();- let mut rules = |dispatch: &RuleDispatch, parent| {- dispatch- .candidates_for(- &facts,- 1,- false,- parent,- None,- CandidateEntries::All,- false,- &mut workspace,- )- .map(|candidate| candidate.rule.0)- .collect::<Vec<_>>()- };- assert_eq!(- rules(- &dispatch,- ParentDispatchFacts::Known {- row: 0,- is_document_root: true,- }- ),- vec![1, 3]- );- assert_eq!(rules(&dispatch, ParentDispatchFacts::NoElementParent), vec![3]);- assert_eq!(rules(&dispatch, ParentDispatchFacts::Unknown), vec![1, 2, 3]);- }-- #[test]- fn rows_are_addressed_by_element_index() {- let mut facts = StyleNodeFacts::new();- let first = StyleNodeID::element(1);- let third = StyleNodeID::element(3);- facts.push_row(- first,- StyleAtomID(10),- StyleAtomID::NONE,- StateSet::default(),- &[StyleAtomID(20)],- &[],- );- facts.push_row(- third,- StyleAtomID(11),- StyleAtomID(30),- StateSet::default(),- &[StyleAtomID(21), StyleAtomID(22)],- &[],- );-- assert_eq!(facts.row_count(), 2);- let row = facts.row_of(third).unwrap();- assert_eq!(facts.node_at(row), third);- assert_eq!(facts.tag_of(row), StyleAtomID(11));- assert_eq!(facts.id_of(row), StyleAtomID(30));- assert_eq!(facts.classes_of(row), &[StyleAtomID(21), StyleAtomID(22)]);- assert_eq!(facts.classes_of(facts.row_of(first).unwrap()), &[StyleAtomID(20)]);-- // A node the batch does not cover is a miss, never a negative answer.- assert_eq!(facts.row_of(StyleNodeID::element(2)), None);- assert_eq!(facts.row_of(StyleNodeID::element(99)), None);- }-- #[test]- fn pending_attribute_exposes_both_transaction_sides() {- let mut tree = StyleNodeTree::new();- let node = tree.allocate_element();- let name = StyleAtomID(40);- let old = StyleAtomID(50);- let new = StyleAtomID(51);- let newest = StyleAtomID(52);- let old_text: Vec<u16> = "old".encode_utf16().collect();- let new_text: Vec<u16> = "new".encode_utf16().collect();- let newest_text: Vec<u16> = "newest".encode_utf16().collect();- let mut store = ElementFactStore::new();- store.set_attribute_value_text(old, &old_text);- store.set_attribute_value_text(new, &new_text);- store.set_attribute_value_text(newest, &newest_text);- store.set_attribute(node, name, old, true);- store.apply_staged();- store.release_staging();- store.set_attribute(node, name, new, true);- store.apply_staged();- store.set_attribute(node, name, newest, true);-- let before = store.staged_before_facts();- store.apply_staged();- let after = store.primary();- assert!(before.text.is_empty());- assert!(after.text.is_empty());-- let old_attribute = before.attribute_of(before.row_of(node).unwrap(), name).unwrap();- assert_eq!(old_attribute.value, old);- assert_eq!(before.text_of(old_attribute), Some(old_text.as_slice()));- let new_attribute = after.attribute_of(after.row_of(node).unwrap(), name).unwrap();- assert_eq!(new_attribute.value, newest);- assert_eq!(after.text_of(new_attribute), Some(newest_text.as_slice()));- }-- #[test]- fn reclaimed_atoms_leave_no_catalog_or_posting_rows_for_reuse() {- let mut store = ElementFactStore::new();- let atom = StyleAtomID(40);- store.note_attribute_name_forms(- atom,- AttributeNameForms {- local: StyleAtomID(41),- folded_name: StyleAtomID(42),- folded_local: StyleAtomID(43),- },- );- store.note_attribute_substitution_name(atom, &[11, 12]);- store.set_attribute_value_text(atom, &[1, 2, 3]);- store.set_language_text(atom, &[4, 5, 6]);- store- .postings- .insert(SelectorPostingKey::Class(atom), StyleNodeID::element(1));-- store.forget_atoms(&[atom, StyleAtomID(42)]);-- assert_eq!(store.attribute_name_forms(atom), AttributeNameForms::default());- assert_eq!(store.attribute_substitution_name(atom), None);- assert!(!store.has_attribute_value_text(atom));- assert_eq!(- store.attribute_catalogs.language_texts.get(atom.0 as usize),- Some(&None)- );- assert!(matches!(- store.postings.lookup(SelectorPostingKey::Class(atom)),- Lookup::KnownAbsent- ));-- store.note_attribute_name_forms(- atom,- AttributeNameForms {- local: StyleAtomID(60),- ..AttributeNameForms::default()- },- );- store.set_attribute_value_text(atom, &[7, 8]);- store.set_language_text(atom, &[9, 10]);- assert_eq!(store.attribute_name_forms(atom).local, StyleAtomID(60));- assert_eq!(- store- .attribute_catalogs- .value_texts- .get(atom.0 as usize)- .and_then(Option::as_deref),- Some([7, 8].as_slice())- );- assert_eq!(- store- .attribute_catalogs- .language_texts- .get(atom.0 as usize)- .and_then(Option::as_deref),- Some([9, 10].as_slice())- );- }-- #[test]- fn live_attribute_names_keep_their_derived_forms_live() {- let mut store = ElementFactStore::new();- let name = StyleAtomID(40);- let forms = AttributeNameForms {- local: StyleAtomID(41),- folded_name: StyleAtomID(42),- folded_local: StyleAtomID(43),- };- store.note_attribute_name_forms(name, forms);- let mut live = HashSet::default();- live.insert(name);-- store.extend_live_attribute_name_forms(&mut live);-- assert_eq!(live.len(), 4);- assert!(- [name, forms.local, forms.folded_name, forms.folded_local]- .into_iter()- .all(|atom| live.contains(&atom))- );- }-- #[test]- fn a_primary_fact_view_is_immutable_and_uncharged() {- let mut tree = StyleNodeTree::new();- let node = tree.allocate_element();- let mut store = ElementFactStore::new();- store.set_tag(node, StyleAtomID(1));- store.apply_staged();- store.release_staging();-- let view = store.primary_view();- store.set_tag(node, StyleAtomID(2));- assert_eq!(view.tag_of(view.row_of(node).unwrap()), StyleAtomID(1));- store.apply_staged();- assert_eq!(view.tag_of(view.row_of(node).unwrap()), StyleAtomID(1));- assert_eq!(store.tag_of_node(node), StyleAtomID(2));- }-- #[test]- fn catalog_publication_does_not_copy_primary_fact_rows() {- let mut store = ElementFactStore::new();- let node = StyleNodeID::element(1);- let name = StyleAtomID(20);- let forms = AttributeNameForms {- local: StyleAtomID(21),- folded_name: StyleAtomID(22),- folded_local: StyleAtomID(23),- };- store.ensure_row(node);- store.apply_staged();- store.release_staging();-- let primary_rows = Arc::as_ptr(&store.rows);- let view = store.primary_view();- store.note_attribute_name_forms(name, forms);- assert_eq!(Arc::as_ptr(&store.rows), primary_rows);- assert_eq!(store.attribute_name_forms(name), forms);- assert_eq!(- view.attribute_name_forms(name),- AttributeNameForms {- folded_name: name,- ..AttributeNameForms::default()- }- );-- drop(view);- store.apply_staged();- assert_eq!(Arc::as_ptr(&store.rows), primary_rows);- assert_eq!(store.primary().attribute_name_forms(name), forms);- }-- #[test]- fn catalog_synchronization_preserves_a_retained_primary_fact_view() {- let mut store = ElementFactStore::new();- let node = StyleNodeID::element(1);- let name = StyleAtomID(20);- let forms = AttributeNameForms {- local: StyleAtomID(21),- folded_name: StyleAtomID(22),- folded_local: StyleAtomID(23),- };- store.ensure_row(node);- store.apply_staged();- store.release_staging();-- let view = store.primary_view();- store.note_attribute_name_forms(name, forms);- store.set_tag(node, StyleAtomID(1));-- let before = store.staged_before_facts();- store.apply_staged();-- assert_eq!(before.attribute_name_forms(name), forms);- assert_eq!(store.primary().attribute_name_forms(name), forms);- assert_eq!(- view.attribute_name_forms(name),- AttributeNameForms {- folded_name: name,- ..AttributeNameForms::default()- }- );- }-- #[test]- fn repeated_catalog_publication_copies_the_catalog_at_most_once() {- let mut store = ElementFactStore::new();-- for raw in 1..=128 {- let atom = StyleAtomID(raw);- store.set_attribute_value_text(atom, &[raw as u16]);- }-- assert_eq!(store.attribute_catalog_copies(), 1);- }-- #[test]- fn distant_process_atom_ids_allocate_only_touched_catalog_pages() {- let mut store = ElementFactStore::new();- let atom = StyleAtomID(1_000_000);- store.note_attribute_name_forms(atom, AttributeNameForms::default());- store.set_attribute_value_text(atom, &[1, 2, 3]);- store.set_language_text(atom, &[4, 5, 6]);- ElementFactStore::increment_atom_count(&mut store.atom_live_counts, atom);- store.custom_property_set_ids_by_name.entry(atom.0 as usize).push(1);-- assert_eq!(store.attribute_catalogs.name_forms.values.page_count(), 1);- assert_eq!(store.attribute_catalogs.value_texts.handles.page_count(), 1);- assert_eq!(store.attribute_catalogs.language_texts.handles.page_count(), 1);- assert_eq!(store.atom_live_counts.values.page_count(), 1);- assert_eq!(store.custom_property_set_ids_by_name.handles.page_count(), 1);- assert_eq!(size_of_val(&store.atom_live_counts.get(atom.0 as usize).unwrap()), 4);-- let mut directory = SegmentedDispatchBucketDirectory::default();- directory.insert(atom.0 as usize, DispatchBucketRange { start: 1, length: 1 });- assert_eq!(directory.ranges.values.page_count(), 1);- }-- #[test]- fn staged_fact_rows_use_paged_element_identity_slots() {- let first = StyleNodeID::element(1);- let distant = StyleNodeID::element(64);- let mut rows = FactStaging::default();- let before = StagedFactRow {- tag: StyleAtomID(1),- ..Default::default()- };- let after = StagedFactRow {- tag: StyleAtomID(2),- ..Default::default()- };-- rows.insert(distant, before, None);- rows.insert(first, StagedFactRow::default(), None);- rows.insert(distant, after, None);-- assert!(rows.has_dirty());- assert_eq!(rows.rows.page_count(), 2);- assert_eq!(rows.entries.len(), 2);- assert_eq!(rows.keys().collect::<Vec<_>>(), vec![distant, first]);- assert_eq!(rows.len(), 2);- assert_eq!(rows.get(distant).unwrap().tag, StyleAtomID(2));- rows.mark_applied();- assert!(!rows.has_dirty());- rows.edit(first, |row| row.tag = StyleAtomID(3)).unwrap();- assert!(rows.has_dirty());- rows.remove(distant);- assert!(rows.has_dirty());- assert_eq!(rows.keys().collect::<Vec<_>>(), vec![first]);- rows.remove(first);- assert!(!rows.has_dirty());- rows.insert(first, StagedFactRow::default(), None);- assert_eq!(rows.keys().collect::<Vec<_>>(), vec![first]);- assert_eq!(rows.dirty_rows().count(), 1);-- let directory_capacity = rows.rows.directory_capacity();- let entry_capacity = rows.entries.capacity();- rows.clear();- assert!(rows.is_empty());- assert_eq!(rows.rows.page_count(), 2);- assert_eq!(rows.rows.directory_capacity(), directory_capacity);- assert_eq!(rows.entries.capacity(), entry_capacity);- }-- #[test]- fn staged_fact_rows_release_oversized_entry_arenas() {- let mut rows = FactStaging::default();- for index in 1..=1024 {- rows.insert(StyleNodeID::element(index), StagedFactRow::default(), None);- }- rows.clear();- let peak_capacity = rows.entries.capacity();-- rows.insert(StyleNodeID::element(1), StagedFactRow::default(), None);- rows.clear();-- assert!(rows.entries.capacity() < peak_capacity);- }-- #[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);- }-- #[test]- fn clearing_keeps_the_arena_for_the_next_transaction() {- let mut facts = StyleNodeFacts::new();- for index in 1..200_u32 {- facts.push_row(- StyleNodeID::element(index),- StyleAtomID(1),- StyleAtomID::NONE,- StateSet::default(),- &[StyleAtomID(2)],- &[],- );- }-- facts.clear();- assert_eq!(facts.row_count(), 0);- assert_eq!(facts.row_of(StyleNodeID::element(5)), None);- }-}+pub use super::facts_types::AttributeFact;+pub use super::facts_types::AttributeNameForms;+pub use super::facts_types::DispatchKey;+pub use super::facts_types::FeatureValue;+pub use super::facts_types::LocalFeatureKey;+pub use super::facts_types::StateSet;+pub use super::facts_types::StyleAtomID;+pub use super::facts_types::dispatch_bloom_bit;diff --git a/Libraries/LibWeb/Rust/src/css/style/matching.rs b/Libraries/LibWeb/Rust/src/css/style/matching.rsdeleted file mode 100644index 611860c40c2..00000000000--- a/Libraries/LibWeb/Rust/src/css/style/matching.rs+++ /dev/null@@ -1,5059 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--use smallvec::SmallVec;-use std::sync::{Mutex, MutexGuard, OnceLock};--use super::batch_matcher::{append_selector_truth_matches, insert_scope_rule};-use super::cascade::CascadeContinuationID;-use super::prefix::{PrefixTransitionContext, PrefixTransitionContexts};-use super::*;--const MIN_SHARED_CASCADE_COMPLETION_DECLARATIONS: usize = 8;--#[derive(PartialEq, Eq, Hash)]-struct SharedDispatchKey(Vec<SharedDispatchProgram>);--#[derive(PartialEq, Eq, Hash)]-struct SharedDispatchProgram {- program: SelectorProgramID,- identity: selector::SharedSelectorIdentity,- entries: selector::SelectorEntryIDs,- author: bool,-}--impl SharedDispatchKey {- fn new(shape: &ScopeDispatchShape, programs: &selector::SelectorPrograms) -> Option<Self> {- if shape.0.is_empty() {- return None;- }- shape- .0- .iter()- .map(|&(program, author)| {- let (identity, entries) = programs.shared_dispatch_identity(program)?;- Some(SharedDispatchProgram {- program,- identity,- entries,- author,- })- })- .collect::<Option<Vec<_>>>()- .map(Self)- }-}--#[derive(Default)]-struct SharedDispatches {- templates: HashMap<SharedDispatchKey, index::WeakRuleDispatch>,-}--/// The interning pools of selector dispatches, shared by every engine in the process.-#[derive(Default)]-struct DispatchPools {- dispatches: SharedDispatches,- scope_shapes: catalog::ScopeShapePools,- storage: index::DispatchStoragePools,-}--fn dispatch_pools() -> MutexGuard<'static, DispatchPools> {- // Every engine interns through the same pools, from whichever thread runs it. Values never- // reach back into a pool when they are dropped, so the lock is only held while interning.- static DISPATCH_POOLS: OnceLock<Mutex<DispatchPools>> = OnceLock::new();- DISPATCH_POOLS.get_or_init(Mutex::default).lock().unwrap()-}--fn verify_match_answer_against_cold(- engine: &mut RetainedState,- answer: &[RuleMatch],- node: StyleNodeID,- description: &str,-) {- verify_style_answer_patch(engine, |verifier| {- verifier.verify_match_answer(answer, node, description);- });-}--impl RetainedState {- fn retained_answer_delta_memo_key(- old_answer: MatchAnswerID,- old_cascade_input: MatchAnswerID,- deltas: &[SelectorTruthDelta],- ) -> RetainedAnswerDeltaMemoKey {- let mut hasher = fast_hash::fast_hasher();- for delta in deltas {- (delta.rule, delta.entry, delta.change).hash(&mut hasher);- }- RetainedAnswerDeltaMemoKey {- old_answer,- old_cascade_input,- delta_count: deltas.len(),- delta_digest: hasher.finish(),- }- }-- fn retained_answer_delta_memo_entry_matches(- entry: &RetainedAnswerDeltaMemoEntry,- deltas: &[SelectorTruthDelta],- ) -> bool {- entry- .deltas- .iter()- .copied()- .eq(deltas.iter().map(|delta| (delta.rule, delta.entry, delta.change)))- }-- /// The pseudo-element winner states a node settled this flush for the kinds the engine- /// settles pseudo-elements from, to travel with the node's winner state: ::before, ::after,- /// ::first-letter, ::marker, both ::search-text kinds, ::selection and ::backdrop. The user agent's rules- /// for ::marker and ::backdrop match every element, and a row for each of them on every element- /// would cost the memory the winner groups have, so those travel only from a node holding a- /// record for that pseudo-element: a list item's marker, or a backdrop in the top layer.- fn settled_pseudo_winner_states(- &self,- effects: &AnswerEffects,- node: StyleNodeID,- ) -> Vec<(tree::PseudoElementTarget, CascadeStateID)> {- effects- .winners- .view(&self.winner_groups)- .pseudo_states(node)- .filter(|&(pseudo, version, _, priority_current)| {- let travels = match pseudo.kind.0 {- 0 | 2 | 3 | 6 | 7 | 8 => true,- kind @ (1 | 5) => self.computed_group_sets.pseudo_style_record(node, kind as u8).is_some(),- _ => false,- };- travels && version == self.program.version() && priority_current- })- .map(|(pseudo, _, state, _)| (pseudo, state))- .collect()- }-- fn remember_retained_answer_delta_transition(- patch: &mut RetainedAnswerPatch,- key: RetainedAnswerDeltaMemoKey,- deltas: &[SelectorTruthDelta],- transition: RetainedAnswerDeltaTransition,- ) {- use std::collections::hash_map::Entry;-- match patch.delta_memo.entry(key) {- Entry::Vacant(entry) => {- entry.insert(RetainedAnswerDeltaMemoEntry {- deltas: deltas- .iter()- .map(|delta| (delta.rule, delta.entry, delta.change))- .collect(),- transition,- });- }- Entry::Occupied(mut entry) if Self::retained_answer_delta_memo_entry_matches(entry.get(), deltas) => {- entry.get_mut().transition = transition;- }- // A digest collision only forfeits this memo opportunity. It must not replace or use- // the unrelated transition already stored under the fixed-size probe key.- Entry::Occupied(_) => {}- }- }-- pub(super) fn materialize_cold_matching_batch(- &mut self,- root: StyleNodeID,- topology: Option<&TransactionTopology>,- ) -> Option<MatchingFactBatch> {- let fallback_nodes;- let nodes = if let Some(topology) = topology- && topology.nodes().len() == self.tree.connected_element_count() as usize- {- topology.nodes()- } else {- fallback_nodes = self.elements_under(root);- &fallback_nodes- };- let mut batch = StyleNodeFacts::new();- self.facts.materialize(nodes.iter().copied(), &mut batch);- let mut expected_row_count = nodes.len();- for scope_root in self.scope_roots.iter().flatten().copied() {- if self.tree.is_live(scope_root) && batch.row_of(scope_root).is_none() {- self.facts.materialize_missing(std::iter::once(scope_root), &mut batch);- expected_row_count += 1;- }- }- if batch.row_count() != expected_row_count {- self.counters.bump(Counter::ColdMatchingBatchMissingRows);- return None;- }-- self.counters.add(- Counter::ColdMatchingBatchRows,- u64::try_from(batch.row_count()).unwrap_or(u64::MAX),- );- Some(batch.into())- }-- pub(super) fn discard_prepared_batch_matching_traversal(&mut self) {- self.prepared_batch_matching_traversal = None;- }-- /// Finish the previous host context before input handoff can discard its- /// publication or reset the arenas referenced by its private scratch.- pub(super) fn install_pending_matching_context(&mut self) {- if let Some(mut traversal) = self.batch_matching_traversal.take() {- self.published_match_answers- .append_pending(std::mem::take(&mut traversal.pending_published));- self.install_answer_effects(std::mem::take(&mut traversal.answer_effects));- // NB: The next transaction may reset prefix arenas. Complete the old- // context before committing its inputs, including private transition IDs.- let mut prefix_contexts = std::mem::take(&mut traversal.prefix_contexts);- prefix_contexts.install(&mut self.prefix_caches.borrow_mut().states);- self.batch_matching_traversal = Some(traversal);- }- }-- pub(super) fn discard_published_match_answers(&mut self) {- if let Some(traversal) = self.batch_matching_traversal.as_mut() {- let effects = std::mem::take(&mut traversal.answer_effects);- effects.release_pending_all(&mut self.match_answers, &mut self.winner_groups);- traversal.pending_published.clear();- }- let mut published = std::mem::take(&mut self.published_match_answers);- let effects = std::mem::take(&mut published.answer_effects);- effects.release_pending_all(&mut self.match_answers, &mut self.winner_groups);- verify_published_style_transaction(self, |_| {- assert!(- published.entries.is_empty()- || self- .counters- .get(Counter::MatchElementCallsDuringPublishedStyleTransaction)- == published.match_element_calls_at_publication,- "a style transaction called match_element() after publishing complete match answers"- );- });- published.release();- }-- /// A demand matches its node again from current facts: the answer an earlier batch published- /// for it must not answer it, while the other nodes' answers stay for their own readers.- pub(super) fn forget_node_match_answer_for_demand(&mut self, node: StyleNodeID) {- self.install_pending_matching_context();- let effects = std::mem::take(&mut self.published_match_answers.answer_effects);- self.install_answer_effects(effects);- self.published_match_answers- .entries- .retain(|answer| answer.node != node);-- self.retained_match_answers.forget(&mut self.match_answers, node);- }-- /// Drop the traversal a private demand matched in, with everything it would have published:- /// its answers, the winners they wrote and the prefix states it extended.- pub(super) fn discard_private_record_demand_matching_batch(&mut self) {- let Some(mut traversal) = self.batch_matching_traversal.take() else {- return;- };- std::mem::take(&mut traversal.answer_effects)- .release_pending_all(&mut self.match_answers, &mut self.winner_groups);- std::mem::take(&mut traversal.pending_published).release();- self.release_traversal_scratch(*traversal);- let mut caches = self.prefix_caches.borrow_mut();- caches.states.release();- caches.answers.release(&mut self.match_answers);- }-- /// Retire the traversal the host keeps open across a pass of style reactions, once a- /// transaction taken during that pass changed the facts its batch was read from. What it- /// published is installed, as at any transaction boundary, and only its scratch is dropped.- pub(super) fn retire_batch_matching_traversal(&mut self) {- self.install_pending_matching_context();- if let Some(traversal) = self.batch_matching_traversal.take() {- self.release_traversal_scratch(*traversal);- }- }-- fn release_traversal_scratch(&mut self, mut traversal: BatchMatchingTraversal) {- traversal.ancestor_requirements.release();- }-- pub(super) fn discard_retained_prefix_caches(&mut self) {- let mut caches = self.prefix_caches.borrow_mut();- caches.states.release();- caches.answers.release(&mut self.match_answers);- }-- pub(super) fn retain_prefix_states(&mut self) {- self.prefix_caches.borrow_mut().states.retain();- }-- pub(super) fn take_prepared_batch_matching_traversal(- &mut self,- root: StyleNodeID,- ) -> Option<PreparedBatchMatchingTraversal> {- let prepared = self.prepared_batch_matching_traversal.take()?;- if prepared.root == root {- return Some(prepared);- }-- None- }-- pub(super) fn retained_answer_dispatch_for_traversal(- &mut self,- reuse_retained_match_answers: bool,- ) -> Option<Arc<RuleDispatch>> {- reuse_retained_match_answers.then(|| self.prepare_scope_program(TreeScopeID::DOCUMENT).1)- }-- /// Share current facts and selector work while a scoped plan completes typed answer misses.- ///- /// Retained prefix caches describe the previous transaction, so this batch deliberately starts- /// empty and is released before publication. Repeated local asks may still promote to one- /// complete current fact batch after their accumulated reconstruction cost justifies it.- pub(super) fn begin_published_match_answer_completion_batch(- &mut self,- root: StyleNodeID,- prefer_complete_batch: bool,- ) {- debug_assert!(self.batch_matching_traversal.is_none());- let materialize_timer = flush::PassTimer::start();- let batch = prefer_complete_batch- .then(|| {- self.prepared_batch_matching_traversal- .as_mut()- .and_then(|prepared| prepared.batch.take())- .or_else(|| self.materialize_cold_matching_batch(root, None))- })- .flatten();- let ancestor_requirements = batch- .as_ref()- .map(|facts| self.prepare_matching_batch(facts))- .unwrap_or_default();- let relation_dispatch = batch- .as_ref()- .map(|_| self.prepare_scope_program(TreeScopeID::DOCUMENT));- materialize_timer.stop(Counter::CompletionBatchMaterializeMicroseconds, &self.counters);- let relation_timer = flush::PassTimer::start();- // The walk that just converged left the retained states describing THIS transaction,- // so the completion batch can extend the warm automaton instead of re-deriving every- // upquery spine. Without a current walk the retained states describe the previous- // transaction and the batch starts empty as before.- {- let mut caches = self.prefix_caches.borrow_mut();- if !caches.states.is_current() {- caches.states.release();- caches.answers.release(&mut self.match_answers);- }- caches.states.make_scratch();- caches.answers.make_scratch();- if let Some((program, dispatch)) = relation_dispatch- && let Some(facts) = batch.as_ref()- && (matches!(caches.states.lookup(program), Lookup::Known(states) if states.relation.is_some())- || dispatch.prefixes().supports_relation(&self.tree, root))- {- let states = caches.states.prepare_program(program);- let mut relation = states.relation.take().unwrap_or_else(|| {- let mut workspace = MatchScratch::default();- let mut evaluator = MatchEvaluator::new(&self.tree, facts)- .with_match_workspace(&mut workspace, selector::MatchEvaluationSide::Current);- let mut evaluation = PrefixEvaluation::new(- dispatch.prefixes(),- &self.tree,- facts,- &self.programs,- &mut evaluator,- None,- None,- );- Box::new(- dispatch- .prefixes()- .build_relation(&mut evaluation, root, &self.counters),- )- });- relation.install_answers(states);- states.relation = Some(relation);- }- }- let mut prefix_contexts = PrefixTransitionContexts::default();- if let Some(facts) = batch.as_ref() {- self.prepare_prefix_rows_for_batch(facts, &mut prefix_contexts);- }- relation_timer.stop(Counter::CompletionBatchRelationMicroseconds, &self.counters);- self.batch_matching_traversal = Some(Box::new(BatchMatchingTraversal {- pending_published: PublishedMatchAnswers::default(),- answer_effects: AnswerEffects::default(),- prefix_contexts,- root,- batch,- topology: None,- retained_answer_dispatch: None,- ancestor_requirements,- prefix_caches: std::sync::Arc::clone(&self.prefix_caches),- match_workspace: MatchScratch::default(),- dispatch_workspace: DispatchCandidateWorkspace::default(),- cascade_compaction_workspace: ordering::CascadeCompactionWorkspace::default(),-- unbatched_facts: StyleNodeFacts::new(),- }));- }-- pub(super) fn end_published_match_answer_completion_batch(&mut self) {- let Some(mut traversal) = self.batch_matching_traversal.take() else {- return;- };- self.published_match_answers- .append_pending(std::mem::take(&mut traversal.pending_published));- self.install_answer_effects(std::mem::take(&mut traversal.answer_effects));- traversal- .prefix_contexts- .install(&mut self.prefix_caches.borrow_mut().states);- traversal.ancestor_requirements.release();- // The batch extended states describing this transaction's facts, so retain their shared- // owner instead of discarding them: the next flush's walk completes over- // warm spines. The sparse origin flag keeps that walk from letting the cache speak for- // nodes the batch never visited.- {- let mut caches = self.prefix_caches.borrow_mut();- caches.states.mark_sparse();- caches.states.retain();- caches.states.mark_current();- caches.answers.retain();- }-- self.forget_custom_property_environments_by_answer();- self.match_answers.sweep_unreferenced();- self.match_answers.compact_if_needed();- if let Some(batch) = traversal.batch.take() {- match &mut self.prepared_batch_matching_traversal {- Some(prepared) if prepared.batch.is_none() => prepared.batch = Some(batch),- None => {- let mut prepared = PreparedBatchMatchingTraversal::new(traversal.root);- prepared.batch = Some(batch);- self.prepared_batch_matching_traversal = Some(prepared);- }- Some(_) => {}- }- }- }-- pub(super) fn traversal_with_cold_matching_batch(- &mut self,- root: StyleNodeID,- batch: MatchingFactBatch,- topology: Option<TransactionTopology>,- reuse_retained_match_answers: bool,- match_workspace: MatchScratch,- ) -> Box<BatchMatchingTraversal> {- let ancestor_requirements = self.prepare_matching_batch(&batch);-- {- let mut caches = self.prefix_caches.borrow_mut();- caches.states.make_scratch();- caches.answers.make_scratch();- }- let mut prefix_contexts = PrefixTransitionContexts::default();- self.prepare_prefix_rows_for_batch(&batch, &mut prefix_contexts);- let retained_answer_dispatch = self.retained_answer_dispatch_for_traversal(reuse_retained_match_answers);- Box::new(BatchMatchingTraversal {- pending_published: PublishedMatchAnswers::default(),- answer_effects: AnswerEffects::default(),- prefix_contexts,- root,- batch: Some(batch),- topology,- retained_answer_dispatch,- ancestor_requirements,- prefix_caches: std::sync::Arc::clone(&self.prefix_caches),- match_workspace,- dispatch_workspace: DispatchCandidateWorkspace::default(),- cascade_compaction_workspace: ordering::CascadeCompactionWorkspace::default(),-- unbatched_facts: StyleNodeFacts::new(),- })- }-- /// Materialize the document's facts once for a synchronous broad style traversal.- ///- /// The caller brackets one traversal explicitly, so engine mutations cannot leave a retained- /// answer stale. If the batch cannot be materialized, let each element use the ordinary exact- /// batch path.- pub fn begin_cold_matching_batch(&mut self, root: StyleNodeID) -> bool {- self.end_cold_matching_batch();-- let mut prepared = self.take_prepared_batch_matching_traversal(root);- let Some(batch) = prepared- .as_mut()- .and_then(|prepared| prepared.batch.take())- .or_else(|| {- self.materialize_cold_matching_batch(- root,- prepared.as_ref().and_then(|prepared| prepared.topology.as_ref()),- )- })- else {- return false;- };- let (topology, reuse_retained_match_answers, match_workspace) = prepared.map_or_else(- || (None, false, MatchScratch::default()),- |prepared| {- (- prepared.topology,- prepared.reuse_retained_match_answers,- prepared.match_workspace,- )- },- );- self.batch_matching_traversal = Some(self.traversal_with_cold_matching_batch(- root,- batch,- topology,- reuse_retained_match_answers,- match_workspace,- ));- true- }-- /// Begin a synchronous selective traversal without paying for broad facts up front.- ///- /// Local asks remain local instead of paying for broad facts up front.- pub fn begin_adaptive_cold_matching_batch(&mut self, root: StyleNodeID) {- self.end_cold_matching_batch();- let mut prepared = self.take_prepared_batch_matching_traversal(root);- if let Some(batch) = prepared.as_mut().and_then(|prepared| prepared.batch.take()) {- let prepared = prepared.unwrap();- self.batch_matching_traversal = Some(self.traversal_with_cold_matching_batch(- root,- batch,- prepared.topology,- prepared.reuse_retained_match_answers,- prepared.match_workspace,- ));- return;- }- let (topology, reuse_retained_match_answers, match_workspace) = prepared.map_or_else(- || (None, false, MatchScratch::default()),- |prepared| {- (- prepared.topology,- prepared.reuse_retained_match_answers,- prepared.match_workspace,- )- },- );-- {- let mut caches = self.prefix_caches.borrow_mut();- caches.states.make_scratch();- caches.answers.make_scratch();- }- let retained_answer_dispatch = self.retained_answer_dispatch_for_traversal(reuse_retained_match_answers);- self.batch_matching_traversal = Some(Box::new(BatchMatchingTraversal {- pending_published: PublishedMatchAnswers::default(),- answer_effects: AnswerEffects::default(),- prefix_contexts: PrefixTransitionContexts::default(),- root,- batch: None,- topology,- retained_answer_dispatch,- ancestor_requirements: AncestorRequirementsCache::default(),- prefix_caches: std::sync::Arc::clone(&self.prefix_caches),- match_workspace,- dispatch_workspace: DispatchCandidateWorkspace::default(),- cascade_compaction_workspace: ordering::CascadeCompactionWorkspace::default(),-- unbatched_facts: StyleNodeFacts::new(),- }));- }-- pub fn end_cold_matching_batch(&mut self) {- if let Some(mut traversal) = self.batch_matching_traversal.take() {- if let Some(batch) = &traversal.batch- && self.tree.tree_scope(traversal.root) == TreeScopeID::DOCUMENT- && self.tree.parent(traversal.root).is_none()- {- let (scope_program, dispatch) = self.prepare_scope_program(TreeScopeID::DOCUMENT);- if !dispatch.prefixes().is_empty() {- let mut evaluator = MatchEvaluator::new(&self.tree, batch);- let mut evaluation = PrefixEvaluation::new(- dispatch.prefixes(),- &self.tree,- batch,- &self.programs,- &mut evaluator,- None,- None,- );- let prefix_caches = std::sync::Arc::clone(&self.prefix_caches);- let mut caches = prefix_caches.borrow_mut();- caches.states.make_scratch();- let states = caches.states.prepare_program(scope_program);-- #[cfg(test)]- let force_bounded = self.force_bounded_prefix_completion;- #[cfg(not(test))]- let force_bounded = false;- let completion_budget = match !force_bounded && dispatch.prefixes().has_sibling_steps() {- true => usize::MAX,- false => PREFIX_TRANSITION_CACHE_COMPLETION_BUDGET,- };- traversal.prefix_contexts.prepare(scope_program, states, batch);- let prefix_context = traversal.prefix_contexts.get_mut(scope_program);- if let Some(topology) = &traversal.topology {- states.complete_nodes_with_budget(- &mut prefix_context.scratch,- &mut prefix_context.effects,- &mut evaluation,- topology- .nodes()- .iter()- .copied()- .filter(|&node| self.tree.tree_scope(node) == TreeScopeID::DOCUMENT),- completion_budget,- &self.counters,- );- } else {- states.complete_nodes_with_budget(- &mut prefix_context.scratch,- &mut prefix_context.effects,- &mut evaluation,- self.tree- .preorder(traversal.root)- .filter(|&node| self.tree.tree_scope(node) == TreeScopeID::DOCUMENT),- completion_budget,- &self.counters,- );- }-- let _ = states;- }- }- self.published_match_answers- .append_pending(std::mem::take(&mut traversal.pending_published));- self.install_answer_effects(std::mem::take(&mut traversal.answer_effects));- traversal- .prefix_contexts- .install(&mut self.prefix_caches.borrow_mut().states);- self.retain_prefix_states();- let mut caches = self.prefix_caches.borrow_mut();- caches.states.mark_full();- caches.answers.retain();- drop(caches);- self.forget_custom_property_environments_by_answer();- self.match_answers.sweep_unreferenced();- self.match_answers.compact_if_needed();- traversal.ancestor_requirements.release();-- self.discard_published_match_answers();- self.install_witness_effects();- }- }-- /// Every element the document holds, shadow trees included, in tree order per tree.- ///- /// A host's shadow tree is not below it in the style tree, so a preorder from the document- /// element does not reach it. Each tree is walked from its own root. A shadow root is a parent- /// in the style tree without being an element, so it is not one of the nodes: it holds no facts- /// and nothing decides anything for it.- #[must_use]- pub(super) fn elements_under(&self, root: StyleNodeID) -> Vec<StyleNodeID> {- let mut nodes: Vec<StyleNodeID> = Vec::new();- let mut roots = SmallVec::from_buf([root]);- while let Some(next) = roots.pop() {- for node in self.tree.preorder(next) {- if self.tree.host_of(node).is_none() {- nodes.push(node);- }- if let Some(shadow_root) = self.tree.shadow_root_of(node) {- roots.push(shadow_root);- }- }- }- nodes- }-- /// Every element under `root` that is not inside one of the named subtrees.- ///- /// Program changes arriving with a new subtree need to inspect only the old resident tree.- /// Walking every new descendant and then asking its ancestors whether it belongs to that- /// subtree makes initial style proportional to the content already covered by the plan.- #[must_use]- pub(super) fn elements_under_excluding_subtrees(- &self,- root: StyleNodeID,- excluded_roots: &[StyleNodeID],- ) -> Vec<StyleNodeID> {- let mut nodes = Vec::new();- let mut pending = vec![root];- while let Some(node) = pending.pop() {- if excluded_roots.binary_search(&node).is_ok() {- continue;- }- if self.tree.host_of(node).is_none() {- nodes.push(node);- }- pending.extend(self.tree.children(node));- if let Some(shadow_root) = self.tree.shadow_root_of(node) {- pending.push(shadow_root);- }- }- nodes- }-- /// Every scope a `::part()` rule can address this element from, nearest host first.- ///- /// One per level of `exportparts` forwarding: the tree each forwarding host stands in holds- /// rules that can name the element under the name that host exposed it by. Duplicates are- /// dropped because two levels can stand in one tree.- pub(super) fn part_exposure_scopes(&self, node: StyleNodeID) -> impl Iterator<Item = TreeScopeID> + '_ {- let mut seen: Vec<TreeScopeID> = Vec::new();- self.tree- .part_hosts_of(node)- .iter()- .map(|&(_, host)| self.tree.tree_scope(host))- .filter(move |scope| match seen.contains(scope) {- true => false,- false => {- seen.push(*scope);- true- }- })- }-- /// Build one scope's selector dispatch and rank its static cascade priorities once.- pub(super) fn build_ranked_scope_dispatch(- &mut self,- scope: TreeScopeID,- ) -> (Arc<RuleDispatch>, ScopeTemplateShapes) {- let (mut shape, mut rules) = scope_dispatch_shape_and_rules(&self.program, &self.programs, scope);- let document_sheet_mode = if scope == TreeScopeID::DOCUMENT {- DocumentSheetMode::None- } else if self.program.scope_uses_document_sheets(scope) {- DocumentSheetMode::All- } else {- DocumentSheetMode::NonAuthor- };- let mut cascade_shape = ScopeCascadeShape {- dispatch: shape.clone(),- depth: self.tree_scope_depth(scope),- document_sheet_mode,- rule_origins_and_layers: rules- .iter()- .map(|&rule| {- let sheet = self.program.rule_sheet(rule);- (- self.program.sheet_origin(sheet) as u8,- self.program.rule_version(rule).layer,- )- })- .collect(),- layer_order: self.program.layer_order_key(scope),- };- cascade_shape.share(&mut dispatch_pools().scope_shapes);- // Preserve source ordering in the cascade key, while equivalent selector multisets- // share matching topology regardless of stylesheet order.- super::batch_matcher::canonicalize_scope_dispatch(&mut shape, &mut rules, &self.programs);- shape.share(&mut dispatch_pools().scope_shapes);- let cascade_template = self.scope_cascade_templates.get(&cascade_shape).cloned();- // Document-local selector and entry numbers are embedded in the topology. Share only- // when those numbers AND their interned semantic payloads agree. Rule bindings,- // cascade ranks, and every element-dependent result are rebuilt for this document.- let shared_key = SharedDispatchKey::new(&shape, &self.programs);- let exact_template = self.scope_dispatch_templates.get(&shape).cloned().or_else(|| {- let key = shared_key.as_ref()?;- let mut pools = dispatch_pools();- let shared = &mut pools.dispatches;- shared.templates.retain(|_, template| template.is_alive());- shared- .templates- .get(key)- .and_then(index::WeakRuleDispatch::upgrade)- .map(Arc::new)- });- let extension_template = exact_template.is_none().then(|| {- // Extending a template copies its topology first. Require the retained prefix to cover- // at least half the resulting entries so copying cannot dominate a small cold build.- self.scope_dispatch_templates- .iter()- .filter(|(candidate, _)| {- !candidate.0.is_empty() && candidate.0.len() < shape.0.len() && shape.0.starts_with(&candidate.0)- })- .filter(|(_, template)| template.entry_count() >= rules.len().div_ceil(2))- .max_by_key(|(_, template)| template.entry_count())- .map(|(candidate, template)| (candidate.0.len(), Arc::clone(template)))- });- let mut dispatch = match (exact_template, extension_template.flatten()) {- (Some(template), _) => RuleDispatch::rebind_rules(&template, &rules),- (None, Some((prefix_len, template))) => {- let mut dispatch =- RuleDispatch::rebind_rules_for_extension(&template, &rules[..template.entry_count()]);- let mut rule_index = template.entry_count();- for &(selector_program, author) in &shape.0[prefix_len..] {- if self.programs.get(selector_program).entries().is_empty() {- continue;- }- insert_scope_rule(- &mut dispatch,- &self.programs,- rules[rule_index],- selector_program,- author,- );- rule_index = dispatch.entry_count();- }- assert_eq!(rule_index, rules.len());- dispatch.finish_prefixes(&mut dispatch_pools().storage.prefixes);- dispatch- }- (None, None) => {- let mut dispatch = RuleDispatch::new();- let mut rule_index = 0;- for &(selector_program, author) in shape.0.iter() {- if self.programs.get(selector_program).entries().is_empty() {- continue;- }- insert_scope_rule(- &mut dispatch,- &self.programs,- rules[rule_index],- selector_program,- author,- );- rule_index = dispatch.entry_count();- }- assert_eq!(rule_index, rules.len());- dispatch.finish_prefixes(&mut dispatch_pools().storage.prefixes);- let ancestor_shape = dispatch.ancestor_dispatch_shape();- if let Some(template) = self.ancestor_dispatch_templates.get(&ancestor_shape) {- dispatch.share_ancestor_topology_with(template);- }- dispatch- }- };- let ancestor_shape = dispatch.ancestor_dispatch_shape();- if let Some(template) = cascade_template {- dispatch.reuse_cascade_order(&template);- } else {- dispatch.assign_cascade_order(|candidate| {- let entry = &self.programs.get(candidate.program).entries()[candidate.entry as usize];- self.own_scope_cascade_priority_of(candidate.rule, scope, entry.specificity, u32::MAX, false)- });- }- // A rule declaring custom properties beside its longhands contributes those longhands- // as any rule does: the environment its custom properties decide is computed apart.- dispatch.assign_cascade_properties(- &mut dispatch_pools().storage,- |candidate| {- self.program.rule_is_gated_by_container_query(candidate.rule)- || !self.program.declarations_are_complete_for(candidate.rule)- },- |candidate| {- let entry = &self.programs.get(candidate.program).entries()[candidate.entry as usize];- let sheet = self.program.rule_sheet(candidate.rule);- if scope != TreeScopeID::DOCUMENT- || self.program.sheet_origin(sheet) != CascadeOrigin::Author- || self.program.rule_is_gated_by_container_query(candidate.rule)- || !self.program.declarations_are_complete_for(candidate.rule)- || entry.scope_root.is_some()- {- return None;- }- let declared = self.program.declared_properties_of(candidate.rule);- if declared.iter().any(|property| property.important) {- return None;- }- Some(declared.iter().map(|property| property.property))- },- );- let dispatch = Arc::new(dispatch);- if let Some(key) = shared_key {- dispatch_pools().dispatches.templates.insert(key, dispatch.downgrade());- }- self.scope_cascade_templates- .entry(cascade_shape.clone())- .or_insert_with(|| Arc::clone(&dispatch));- self.scope_dispatch_templates- .entry(shape.clone())- .or_insert_with(|| Arc::clone(&dispatch));- self.ancestor_dispatch_templates- .entry(ancestor_shape)- .or_insert_with(|| dispatch.ancestor_topology());- self.scope_templates_need_sweep = true;- let shapes = ScopeTemplateShapes {- dispatch: shape,- cascade: cascade_shape,- };- (dispatch, shapes)- }-- /// Drops the templates no live scope program has the shape of. Each style transaction- /// prepares its scopes first, so the templates a rebuild after a program change seeds from- /// have served by the time it ends. Sheets that arrive one at a time give every intermediate- /// sheet set its own shape, and each of those templates would otherwise keep a complete- /// dispatch alive for the rest of the document's life.- ///- /// The templates of the last removed program whose shape no live shape has or extends, the way- /// sheets arriving after it do, stay too, so that a page switching between two sheet sets- /// rebinds them. A template kept for a live shape is replaced by a live dispatch of that- /// shape, as an equivalent template that keeps no other dispatch alive.- // NB: The shapes' interior mutability is the memory charge of their shared storage, which hashing and comparing- // them does not read.- #[allow(clippy::mutable_key_type)]- pub(super) fn drop_unused_scope_templates(&mut self) {- if !std::mem::take(&mut self.scope_templates_need_sweep) {- return;- }- let mut live_dispatches = HashMap::<&ScopeDispatchShape, &Arc<RuleDispatch>>::default();- let mut live_cascades = HashMap::<&ScopeCascadeShape, &Arc<RuleDispatch>>::default();- let mut live_ancestors = HashMap::<AncestorDispatchShape, Arc<index::AncestorDispatchTopology>>::default();- for program in self.scope_programs.iter().flatten() {- live_dispatches- .entry(&program.shapes.dispatch)- .or_insert(&program.dispatch);- live_cascades- .entry(&program.shapes.cascade)- .or_insert(&program.dispatch);- live_ancestors- .entry(program.dispatch.ancestor_dispatch_shape())- .or_insert_with(|| program.dispatch.ancestor_topology());- }- // NB: A program removed while another of its shape replaces it, as an unrelated change does, keeps nothing- // the live templates do not, so an earlier removal keeps its templates instead.- let retired_index = self.retired_scope_templates.iter().rposition(|(shapes, _)| {- !live_dispatches- .keys()- .any(|live| live.0.len() >= shapes.dispatch.0.len() && live.0.starts_with(&shapes.dispatch.0))- });- let retired = retired_index.map(|index| &self.retired_scope_templates[index]);- let retired_ancestor_shape = retired.map(|(_, ancestors)| ancestors.shape());- self.scope_dispatch_templates- .retain(|shape, template| match live_dispatches.get(shape) {- Some(live) => {- if !Arc::ptr_eq(live, template) {- *template = Arc::clone(live);- }- true- }- None => retired.is_some_and(|(shapes, _)| shapes.dispatch == *shape),- });- self.scope_cascade_templates- .retain(|shape, template| match live_cascades.get(shape) {- Some(live) => {- if !Arc::ptr_eq(live, template) {- *template = Arc::clone(live);- }- true- }- None => retired.is_some_and(|(shapes, _)| shapes.cascade == *shape),- });- let ancestor_template_is_current =- |shape: &AncestorDispatchShape, template: &Arc<index::AncestorDispatchTopology>| match live_ancestors- .get(shape)- {- Some(live) => Arc::ptr_eq(live, template),- None => retired_ancestor_shape.as_ref() == Some(shape),- };- // NB: The table is shared copy-on-write with forks; only a change may unshare it.- if !self- .ancestor_dispatch_templates- .iter()- .all(|(shape, template)| ancestor_template_is_current(shape, template))- {- self.ancestor_dispatch_templates- .retain(|shape, template| match live_ancestors.get(shape) {- Some(live) => {- *template = Arc::clone(live);- true- }- None => retired_ancestor_shape.as_ref() == Some(shape),- });- }- let kept = retired_index.and_then(|index| self.retired_scope_templates.drain(..).nth(index));- self.retired_scope_templates.clear();- self.retired_scope_templates.extend(kept);- dispatch_pools()- .dispatches- .templates- .retain(|_, template| template.is_alive());- }-- /// Remove a scope program no concrete scope resolves to any more, keeping its templates as- /// the retired ones.- pub(super) fn remove_scope_program(&mut self, id: ScopeProgramID) {- let mut caches = self.prefix_caches.borrow_mut();- caches.states.remove(id);- caches.answers.remove_program(&mut self.match_answers, id);- drop(caches);- let program = self.scope_programs[id].take().unwrap();- let hash = intern_table::content_hash(&program.key);- self.scope_programs.remove_identity(hash, id);- self.vacant_scope_programs.push(id);- self.retired_scope_templates- .push((program.shapes, program.dispatch.ancestor_topology()));- self.scope_templates_need_sweep = true;- }-- pub(super) fn scope_dispatch_key(&self, scope: TreeScopeID) -> ScopeDispatchKey {- let document_sheet_mode = if scope == TreeScopeID::DOCUMENT {- DocumentSheetMode::None- } else if self.program.scope_uses_document_sheets(scope) {- DocumentSheetMode::All- } else {- DocumentSheetMode::NonAuthor- };- let document_sheets = if scope == TreeScopeID::DOCUMENT {- &[]- } else {- self.program.sheets_in_scope(TreeScopeID::DOCUMENT)- };- let document_sheets = document_sheets.iter().filter(|&&sheet| {- document_sheet_mode == DocumentSheetMode::All || self.program.sheet_origin(sheet) != CascadeOrigin::Author- });- ScopeDispatchKey {- depth: self.tree_scope_depth(scope),- document_sheet_mode,- sheets: self- .program- .sheets_in_scope(scope)- .iter()- .chain(document_sheets)- .map(|&sheet| (sheet, self.program.sheet_dispatch_version(sheet)))- .collect(),- layer_order: self.program.layer_order_key(scope),- }- }-- pub(super) fn scope_program(&self, id: ScopeProgramID) -> &ScopeProgram {- self.scope_programs[id]- .as_ref()- .expect("a retained scope names a live program")- }-- pub(super) fn release_scope_program(&mut self, id: ScopeProgramID) {- let program = self.scope_programs[id]- .as_mut()- .expect("a retained scope names a live program");- assert_ne!(program.scope_count, 0);- program.scope_count -= 1;- if program.scope_count != 0 {- return;- }- self.remove_scope_program(id);- }-- pub(super) fn intern_scope_program(&mut self, scope: TreeScopeID, key: ScopeDispatchKey) -> ScopeProgramID {- let hash = intern_table::content_hash(&key);- if let Some(id) = self.scope_programs.find(hash, |_id, program| {- program.as_ref().is_some_and(|program| program.key == key)- }) {- let count = &mut self.scope_programs[id].as_mut().unwrap().scope_count;- *count = count.checked_add(1).expect("scope program reference count overflow");- return id;- }-- let id = self.vacant_scope_programs.pop().unwrap_or_else(|| {- ScopeProgramID(u32::try_from(self.scope_programs.len()).expect("scope program identity space exhausted"))- });- let (dispatch, shapes) = self.build_ranked_scope_dispatch(scope);- let program = ScopeProgram {- key,- dispatch,- shapes,- scope_count: 1,- };- self.scope_programs.insert(hash, id, Some(program));- id- }-- /// Resolve the immutable selector program a concrete scope evaluates against.- pub(super) fn prepare_scope_program(&mut self, scope: TreeScopeID) -> (ScopeProgramID, Arc<RuleDispatch>) {- let depth = self.tree_scope_depth(scope);- let scope_index = scope.0 as usize;- if let Some(Some((held_depth, id))) = self.scope_program_by_scope.get(scope_index)- && *held_depth == depth- {- return (*id, Arc::clone(&self.scope_program(*id).dispatch));- }-- if let Some((_, previous)) = self.scope_program_by_scope.get_mut(scope_index).and_then(Option::take) {- self.release_scope_program(previous);- }- let key = self.scope_dispatch_key(scope);- let id = self.intern_scope_program(scope, key);- self.scope_program_by_scope.insert(scope_index, Some((depth, id)));- (id, Arc::clone(&self.scope_program(id).dispatch))- }-- /// Borrow a scope whose version and encapsulation depth were resolved before matching.- pub(super) fn prepared_scope_program(&self, scope: TreeScopeID) -> (ScopeProgramID, &RuleDispatch) {- let (_, id) = self- .scope_program_by_scope- .get(scope.0 as usize)- .copied()- .flatten()- .expect("a matching scope must be prepared before evaluation");- (id, &self.scope_program(id).dispatch)- }-- pub(super) fn prepare_scope_programs_for_nodes(&mut self, nodes: impl IntoIterator<Item = StyleNodeID>) {- if !self.tree.has_tree_scopes() && self.scope_roots.is_empty() {- self.prepare_scope_program(TreeScopeID::DOCUMENT);- return;- }- // Scopes are prepared in first-use order; a dense visited bitmap keyed by scope id keeps- // deduplication linear on pages whose every component contributes its own scope.- let mut scopes: SmallVec<[TreeScopeID; 4]> = SmallVec::new();- let mut seen: SmallVec<[bool; 64]> = SmallVec::new();- for node in nodes {- let inner = self- .tree- .shadow_root_of(node)- .and_then(|root| self.scope_by_root.get(root));- for scope in std::iter::once(self.tree.tree_scope(node))- .chain(inner)- .chain(self.scopes_slotted_into(node))- .chain(self.part_exposure_scopes(node))- {- let index = scope.0 as usize;- if index >= seen.len() {- seen.resize(index + 1, false);- }- if !seen[index] {- seen[index] = true;- scopes.push(scope);- }- }- }-- for scope in scopes {- self.prepare_scope_program(scope);- }- }-- fn prepare_prefix_rows_for_scope(- &mut self,- scope: TreeScopeID,- facts: &StyleNodeFacts,- contexts: &mut PrefixTransitionContexts,- ) {- let (program, dispatch) = self.prepared_scope_program(scope);- if dispatch.prefixes().is_empty() {- return;- }- let mut caches = self.prefix_caches.borrow_mut();- contexts.prepare(program, caches.states.prepare_program(program), facts);- }-- pub(super) fn prepare_prefix_rows_for_batch(- &mut self,- facts: &StyleNodeFacts,- contexts: &mut PrefixTransitionContexts,- ) {- let mut caches = self.prefix_caches.borrow_mut();- if !self.tree.has_tree_scopes() && self.scope_roots.is_empty() {- let (program, dispatch) = self.prepared_scope_program(TreeScopeID::DOCUMENT);- if !dispatch.prefixes().is_empty() {- contexts.prepare(program, caches.states.prepare_program(program), facts);- }-- return;- }- for row in 0..facts.row_count() {- let row = u32::try_from(row).expect("fact row space exhausted");- if !facts.has_row(row) {- continue;- }- let (program, dispatch) = self.prepared_scope_program(self.tree.tree_scope(facts.node_at(row)));- if !dispatch.prefixes().is_empty() {- contexts.prepare(program, caches.states.prepare_program(program), facts);- }- }- }-- fn prepare_matching_batch(&mut self, facts: &StyleNodeFacts) -> AncestorRequirementsCache {- let mut requirements = AncestorRequirementsCache::default();- if !self.tree.has_tree_scopes() && self.scope_roots.is_empty() {- let (_, dispatch) = self.prepare_scope_program(TreeScopeID::DOCUMENT);- requirements.prepare(&self.tree, facts, &dispatch, None);- return requirements;- }- self.prepare_scope_programs_for_nodes((0..facts.row_count()).filter_map(|row| {- let row = u32::try_from(row).expect("fact row space exhausted");- facts.has_row(row).then(|| facts.node_at(row))- }));- // Group primary nodes by ancestor topology. Shadow scopes keep only their own rows,- // rather than allocating a document-sized requirement matrix for each scope program.- let mut groups: Vec<(ScopeProgramID, Vec<StyleNodeID>, bool)> = Vec::new();- for row in 0..facts.row_count() {- let row = u32::try_from(row).expect("fact row space exhausted");- if !facts.has_row(row) {- continue;- }- let node = facts.node_at(row);- let scope = self.tree.tree_scope(node);- let (id, dispatch) = self.prepared_scope_program(scope);- let topology = dispatch.ancestor_topology_id();- let index = groups- .iter()- .position(|(id, _, _)| self.scope_program(*id).dispatch.ancestor_topology_id() == topology)- .unwrap_or_else(|| {- groups.push((id, Vec::new(), false));- groups.len() - 1- });- groups[index].1.push(node);- groups[index].2 |= scope == TreeScopeID::DOCUMENT;- }-- for (id, nodes, dense) in groups {- let dispatch = &self.scope_programs[id].as_ref().unwrap().dispatch;- requirements.prepare(&self.tree, facts, dispatch, (!dense).then_some(nodes.as_slice()));- }-- requirements- }-- /// Ask one scope's rules of one node against the dispatch the scope keeps.- #[allow(clippy::too_many_arguments)]- pub(super) fn match_node_in_kept_scope(- &mut self,- node: StyleNodeID,- scope: TreeScopeID,- facts: &StyleNodeFacts,- dispatch_workspace: &mut DispatchCandidateWorkspace,- matches: &mut RuleMatches,- requirements: Option<&AncestorRequirements>,- shared_prefix_caches: Option<&std::sync::Arc<SharedPrefixCaches>>,- prefix_contexts: &mut PrefixTransitionContexts,- match_workspace: Option<&mut MatchScratch>,- mut retry: BatchMatchRetry<'_>,- ) -> Result<(), Incomplete> {- let (scope_program, _) = self.prepared_scope_program(scope);- let dispatch = &self.scope_programs[scope_program].as_ref().unwrap().dispatch;- if let Some(completed) = retry.completed.as_deref_mut() {- completed.resize(dispatch.entry_count(), false);- }- let mut local_prefix_states;- let mut local_prefix_context;- let mut shared_prefix_caches = shared_prefix_caches.map(|caches| caches.borrow_mut());- let shared_prefix_states;- let prefix_states = if self.tree.tree_scope(node) != scope || dispatch.prefixes().is_empty() {- None- } else if let Some(caches) = shared_prefix_caches.as_deref_mut() {- let states = caches- .states- .lookup_mut(scope_program)- .sparse()- .expect("prefix rows are prepared before matching");- shared_prefix_states = Some(states);- shared_prefix_states.map(|states| {- prefix_contexts.rebind(scope_program, &mut *states, facts);- (states, prefix_contexts.get_mut(scope_program))- })- } else {- local_prefix_states = Some(PrefixStates::new());- local_prefix_context = Some(PrefixTransitionContext::new(- local_prefix_states.as_mut().unwrap(),- facts,- ));- local_prefix_states- .as_mut()- .map(|states| (states, local_prefix_context.as_mut().unwrap()))- };- let (result, effects) = self.match_node_in_scope(- node,- scope,- dispatch,- facts,- dispatch_workspace,- requirements,- prefix_states,- match_workspace,- BatchMatchAttempt {- matches,- requests: retry.requests,- completed: retry.completed.map(Vec::as_mut_slice),- deferred_prefix_matches: retry.deferred_prefix_matches,- answer_is_exact: retry.answer_is_exact,- cascade_only: retry.cascade_only,- },- );- self.append_witness_effects(effects);- result- }-- /// Ask one scope's rules of one node, appending what matches.- ///- /// The dispatch and the ancestor summary are passed in because the two callers get them- /// differently: a pass over the whole document builds one of each per scope and drops them,- /// while a per-element ask reads the dispatch the scope keeps and summarizes one element.- #[allow(clippy::too_many_arguments)]- pub(super) fn match_node_in_scope(- &self,- node: StyleNodeID,- scope: TreeScopeID,- dispatch: &RuleDispatch,- facts: &StyleNodeFacts,- dispatch_workspace: &mut DispatchCandidateWorkspace,- ancestor_requirements: Option<&AncestorRequirements>,- prefix_states: Option<(&mut PrefixStates, &mut PrefixTransitionContext)>,- match_workspace: Option<&mut MatchScratch>,- attempt: BatchMatchAttempt<'_>,- ) -> (Result<(), Incomplete>, Vec<WitnessEffect>) {- let mut effects = Vec::new();- let mut interpreter =- BatchMatcher::new(&self.tree, facts, dispatch, &self.programs, &self.program).in_scope(scope);- if attempt.cascade_only {- interpreter = interpreter.for_cascade();- }- if self.tree.tree_scope(node) == scope- && let Some(requirements) = ancestor_requirements- {- interpreter = interpreter.with_ancestor_requirements(requirements);- }- if let Some(shadow_root) = self.scope_root(scope) {- interpreter = interpreter.in_shadow_tree(shadow_root);- }- if self.tree.tree_scope(node) != scope {- if self.scopes_slotted_into(node).any(|slotted| slotted == scope) {- interpreter = interpreter.for_a_node_slotted_in();- } else if self.part_exposure_scopes(node).any(|exposed| exposed == scope) {- interpreter = interpreter.for_a_part_exposed_here();- } else if self- .tree- .shadow_root_of(node)- .is_some_and(|root| self.scope_root(scope) == Some(root))- {- interpreter = interpreter.for_the_host_of_this_tree();- }- }- let result = interpreter.match_node_collecting_requests(- node,- attempt.matches,- &self.counters,- BatchMatchState {- match_workspace,- witness_effects: Some(&mut effects),- dispatch_workspace,- requests: attempt.requests,- completed: attempt.completed,- prefix_states,- deferred_prefix_matches: attempt.deferred_prefix_matches,- },- );- if let Some(answer_is_exact) = attempt.answer_is_exact {- *answer_is_exact &= result.answer_is_exact;- }- (result.result, effects)- }-- pub(super) fn append_witness_effects(&mut self, effects: Vec<WitnessEffect>) {- if effects.is_empty() {- return;- }- self.pending_witness_effects.extend(effects);- }-- /// Install completed observations only after matching has released its reads.- pub(super) fn install_witness_effects(&mut self) {- if self.pending_witness_effects.is_empty() {- return;- }- for effect in std::mem::take(&mut self.pending_witness_effects) {- match effect {- WitnessEffect::Retain(key, witness) => {- self.relational_witnesses.retain(key, witness, &self.tree);- }- WitnessEffect::Clear(key) => self.relational_witnesses.clear(key),- }- }- }-- /// Return the retained witness proving that this anchor's Boolean cannot have flipped.- ///- /// The entry only proves that the anchor's last completed evaluation of the query answered- /// true; that the witness still witnesses is re-established here against the live tree and- /// the current facts. Anything unprovable - no entry, a retired or moved witness, a fact row- /// the check cannot see, a query the program no longer answers for - routes conservatively,- /// and a witness caught no longer witnessing is cleared at the end of the walk.- pub(super) fn retained_witness_for_anchor(- &mut self,- program_id: SelectorProgramID,- query_id: RelativeQueryID,- anchor: StyleNodeID,- ) -> Lookup<StyleNodeID, RelationalWitnessGap> {- let key = RelationalWitnessKey {- program: program_id,- query: query_id,- anchor,- };- let witness = match self.relational_witnesses.lookup(key).sparse() {- Ok(&witness) => witness,- Err(gap) => return Lookup::Missing(gap),- };- let Some(query) = self.programs.get(program_id).retainable_relative_query(query_id) else {- return Lookup::Missing(RelationalWitnessGap::MissingQuery(key));- };- if !self.tree.is_live(witness) {- self.append_witness_effects(vec![WitnessEffect::Clear(key)]);- return Lookup::Missing(RelationalWitnessGap::RetiredWitness { key, witness });- }- let Some(walk_anchor) = traversal_anchor(anchor, query.match_in_shadow_tree, &self.tree) else {- self.append_witness_effects(vec![WitnessEffect::Clear(key)]);- return Lookup::Missing(RelationalWitnessGap::UnreachableAnchor(key));- };- let still_on_the_axis = match query.axis {- RelativeAxis::Child => self.tree.parent(witness) == Some(walk_anchor),- RelativeAxis::NextSibling => self.tree.previous_element_sibling(witness) == Some(walk_anchor),- RelativeAxis::Descendant => self.tree.ancestors(witness).any(|ancestor| ancestor == walk_anchor),- // Walked backwards from the witness with a step budget, so the check stays constant- // however long the sequence is; an anchor further back than that routes conservatively.- RelativeAxis::FollowingSibling => {- let mut steps = 0;- let mut current = self.tree.previous_element_sibling(witness);- loop {- match current {- Some(sibling) if sibling == walk_anchor => break true,- Some(sibling) if steps < RETAINED_WITNESS_SIBLING_STEPS => {- steps += 1;- current = self.tree.previous_element_sibling(sibling);- }- _ => break false,- }- }- }- // A multi-compound argument is never simple, so no witness of it is ever retained.- RelativeAxis::NextSiblingSubtree | RelativeAxis::FollowingSiblingSubtree => false,- };- if !still_on_the_axis {- self.append_witness_effects(vec![WitnessEffect::Clear(key)]);- return Lookup::Missing(RelationalWitnessGap::StaleAxis { key, witness });- }- // The compound of a retainable query reads only facts the witness itself publishes, so one- // current-side row decides it exactly. A node the store has no row for reports a miss, and- // the miss routes conservatively rather than deciding anything.- let resident_facts = self.facts.primary();- let transaction_fact_view = self.transaction_fact_view.as_ref();- let current_row = transaction_fact_view- .and_then(|view| view.row_of(TransactionFactSide::After, resident_facts, witness))- .or_else(|| resident_facts.row_of(witness).map(|row| (resident_facts, row)));- if current_row.is_none() {- return Lookup::Missing(RelationalWitnessGap::IncompleteFacts {- key,- witness,- incomplete: Incomplete::MissingFacts(witness),- });- }- let program = self.programs.get(program_id);- let mut evaluator = MatchEvaluator::new(&self.tree, resident_facts);- if let Some(view) = transaction_fact_view {- evaluator = evaluator.with_transaction_fact_view(view, TransactionFactSide::After);- }- match evaluator.matches_node(program, query.compound, witness, &self.counters) {- Ok(true) => Lookup::Known(witness),- Ok(false) => {- self.append_witness_effects(vec![WitnessEffect::Clear(key)]);- Lookup::Missing(RelationalWitnessGap::SelectorMismatch { key, witness })- }- Err(incomplete) => Lookup::Missing(RelationalWitnessGap::IncompleteFacts {- key,- witness,- incomplete,- }),- }- }-- pub(super) fn append_descendant_fact_window(- &self,- append: &mut impl FnMut(StyleNodeID) -> bool,- root: StyleNodeID,- first: StyleNodeID,- mut remaining: usize,- ) -> bool {- let mut reached_first = false;- for node in self.tree.preorder(root) {- reached_first |= node == first;- if reached_first && append(node) {- remaining -= 1;- if remaining == 0 {- break;- }- }- }- reached_first- }-- /// Add the fact range an interrupted evaluator can still read, up to `window` rows of it.- ///- /// Returning a node means it was already requested but the resident store could not supply a- /// row for it, so another retry cannot make progress.- ///- /// A sibling or descendant scan names the whole remaining range it can read, but how much of- /// it the scan really reads is not known until it runs. Taking the whole range on the first- /// miss makes a bounded query materialize rows it may never inspect, while taking one row per- /// retry makes a query that reads the whole range quadratic. The range is therefore taken a- /// window at a time, and the window doubles per retry: a scan that stops early pays for what it- /// read, one that runs to the end converges in a logarithmic number of restarts, and neither- /// asks for more than twice what it needs.- pub(super) fn widen_fact_coverage(- &self,- covered: &mut Vec<StyleNodeID>,- incomplete: Incomplete,- window: &mut usize,- ) -> Result<(), StyleNodeID> {- let first = incomplete.first_missing_node();- if covered.contains(&first) {- return Err(first);- }- let mut append = |node| {- if covered.contains(&node) {- return false;- }- covered.push(node);- true- };- if self.append_fact_window(&mut append, incomplete, *window)? {- *window = window.saturating_mul(2);- }- Ok(())- }-- fn append_fact_window(- &self,- append: &mut impl FnMut(StyleNodeID) -> bool,- incomplete: Incomplete,- window: usize,- ) -> Result<bool, StyleNodeID> {- match incomplete {- Incomplete::MissingFacts(missing) => {- append(missing);- Ok(false)- }- Incomplete::MissingDescendantFacts { root, first } => self- .append_descendant_fact_window(append, root, first, window)- .then_some(true)- .ok_or(first),- Incomplete::MissingSiblingFacts { first, last_exclusive } => {- let mut remaining = window;- let mut current = Some(first);- while current != last_exclusive && remaining > 0 {- let Some(sibling) = current else {- break;- };- if append(sibling) {- remaining -= 1;- }- current = self.tree.next_element_sibling(sibling);- }- Ok(true)- }- }- }-- /// Add every exact fact range one cold candidate pass requested.- ///- /// `previously_covered` separates a duplicate request in this batch from a row that was already- /// materialized for the pass and still could not be supplied. The former is harmless; the- /// latter cannot make progress on another retry.- pub(super) fn widen_fact_coverage_for_requests(- &mut self,- covered: &mut Vec<StyleNodeID>,- requests: &[Incomplete],- window: &mut usize,- ) -> Result<(), StyleNodeID> {- use std::collections::hash_map::Entry;-- let previously_covered = covered.len();- let mut widened_a_range = false;- // Keep fact materialization in discovery order, but index membership for the whole- // batch. Scanning the growing vector for every requested row is quadratic.- let mut positions: HashMap<StyleNodeID, usize> = covered- .iter()- .copied()- .enumerate()- .map(|(index, node)| (node, index))- .collect();- // Several candidates can miss on the same range. Repeating that request would take- // another window beyond the one just added and rescan already-covered rows.- let mut seen = HashSet::default();- let result = (|| {- for &request in requests {- if !seen.insert(request) {- continue;- }- let first = request.first_missing_node();- if positions.get(&first).is_some_and(|&index| index < previously_covered) {- return Err(first);- }- let mut append = |node| {- if let Entry::Vacant(entry) = positions.entry(node) {- entry.insert(covered.len());- covered.push(node);- true- } else {- false- }- };- widened_a_range |= self.append_fact_window(&mut append, request, *window)?;- }- Ok(())- })();-- result?;- if widened_a_range {- *window = window.saturating_mul(2);- }- Ok(())- }-- /// Every rule that decides for one element, in the order the cascade applies them.- ///- /// This is the question a style recompute asks. The document pass below answers it for every- /// element at once and exists to be compared against another matcher; this one is what styling- /// reads.- #[must_use]- #[cfg(test)]- pub fn match_element_signature(&mut self, node: StyleNodeID) -> Option<u32> {- if !self.match_answer_is_comparable_across_elements(node) {- return None;- }- let effects = self- .batch_matching_traversal- .as_ref()- .map(|traversal| &traversal.answer_effects)- .unwrap_or(&self.published_match_answers.answer_effects);- effects- .cascade_input(&self.retained_match_answers, node)- .map(|identity| identity.0)- }-- pub(super) fn match_answer_is_comparable_across_elements(&self, node: StyleNodeID) -> bool {- self.tree.tree_scope(node) == TreeScopeID::DOCUMENT && self.match_answer_is_retainable(node)- }-- pub(super) fn match_answer_is_retainable(&self, node: StyleNodeID) -> bool {- self.tree.shadow_root_of(node).is_none()- && !self- .scopes_slotted_into(node)- .any(|scope| scope != TreeScopeID::DOCUMENT)- && !self- .part_exposure_scopes(node)- .any(|scope| scope != TreeScopeID::DOCUMENT)- }-- fn set_pending_answer_identity(- &mut self,- effects: &mut AnswerEffects,- node: StyleNodeID,- identity: MatchAnswerID,- ) -> bool {- if node.element_index().is_none() || self.match_answers.answer(identity).is_none() {- return false;- }- if effects.answer_identity(&self.retained_match_answers, node) == Some(identity) {- return true;- }- effects.remember_identity(node, identity, &mut self.match_answers);- true- }-- pub(super) fn install_winner_effects(&mut self, effects: super::cascade::WinnerEffects) {- effects.install(&mut self.winner_groups);- }-- pub(super) fn install_answer_effects(&mut self, mut effects: AnswerEffects) {- self.install_winner_effects(std::mem::take(&mut effects.winners));- effects.install(- &mut self.retained_match_answers,- &mut self.match_answers,- &mut self.prefix_caches.borrow_mut().answers,- );- }-- pub(super) fn retained_match_answer_with_effects<'a>(- &'a self,- effects: &AnswerEffects,- node: StyleNodeID,- ) -> Lookup<&'a Arc<[RetainedRuleMatch]>, StyleNodeID> {- match effects- .answer_identity(&self.retained_match_answers, node)- .and_then(|identity| self.match_answers.answer(identity))- {- Some(answer) => Lookup::Known(answer),- None => Lookup::Missing(node),- }- }-- pub(super) fn publish_cascade_input_with_effects(- &mut self,- effects: &mut AnswerEffects,- node: StyleNodeID,- cascade_input: MatchAnswerID,- ) {- if !self.match_answer_is_comparable_across_elements(node) {- effects.forget_cascade_input(node, &mut self.match_answers);- return;- }- if effects.cascade_input(&self.retained_match_answers, node) != Some(cascade_input) {- effects.remember_cascade_input(node, cascade_input, &mut self.match_answers);- }- }-- #[cfg(test)]- pub(super) fn remember_retained_match_answer(&mut self, node: StyleNodeID, matches: &[RuleMatch]) {- let mut effects = AnswerEffects::default();- self.remember_retained_match_answer_with_effects(&mut effects, node, matches);- self.install_answer_effects(effects);- }-- pub(super) fn remember_retained_match_answer_with_effects(- &mut self,- effects: &mut AnswerEffects,- node: StyleNodeID,- matches: &[RuleMatch],- ) {- let answer = prepare_retained_match_answer(matches.iter().copied());- self.remember_prepared_retained_match_answer_with_truth_with_effects(effects, node, answer, None);- }-- #[cfg(test)]- pub(super) fn remember_prepared_retained_match_answer_with_truth(- &mut self,- node: StyleNodeID,- answer: Vec<RetainedRuleMatch>,- selector_truth: Option<Vec<SelectorTruth>>,- ) {- let mut effects = AnswerEffects::default();- self.remember_prepared_retained_match_answer_with_truth_with_effects(- &mut effects,- node,- answer,- selector_truth,- );- self.install_answer_effects(effects);- }-- pub(super) fn remember_prepared_retained_match_answer_with_truth_with_effects(- &mut self,- effects: &mut AnswerEffects,- node: StyleNodeID,- answer: Vec<RetainedRuleMatch>,- selector_truth: Option<Vec<SelectorTruth>>,- ) {- if !self.match_answer_is_retainable(node) {- return;- }- let tree_scope = self.tree.tree_scope(node);- if answer.iter().any(|entry| entry.tree_scope != tree_scope) {- return;- }- let reused_derived_answer = verify_selector_truth_derivation_is_enabled().then(|| {- let truth = selector_truth.unwrap_or_else(|| prepare_selector_truth_set(&answer, &self.programs));- let truth_rows = truth.len();- let (identity, reused_truth) = self.selector_truth_sets.intern_prepared(truth);- self.counters.bump(if reused_truth {- Counter::SelectorTruthSetHits- } else {- Counter::SelectorTruthSetMisses- });- if !reused_truth {- self.counters.add(- Counter::SelectorTruthSetRows,- u64::try_from(truth_rows).expect("selector truth row count exceeds u64"),- );- }- let truth = Arc::clone(self.selector_truth_sets.get(identity));- let (dispatch, _) = self.build_ranked_scope_dispatch(tree_scope);- let mut derived = RuleMatches::new();- append_selector_truth_matches(- &mut derived,- node,- &self.program,- &self.programs,- &dispatch,- &truth,- &self.counters,- );- let derived = prepare_retained_match_answer(derived.as_slice().iter().copied());- let mut retained = RuleMatches::new();- append_retained_matches(&mut retained, node, tree_scope, &self.programs, &dispatch, &answer)- .expect("a retained answer must still exist in its ranked dispatch");- let retained = prepare_retained_match_answer(retained.as_slice().iter().copied());- assert_eq!(retained, derived, "selector truth derivation differs for {node:?}");- self.selector_truth_sets- .verify_derived_answer(identity, tree_scope, self.program.version(), &retained)- });- if let Some(reused) = reused_derived_answer {- self.counters.bump(if reused {- Counter::SelectorTruthDerivedAnswerHits- } else {- Counter::SelectorTruthDerivedAnswerMisses- });- }- if node.element_index().is_none() {- return;- }- let identity = self.match_answers.intern_prepared(answer, &self.programs);- if effects.answer_identity(&self.retained_match_answers, node) != Some(identity) {- effects.remember_identity(node, identity, &mut self.match_answers);- }- }-- pub(super) fn retained_match_answer(&self, node: StyleNodeID) -> Lookup<&Arc<[RetainedRuleMatch]>, StyleNodeID> {- match self- .current_answer_identity(node)- .and_then(|identity| self.match_answers.answer(identity))- {- Some(answer) => Lookup::Known(answer),- None => Lookup::Missing(node),- }- }-- /// Materialize one selector program's exact subject relation from the active side retained by- /// the previous style transaction. Every connected element must have an exact answer: a sparse- /// column cannot prove that the missing elements do not match.- pub(super) fn retained_selector_incidence(- &mut self,- program: SelectorProgramID,- document_root: StyleNodeID,- ) -> Option<Arc<[RetainedSelectorIncidence]>> {- if let Some(incidences) = self.retained_selector_incidences.lookup(program) {- return Some(Arc::clone(incidences));- }- let mut incidences = Vec::new();- for node in self.tree.preorder(document_root) {- let answer = self.retained_match_answer(node).sparse().ok()?;- for matched in answer.iter().filter(|matched| matched.program == program) {- incidences.push(RetainedSelectorIncidence {- node,- entry: matched.entry,- });- }- }- incidences.sort_unstable();- incidences.dedup();- Some(self.retained_selector_incidences.remember(program, incidences))- }-- /// Materialize several active programs' selector incidences in one retained-answer pass.- ///- /// A media-query change commonly flips many independently gated rules at once. Walking every- /// retained match answer once per rule makes planning proportional to rules times elements,- /// even though each answer already contains all of those rules together.- pub(super) fn retain_selector_incidences(&mut self, programs: &[SelectorProgramID], document_root: StyleNodeID) {- let mut missing: Vec<_> = programs- .iter()- .copied()- .filter(|program| self.retained_selector_incidences.lookup(*program).is_none())- .collect();- missing.sort_unstable();- missing.dedup();- if missing.is_empty() {- return;- }- self.counters- .add(Counter::RetainedSelectorIncidenceBatchPrograms, missing.len() as u64);-- let mut incidences = vec![Vec::new(); missing.len()];- let mut rows = 0;- for node in self.tree.preorder(document_root) {- let Ok(answer) = self.retained_match_answer(node).sparse() else {- self.counters.bump(Counter::RetainedSelectorIncidenceBatchMissingRows);- return;- };- rows += 1;- for matched in answer.iter() {- let Ok(index) = missing.binary_search(&matched.program) else {- continue;- };- incidences[index].push(RetainedSelectorIncidence {- node,- entry: matched.entry,- });- }- }- self.counters.add(Counter::RetainedSelectorIncidenceBatchRows, rows);- for (program, mut incidences) in missing.into_iter().zip(incidences) {- incidences.sort_unstable();- incidences.dedup();- self.retained_selector_incidences.remember(program, incidences);- }- }-- /// Materialize selector incidence from current facts when no active retained answer names it.- pub(super) fn materialize_current_selector_incidence(- &mut self,- program: SelectorProgramID,- ) -> Option<Arc<[RetainedSelectorIncidence]>> {- if let Some(incidences) = self.retained_selector_incidences.lookup(program) {- return Some(Arc::clone(incidences));- }- if self.programs.get(program).can_leave_its_scope() {- return None;- }- let (scope_program, dispatch) = self.prepare_scope_program(TreeScopeID::DOCUMENT);- let compiled = self.programs.get(program);- let mut incidences = Vec::new();- for (entry_index, entry) in compiled.entries().iter().enumerate() {- let posting_key = compiled.dispatch_key(entry);- if !posting_key.has_selector_posting() {- return None;- }- let candidates = match self.facts.postings().lookup(posting_key) {- Lookup::Known(posting) => posting.candidates(),- Lookup::KnownAbsent => continue,- Lookup::Missing(_) => return None,- };- let subject_required = compiled.subject_required_keys(entry_index);- let position = compiled.subject_position(entry_index);- let prefix_entry = entry- .has_prefix_chain()- .then(|| {- self.programs.entry_id(- program,- u32::try_from(entry_index).expect("selector entry identity space exhausted"),- )- })- .filter(|&entry| dispatch.prefixes().contains_entry(entry));- for node in candidates {- if !self.node_is_within_subject_position(node, position, TransactionFactSide::After) {- continue;- }- let mut carries_required = true;- for required in subject_required {- if !required.has_selector_posting() {- continue;- }- match self.facts.postings().lookup(*required) {- Lookup::Known(posting) => carries_required &= posting.contains(node),- Lookup::KnownAbsent => carries_required = false,- Lookup::Missing(_) => return None,- }- if !carries_required {- break;- }- }- if !carries_required {- continue;- }- if let Some(prefix_entry) = prefix_entry {- let retained_prefix_match = {- let caches = self.prefix_caches.borrow();- caches.states.lookup(scope_program).sparse().ok().and_then(|states| {- states- .retained_matches_for(node)- .map(|matches| matches.contains(&prefix_entry))- })- };- if let Some(matches) = retained_prefix_match {- if matches {- incidences.push(RetainedSelectorIncidence {- node,- entry: u32::try_from(entry_index).expect("selector entry identity space exhausted"),- });- }- continue;- }- }- match MatchEvaluator::new(&self.tree, self.facts.primary()).matches_entry_after_dispatch(- compiled,- entry,- posting_key,- node,- &self.counters,- ) {- Ok(true) => incidences.push(RetainedSelectorIncidence {- node,- entry: u32::try_from(entry_index).expect("selector entry identity space exhausted"),- }),- Ok(false) => {}- Err(_) => return None,- }- }- }- incidences.sort_unstable();- incidences.dedup();- let mut selected_count = 0;- for index in 0..incidences.len() {- let incidence = incidences[index];- let entry = &compiled.entries()[incidence.entry as usize];- let existing = incidences[..selected_count]- .iter_mut()- .rev()- .take_while(|existing| existing.node == incidence.node)- .find(|existing| compiled.entries()[existing.entry as usize].pseudo_element == entry.pseudo_element);- if let Some(existing) = existing {- if entry.specificity > compiled.entries()[existing.entry as usize].specificity {- *existing = incidence;- }- } else {- incidences[selected_count] = incidence;- selected_count += 1;- }- }- incidences.truncate(selected_count);- incidences.sort_unstable();- Some(self.retained_selector_incidences.remember(program, incidences))- }-- /// Read one selector entry's pre-transaction truth from the retained exact answer.- ///- /// A selector list retains only the entry which supplied the rule's winning specificity. If a- /// different entry of the same program is present, absence of `entry` is therefore not proof- /// that it did not match, and exact narrowing must fall back conservatively.- pub(super) fn retained_entry_matches(- &self,- node: StyleNodeID,- program: SelectorProgramID,- entry: u32,- ) -> Option<bool> {- let answer = self.retained_match_answer(node).sparse().ok()?;- let mut matched_program = false;- for matched in answer.iter() {- if matched.program != program {- continue;- }- if matched.entry == entry {- return Some(true);- }- matched_program = true;- }- (!matched_program).then_some(false)- }-- pub(super) fn append_catalog_answer(- &self,- identity: MatchAnswerID,- node: StyleNodeID,- tree_scope_override: Option<TreeScopeID>,- out: &mut Vec<RuleMatch>,- ) -> Option<()> {- let answer = self.match_answers.answer(identity)?;- out.reserve_exact(answer.len());- for &stored_entry in answer.iter() {- let mut entry = stored_entry;- if let Some(tree_scope) = tree_scope_override {- entry.tree_scope = tree_scope;- }- let (_, dispatch) = self.prepared_scope_program(entry.tree_scope);- let cascade_order = dispatch.cascade_order_for_entry(entry.rule, entry.program, entry.entry)?;- out.push(entry.materialize(node, &self.programs, cascade_order)?);- }- Some(())- }-- /// The selector identities whose answers can change in a patchable transaction.- ///- /// A retained answer keeps only the greatest matching selector-list entry per rule and pseudo- /// target. Re-evaluating one routed entry is therefore not enough when that entry was the- /// winner: another entry of the same rule may still match. The patch unit is consequently one- /// routed rule version. Program edits name the old version for removal and the current version- /// for evaluation, while every identity no input reached remains byte-for-byte unchanged.- pub(super) fn rules_for_retained_answer_patch(- &self,- transaction: &StyleTransaction,- ) -> Option<RetainedAnswerPatchSelection> {- if !transaction.markers.is_empty() {- return None;- }-- let mut affected = Vec::new();- let mut always_emit = false;- let mut has_non_selector_inputs = false;- let mut always_emit_nodes = Vec::new();- let mut orders_shifted = false;- let mut requires_full_match = false;- let mut tree_mutation_rules_selected = false;- let mut affected_routing_keys = HashSet::default();- let mut affected_current_rules = HashSet::default();- let mut cascade_update_properties = Vec::new();- let mut cascade_update_rules = Vec::new();- for input in &transaction.inputs {- // Retained cascade inputs are document-scope identities. A local fact inside a shadow- // tree may route to both that tree and an outer host, but its published answers cannot- // be completed from the document cascade order used by a retained patch.- if input- .key- .style_node()- .is_some_and(|node| self.tree.tree_scope(node) != TreeScopeID::DOCUMENT)- {- return None;- }- // Assigning a slottable moves it between the cascade programs of shadow scopes even- // though the slottable itself remains in the document scope. A document-scope patch- // cannot name those rules, so treating this as an ordinary tree mutation can preserve- // a stale retained answer and suppress the reaction entirely.- if let (- InputKey::TreeRelations(_),- InputValue::TreeRelations(Some(old)),- InputValue::TreeRelations(Some(new)),- ) = (input.key, input.old, input.new)- && old.assigned_slot != new.assigned_slot- {- return None;- }- let join_deltas = transaction.program_joins_for(input.key);- if !join_deltas.is_empty() {- if input- .key- .program_tree_scope()- .is_some_and(|scope| scope != TreeScopeID::DOCUMENT)- {- return None;- }- for delta in join_deltas {- let version = self.program.rule_version(delta.rule);- if version.kind == RuleKind::Property {- if let Some(name) = version.declared_name {- match self.custom_property_registration_consumers(name) {- Ok(consumers) => always_emit_nodes.extend(consumers),- Err(_) => {- always_emit = true;- has_non_selector_inputs = true;- }- }- }- continue;- }- if version.kind == RuleKind::Keyframes {- if let Some(name) = version.declared_name {- match self.facts.postings().lookup(DependencyPostingKey::AnimationName(name)) {- Lookup::Known(posting) => always_emit_nodes.extend(posting.candidates()),- Lookup::KnownAbsent => {}- Lookup::Missing(_) => {- always_emit = true;- has_non_selector_inputs = true;- }- }- }- continue;- }- if version.kind == RuleKind::Function {- match self.facts.postings().lookup(DependencyPostingKey::AnyCustomFunction) {- Lookup::Known(posting) => always_emit_nodes.extend(posting.candidates()),- Lookup::KnownAbsent => {}- Lookup::Missing(_) => {- always_emit = true;- has_non_selector_inputs = true;- }- }- continue;- }- match delta.kind {- ProgramJoinDeltaKind::Declarations => {- always_emit = true;- has_non_selector_inputs |= !version.kind.matches_elements();- }- ProgramJoinDeltaKind::Priority => {- // NB: Named rules have no retained selector matches, but changing- // their priority can still change the definition consumers use.- if !version.kind.matches_elements() {- always_emit = true;- has_non_selector_inputs = true;- }- orders_shifted = true;- cascade_update_rules.push(delta.rule);- cascade_update_properties.extend(- self.program- .declared_properties_of(delta.rule)- .iter()- .map(|declared| declared.property),- );- }- ProgramJoinDeltaKind::ActiveRuleMatch => {- requires_full_match = true;- let reevaluate_current = matches!(- input.key,- InputKey::RuleField(_, RuleField::Activation) | InputKey::SheetActivation(_)- );- if reevaluate_current && let Some(program) = delta.after_program {- affected.push(RetainedAnswerPatchSelectionRule {- rule: delta.rule,- program,- evaluate: true,- });- }- let before_program = delta.before_contributes.then_some(delta.before_program).flatten();- let after_program = delta.after_contributes.then_some(delta.after_program).flatten();- if !reevaluate_current {- if before_program == after_program {- if let Some(program) = after_program {- affected.push(RetainedAnswerPatchSelectionRule {- rule: delta.rule,- program,- evaluate: true,- });- }- } else {- if let Some(program) = before_program {- affected.push(RetainedAnswerPatchSelectionRule {- rule: delta.rule,- program,- evaluate: false,- });- }- if let Some(program) = after_program {- affected.push(RetainedAnswerPatchSelectionRule {- rule: delta.rule,- program,- evaluate: true,- });- }- }- }- // Named rules and custom functions have consumers outside selector- // answers. A program-less selector replacement does not: absence on- // that field means there is no selector contribution on that side.- if !matches!(input.key, InputKey::RuleField(_, RuleField::Selector))- && (delta.before_contributes || delta.after_contributes)- && delta.before_program.is_none()- && delta.after_program.is_none()- {- always_emit = true;- has_non_selector_inputs = true;- }- }- }- }- continue;- }- let keys = match input.key {- InputKey::CascadeTopology(TopologyAxis::SheetOrder(_) | TopologyAxis::LayerOrder(_)) => continue,- InputKey::LocalFeature(_, LocalFeatureKey::PartExposure) => return None,- InputKey::TreeRelations(_) | InputKey::LocalFeature(_, LocalFeatureKey::ArrivingFacts) => {- // A subtree arriving, leaving, or moving cannot change a resident answer- // through a descendant or child compound: a non-subject compound matching- // inside the moved subtree puts the subject inside it too, and the plan- // forgets the moved subtree's own answers so those nodes match cold. What- // reaches residents is the sibling axis, relational queries, and positional,- // emptiness, or heading truth, so those rule families are the affected set.- if !tree_mutation_rules_selected {- tree_mutation_rules_selected = true;- let tree_mutation_routes = self- .routing- .sibling_first_routes()- .iter()- .chain(self.routing.relational_routes())- .chain(self.routing.routes_for(RoutingKey::Structural));- for &route in tree_mutation_routes {- let rule = self.routing.rule_of(route);- let point = self.routing.route(route);- let (program, _) = self.programs.entry_location(point.entry);- if self.program.rule_can_decide(rule)- && self.program.rule_version(rule).selector_program == Some(program)- {- affected_current_rules.insert((rule, program));- }- }- }- continue;- }- 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- }- InputKey::LocalFeature(..) | InputKey::State(..) => routing_keys_for_input(input),- InputKey::ElementDeclaration(node, _) | InputKey::ElementStyleInput(node) => {- always_emit_nodes.push(node);- continue;- }- InputKey::CustomPropertyRegistration(name) => {- match self.custom_property_registration_consumers(name) {- Ok(consumers) => always_emit_nodes.extend(consumers),- Err(_) => {- always_emit = true;- has_non_selector_inputs = true;- }- }- continue;- }- _ => return None,- };- affected_routing_keys.extend(keys);- }- for key in affected_routing_keys {- for &route in self.routing.routes_for(key) {- let rule = self.routing.rule_of(route);- let point = self.routing.route(route);- let (program, _) = self.programs.entry_location(point.entry);- if self.program.rule_can_decide(rule)- && self.program.rule_version(rule).selector_program == Some(program)- {- affected_current_rules.insert((rule, program));- }- }- }- affected.extend(- affected_current_rules- .into_iter()- .map(|(rule, program)| RetainedAnswerPatchSelectionRule {- rule,- program,- evaluate: true,- }),- );- let mut removed_programs: Vec<SelectorProgramID> = affected- .iter()- .filter_map(|affected| (!affected.evaluate).then_some(affected.program))- .collect();- if !removed_programs.is_empty() {- removed_programs.sort_unstable();- removed_programs.dedup();- affected.extend(- self.program- .sheets_in_scope(TreeScopeID::DOCUMENT)- .iter()- .flat_map(|&sheet| self.program.rules_in_sheet(sheet))- .filter_map(|current_rule| {- let program = self.program.rule_version(current_rule).selector_program?;- removed_programs.binary_search(&program).ok()?;- Some(RetainedAnswerPatchSelectionRule {- rule: current_rule,- program,- evaluate: true,- })- }),- );- }- affected.sort_unstable_by_key(|affected| (affected.rule, affected.program));- affected.dedup_by(|next, previous| {- if (previous.rule, previous.program) != (next.rule, next.program) {- return false;- }- previous.evaluate |= next.evaluate;- true- });- cascade_update_properties.extend(- transaction- .rule_declaration_changes- .iter()- .flat_map(|change| change.old_properties.iter().chain(&change.new_properties).copied()),- );- cascade_update_rules.extend(transaction.rule_declaration_changes.iter().map(|change| change.rule));- let custom_changed_rules: Vec<RuleID> = transaction- .rule_declaration_changes- .iter()- .filter(|change| change.custom_declarations_changed)- .map(|change| change.rule)- .collect();- Some(RetainedAnswerPatchSelection {- affected,- always_emit,- has_non_selector_inputs,- always_emit_nodes,- orders_shifted,- requires_full_match,- custom_changed_rules,- cascade_update_properties,- cascade_update_rules,- program_base_version: transaction.program_base_version,- })- }-- pub(super) fn prepare_retained_answer_patch(- &mut self,- selection: RetainedAnswerPatchSelection,- ) -> RetainedAnswerPatch {- let (scope_program, dispatch) = self.prepare_scope_program(TreeScopeID::DOCUMENT);- let rule_keys: Vec<_> = selection- .affected- .into_iter()- .map(|affected| (affected.rule, affected.program))- .collect();- let dispatch_workspace = DispatchCandidateWorkspace::with_entry_capacity(dispatch.entry_count());- let prefix_context = {- let mut caches = self.prefix_caches.borrow_mut();- caches.states.make_scratch();- caches.states.prepare_to_mutate();- let states = caches.states.prepare_program(scope_program);- // NB: A narrow filtered patch bypasses prefixes in the matcher. Every per-node- // narrowed key set is a subset of rule_keys, so it takes that same path.-- if BatchMatcher::new(- &self.tree,- self.facts.primary(),- &dispatch,- &self.programs,- &self.program,- )- .filtered_rules_are_narrow(&rule_keys)- {- PrefixTransitionContext::default()- } else {- PrefixTransitionContext::new(states, self.facts.primary())- }- };- let mut cascade_update_properties = selection.cascade_update_properties;- cascade_update_properties.sort_unstable();- cascade_update_properties.dedup();- let mut cascade_update_rules = selection.cascade_update_rules;- cascade_update_rules.sort_unstable();- cascade_update_rules.dedup();- let mut custom_changed_rules = selection.custom_changed_rules;- custom_changed_rules.sort_unstable();- custom_changed_rules.dedup();- let mut always_emit_nodes = selection.always_emit_nodes;- always_emit_nodes.sort_unstable();- always_emit_nodes.dedup();- RetainedAnswerPatch {- prefix_context,- rule_keys,- scope_program,- dispatch,- match_workspace: MatchScratch::default(),- prefix_caches: std::sync::Arc::clone(&self.prefix_caches),- dispatch_workspace,- always_emit: selection.always_emit,- has_non_selector_inputs: selection.has_non_selector_inputs,- always_emit_nodes,- orders_shifted: selection.orders_shifted,- requires_full_match: selection.requires_full_match,- cascade_update_properties,- cascade_update_rules,- custom_changed_rules,- cascade_candidates: Vec::new(),- cascade_compaction_workspace: ordering::CascadeCompactionWorkspace::default(),- program_base_version: selection.program_base_version,- delta_memo: HashMap::default(),- }- }-- /// Repair declaration or priority edits from retained selector truth and the previous compact- /// answer.- ///- /// Element winners are updated only for properties declared by the edited or reprioritized- /// rules. Pseudo-element winners are not retained yet, so an affected rule that matched a- /// pseudo target uses the exact fallback. Every other pseudo entry is unchanged and can be- /// copied from the previous compact answer.- pub(super) fn apply_retained_cascade_updates(- &mut self,- effects: &mut AnswerEffects,- node: StyleNodeID,- patch: &mut RetainedAnswerPatch,- old_identity: MatchAnswerID,- old_cascade_input: MatchAnswerID,- ) -> Option<RetainedAnswerPatchOutcome> {- let retained = self.match_answers.retained_answer(old_identity)?;- if patch.cascade_update_properties.is_empty() || patch.requires_full_match {- return None;- }- let base_version = patch.program_base_version?;- let (_, previous) = effects- .winners- .view(&self.winner_groups)- .token_for(WinnerGroupKey::retained(node, base_version))- .sparse()- .ok()?;- let mut exact_answer: Vec<RuleMatch> = retained- .iter()- .copied()- .map(|entry| {- let cascade_order = patch- .dispatch- .cascade_order_for_entry(entry.rule, entry.program, entry.entry)?;- entry.materialize(node, &self.programs, cascade_order)- })- .collect::<Option<_>>()?;- exact_answer = self.in_cascade_order(exact_answer, false);- let cascade_winners_are_complete =- self.cascade_winner_inventory_is_complete_in_transaction(effects, &exact_answer, node);- if exact_answer.iter().any(|entry| {- entry.pseudo_element.is_some() && patch.cascade_update_rules.binary_search(&entry.rule).is_ok()- }) {- return None;- }-- let updates = self.exact_cascade_winner_updates_for_properties_with_scratch(- node,- &exact_answer,- None,- &patch.cascade_update_properties,- &mut patch.cascade_candidates,- )?;- let (state, delta) =- self.with_cascade_interning_counters(|groups| groups.apply_property_updates(previous, &updates));- let published = effects- .winners- .set(&mut self.winner_groups, node, state, self.program.version());-- if published {- self.counters.bump(Counter::CascadeNodeHandlesPublished);- }-- let mut winning_rules: Vec<RuleID> = self- .winner_groups- .winners_in_state(state)- .filter_map(|winner| match winner.source {- WinnerSource::Rule(rule) => Some(rule),- WinnerSource::Element(_) | WinnerSource::ExactCascade => None,- })- .collect();- winning_rules.sort_unstable();- winning_rules.dedup();- self.counters- .add(Counter::CascadeMatchesBeforeCompaction, exact_answer.len() as u64);- let old_compact = self.match_answers.answer(old_cascade_input)?;- exact_answer.retain(|entry| {- if entry.pseudo_element.is_some() {- return old_compact- .iter()- .any(|old| (old.rule, old.program, old.entry) == (entry.rule, entry.program, entry.entry));- }- self.compaction_keeps_verbatim(entry.rule) || winning_rules.binary_search(&entry.rule).is_ok()- });- let new_cascade_input = self.intern_cascade_input(&exact_answer);- if new_cascade_input != old_cascade_input {- self.counters.bump(Counter::MatchAnswerChanges);- }- self.publish_cascade_input_with_effects(effects, node, new_cascade_input);- // An edit to a matched rule's custom declarations moves no winner; the node reacts to it- // all the same, since its environment is computed from those declarations.- let emit = !delta.is_empty()- || self.record_rolls_back_substitution(node)- || patch.has_non_selector_inputs- || patch.always_emit_nodes.binary_search(&node).is_ok()- || exact_answer.iter().any(|entry| {- entry.pseudo_element.is_none() && patch.custom_changed_rules.binary_search(&entry.rule).is_ok()- });- if !emit {- self.counters.bump(Counter::RetainedMatchAnswerPatchStops);- }- Some(RetainedAnswerPatchOutcome {- identity_preserved: !emit,- emit,- incremental_cascade_answer: Some(IncrementalCascadeAnswer {- node,- cascade_input: new_cascade_input,- matches: Some(exact_answer.into_boxed_slice()),- cascade_winners_are_complete,- }),- })- }-- /// Whether signed element match changes cannot alter the compact cascade answer.- ///- /// Keep the exact retained answer current even when every changed rule loses to an- /// unaffected retained winner, but avoid materializing and reducing that whole answer again.- pub(super) fn retained_match_deltas_cannot_change_cascade(- &self,- effects: &AnswerEffects,- node: StyleNodeID,- retained: &[RetainedRuleMatch],- deltas: &[SelectorTruthDelta],- ) -> bool {- // A record rolled back below a substituted revert keyword holds a declaration its winners- // do not name, which any delta may move.- if self.record_rolls_back_substitution(node) {- return false;- }- let Some((_, previous)) = effects- .winners- .view(&self.winner_groups)- .token_for(WinnerGroupKey::current(node, self.program.version()))- .sparse()- .ok()- else {- return false;- };- if !self.facts.element_custom_declarations(node).is_empty() {- return false;- }- for retained_entry in retained {- let Some(entry) = self- .programs- .get(retained_entry.program)- .entries()- .get(retained_entry.entry as usize)- else {- return false;- };- if entry.pseudo_element.is_none()- && (retained_entry.tree_scope != TreeScopeID::DOCUMENT- || self.program.rule_is_gated_by_container_query(retained_entry.rule)- || !self.program.declarations_are_complete_for(retained_entry.rule))- {- return false;- }- }- for delta in deltas {- let entry = self.programs.entry(delta.entry).1;- if !self.rule_has_complete_element_winners(delta.rule, entry) {- return false;- }- for declared in self.program.declared_properties_of(delta.rule) {- if matches!(- declared.operator,- CascadeOperator::Revert | CascadeOperator::RevertLayer- ) {- return false;- }- let Some(winner) = self.winner_groups.winner_in_state(previous, declared.property) else {- return false;- };- if winner.key.continuation != CascadeContinuationID::default() {- return false;- }- match delta.change {- SetChange::Removed if winner.source == WinnerSource::Rule(delta.rule) => return false,- SetChange::Added => {- if winner.source == WinnerSource::ExactCascade {- return false;- }- let priority = self.cascade_priority_of(- node,- delta.rule,- TreeScopeID::DOCUMENT,- entry.specificity,- u32::MAX,- declared.important,- );- if priority > winner.priority {- return false;- }- }- SetChange::Removed => {}- }- }- }- true- }-- /// Apply signed entry truth to the compact retained relation without publishing it.- ///- /// Mixed patches use this as their exact base, then ask the matcher only about the remaining- /// refreshes and attributed rules. The same selector-list guards as the direct path keep an- /// entry delta from hiding a different winning entry of the rule.- fn retained_answer_after_deltas(- &self,- node: StyleNodeID,- patch: &RetainedAnswerPatch,- retained: &[RetainedRuleMatch],- deltas: &[SelectorTruthDelta],- ) -> Option<(Vec<RetainedRuleMatch>, u64)> {- if !patch.requires_full_match {- for delta in deltas {- let (program, selector_entry) = self.programs.entry_location(delta.entry);- let entries = self.programs.get(program).entries();- let changed_entry = entries.get(selector_entry as usize)?;- let retained_winner = retained.iter().find(|retained_entry| {- retained_entry.rule == delta.rule- && self- .programs- .get(retained_entry.program)- .entries()- .get(retained_entry.entry as usize)- .is_some_and(|entry| entry.pseudo_element == changed_entry.pseudo_element)- });- match delta.change {- SetChange::Added- if retained_winner.is_some_and(|winner| {- self.programs.entry_id(winner.program, winner.entry) != delta.entry- }) =>- {- return None;- }- SetChange::Removed- if retained_winner.is_some_and(|winner| {- self.programs.entry_id(winner.program, winner.entry) == delta.entry- }) && entries.iter().enumerate().any(|(index, entry)| {- index != selector_entry as usize && entry.pseudo_element == changed_entry.pseudo_element- }) =>- {- return None;- }- _ => {}- }- }- }-- let retained_key = |entry: &RetainedRuleMatch| (entry.rule, self.programs.entry_id(entry.program, entry.entry));- debug_assert!(retained.is_sorted_by_key(retained_key));- let mut answer = Vec::with_capacity(retained.len().saturating_add(deltas.len()));- let mut retained_index = 0;- let mut delta_index = 0;- let mut applied = 0_u64;- while delta_index < deltas.len() {- let delta = deltas[delta_index];- debug_assert_eq!(delta.node, node);- let key = (delta.rule, delta.entry);- let mut weight = 0_i32;- while delta_index < deltas.len() && (deltas[delta_index].rule, deltas[delta_index].entry) == key {- weight += match deltas[delta_index].change {- SetChange::Added => 1,- SetChange::Removed => -1,- };- delta_index += 1;- }- if weight == 0 {- continue;- }- while retained_index < retained.len() && retained_key(&retained[retained_index]) < key {- answer.push(retained[retained_index]);- retained_index += 1;- }- let held = retained.get(retained_index).filter(|entry| retained_key(entry) == key);- if weight < 0 {- held?;- retained_index += 1;- } else {- if held.is_some() {- return None;- }- let (program, selector_entry) = self.programs.entry_location(delta.entry);- let entry = self.programs.get(program).entries().get(selector_entry as usize)?;- if entry.scope_root.is_some() {- return None;- }- answer.push(RetainedRuleMatch {- rule: delta.rule,- program,- entry: selector_entry,- tree_scope: TreeScopeID::DOCUMENT,- scope_proximity: u32::MAX,- });- }- applied += 1;- }- answer.extend_from_slice(&retained[retained_index..]);- Some((answer, applied))- }-- /// Apply a complete signed match delta directly to one retained exact answer.- ///- /// Entries with dynamic scope proximity still use the cold patch: their match row contains a- /// value that the prefix match-set delta does not carry yet.- #[allow(clippy::too_many_arguments)]- pub(super) fn apply_retained_match_answer_deltas(- &mut self,- effects: &mut AnswerEffects,- node: StyleNodeID,- patch: &mut RetainedAnswerPatch,- old_identity: MatchAnswerID,- old_cascade_input: MatchAnswerID,- deltas: &[SelectorTruthDelta],- ) -> Option<RetainedAnswerPatchOutcome> {- let retained = self.match_answers.retained_answer(old_identity)?;- let orders_shifted = patch.orders_shifted_for(retained)- || (patch.orders_shifted- && deltas- .iter()- .any(|delta| patch.cascade_update_rules.binary_search(&delta.rule).is_ok()));- if !patch.cascade_update_properties.is_empty() {- if !deltas.is_empty() {- return None;- }- let outcome = self.apply_retained_cascade_updates(effects, node, patch, old_identity, old_cascade_input)?;- self.counters.bump(Counter::RetainedMatchAnswerDeltaPatches);- return Some(outcome);- }- // Empty signed truth preserves the exact answer. Unless cascade order itself moved, its- // compact identity is also unchanged, so stop without rebuilding either representation.- if deltas.is_empty() && !orders_shifted {- self.publish_cascade_input_with_effects(effects, node, old_cascade_input);- self.counters.bump(Counter::RetainedMatchAnswerDeltaPatches);- let emit = patch.always_emit_for(node);- if !emit {- self.counters.bump(Counter::RetainedMatchAnswerPatchStops);- }- return Some(RetainedAnswerPatchOutcome {- identity_preserved: true,- emit,- incremental_cascade_answer: None,- });- }-- // Nodes sharing the same retained identity, compact identity, and consolidated delta- // content share the entire transition: the answer content, the guards below, the compact- // reduction, and the stop verdict are all node-independent for comparable document-scope- // answers under one patch's fixed cascade orders. A stopping transition therefore runs- // once per cohort; every further member is one column store. A container-gated rule- // decides for each node over its own containers, so an answer holding one is not shared.- let answer_is_gated = retained- .iter()- .map(|entry| entry.rule)- .chain(deltas.iter().map(|delta| delta.rule))- .any(|rule| self.program.rule_is_gated_by_container_query(rule));- let memo_key = (!patch.always_emit_for(node)- && !orders_shifted- && !answer_is_gated- && !self.node_has_element_declaration_input(node))- .then(|| Self::retained_answer_delta_memo_key(old_identity, old_cascade_input, deltas));- if let Some(key) = &memo_key- && let Some(entry) = patch.delta_memo.get(key)- && Self::retained_answer_delta_memo_entry_matches(entry, deltas)- && let transition = &entry.transition- && self.set_pending_answer_identity(effects, node, transition.new_answer)- {- self.counters.bump(Counter::RetainedMatchAnswerDeltaMemoHits);- let stopped =- transition.new_cascade_input == old_cascade_input && !self.record_rolls_back_substitution(node);- if let Some((state, version)) = transition.winner_state {- let _ = effects.winners.set(&mut self.winner_groups, node, state, version);- }- // Pseudo-element rows are independent of the element's sparse winner row.- for &(pseudo, state) in &transition.pseudo_winner_states {- let _ =- effects- .winners- .set_pseudo(&mut self.winner_groups, node, pseudo, state, self.program.version());- }- self.publish_cascade_input_with_effects(effects, node, transition.new_cascade_input);- self.counters.bump(Counter::RetainedMatchAnswerDeltaPatches);- if stopped {- self.counters.bump(Counter::RetainedMatchAnswerPatchStops);- return Some(RetainedAnswerPatchOutcome {- identity_preserved: true,- emit: false,- incremental_cascade_answer: None,- });- }- self.counters.bump(Counter::MatchAnswerChanges);- let incremental_cascade_answer = transition.winners_updated.then_some(IncrementalCascadeAnswer {- node,- cascade_input: transition.new_cascade_input,- matches: None,- cascade_winners_are_complete: transition.cascade_winners_are_complete,- });- return Some(RetainedAnswerPatchOutcome {- identity_preserved: false,- emit: true,- incremental_cascade_answer,- });- }-- let retained = self.match_answers.retained_answer(old_identity)?;- let (answer, applied) = self.retained_answer_after_deltas(node, patch, retained, deltas)?;-- if !orders_shifted && self.retained_match_deltas_cannot_change_cascade(effects, node, retained, deltas) {- self.remember_prepared_retained_match_answer_with_truth_with_effects(effects, node, answer, None);- self.publish_cascade_input_with_effects(effects, node, old_cascade_input);- self.counters.bump(Counter::RetainedMatchAnswerDeltaPatches);- self.counters.add(Counter::RetainedMatchAnswerDeltaEntries, applied);- if !patch.always_emit_for(node) {- self.counters.bump(Counter::RetainedMatchAnswerPatchStops);- }- if let Some(key) = memo_key- && let Some(new_identity) = effects.answer_identity(&self.retained_match_answers, node)- {- let winner_state = match effects- .winners- .view(&self.winner_groups)- .lookup(WinnerGroupKey::current(node, self.program.version()))- {- Lookup::Known(&(state, version)) => Some((state, version)),- Lookup::KnownAbsent | Lookup::Missing(_) => None,- };- let pseudo_winner_states = self.settled_pseudo_winner_states(effects, node);- Self::remember_retained_answer_delta_transition(- patch,- key,- deltas,- RetainedAnswerDeltaTransition {- new_answer: new_identity,- new_cascade_input: old_cascade_input,- winner_state,- pseudo_winner_states: pseudo_winner_states.into_boxed_slice(),- winners_updated: false,- cascade_winners_are_complete: false,- },- );- }- return Some(RetainedAnswerPatchOutcome {- identity_preserved: true,- emit: patch.always_emit_for(node),- incremental_cascade_answer: None,- });- }-- let mut materialized: Vec<RuleMatch> = Vec::with_capacity(answer.len());- for &entry in &answer {- let cascade_order = patch- .dispatch- .cascade_order_for_entry(entry.rule, entry.program, entry.entry)?;- materialized.push(entry.materialize(node, &self.programs, cascade_order)?);- }- let materialized = self.in_cascade_order(materialized, false);- let cascade_winners_are_complete =- self.cascade_winner_inventory_is_complete_in_transaction(effects, &materialized, node);-- verify_match_answer_against_cold(self, &materialized, node, "a retained match answer delta");-- self.remember_prepared_retained_match_answer_with_truth_with_effects(effects, node, answer, None);- let cascade_winners_updated =- self.apply_cascade_winner_match_deltas(effects, node, &materialized, deltas, &mut patch.cascade_candidates);- let mut new_input = materialized;- if !(cascade_winners_updated- && cascade_winners_are_complete- && self.compact_matches_from_updated_winners(effects, node, &mut new_input))- {- self.compact_matches_for_cascade_with_scratch(- effects,- &mut new_input,- false,- None,- &mut patch.cascade_compaction_workspace,- );- }- let new_cascade_input = self.intern_cascade_input(&new_input);- let changed = old_cascade_input != new_cascade_input;- if changed {- self.counters.bump(Counter::MatchAnswerChanges);- }- self.publish_cascade_input_with_effects(effects, node, new_cascade_input);- self.counters.bump(Counter::RetainedMatchAnswerDeltaPatches);- self.counters.add(Counter::RetainedMatchAnswerDeltaEntries, applied);- let emit =- patch.always_emit_for(node) || changed || orders_shifted || self.record_rolls_back_substitution(node);- if !emit {- self.counters.bump(Counter::RetainedMatchAnswerPatchStops);- }- // The whole transition is node-independent for the cohort: remember the new answer- // identity, the compact identity, and the settled winner state, so every further member- // replays by column stores whether the transition stopped or emitted.- if let Some(key) = memo_key- && let Some(new_identity) = effects.answer_identity(&self.retained_match_answers, node)- {- let winner_state = match effects- .winners- .view(&self.winner_groups)- .lookup(WinnerGroupKey::current(node, self.program.version()))- {- Lookup::Known(&(state, version)) => Some((state, version)),- Lookup::KnownAbsent | Lookup::Missing(_) => None,- };- let pseudo_winner_states = self.settled_pseudo_winner_states(effects, node);- Self::remember_retained_answer_delta_transition(- patch,- key,- deltas,- RetainedAnswerDeltaTransition {- new_answer: new_identity,- new_cascade_input,- winner_state,- pseudo_winner_states: pseudo_winner_states.into_boxed_slice(),- winners_updated: cascade_winners_updated,- cascade_winners_are_complete,- },- );- }- Some(RetainedAnswerPatchOutcome {- identity_preserved: false,- emit,- incremental_cascade_answer: (emit && cascade_winners_updated).then(|| IncrementalCascadeAnswer {- node,- cascade_input: new_cascade_input,- matches: Some(new_input.into_boxed_slice()),- cascade_winners_are_complete,- }),- })- }-- /// Re-derive the affected rules' matches at one node through the shared filtered- /// interpreter: the shared prefix states answer every prefix-covered entry from one- /// transition per node, the shared workspace carries relation and sibling-prefix caches- /// across nodes, and the dispatch narrows the rest. `None` means exact evaluation could not- /// complete, which retires the answer.- pub(super) fn filtered_patch_replacement(- &mut self,- node: StyleNodeID,- patch: &mut RetainedAnswerPatch,- narrowed_keys: Option<&[(RuleID, SelectorProgramID)]>,- ) -> Option<Vec<RuleMatch>> {- let affected_keys: &[(RuleID, SelectorProgramID)] = narrowed_keys.unwrap_or(&patch.rule_keys);- self.counters.bump(Counter::SelectorTruthRepairUpqueries);- let mut matches = RuleMatches::new();- let prefix_caches = std::sync::Arc::clone(&patch.prefix_caches);- let mut caches = prefix_caches.borrow_mut();- let mut states = caches- .states- .lookup_mut(patch.scope_program)- .sparse()- .expect("prefix rows are prepared before answer patching");- let interpreter = BatchMatcher::new(- &self.tree,- self.facts.primary(),- &patch.dispatch,- &self.programs,- &self.program,- )- .with_rule_filter(affected_keys);- let result = interpreter.match_node_collecting_requests(- node,- &mut matches,- &self.counters,- BatchMatchState {- match_workspace: Some(&mut patch.match_workspace),- witness_effects: None,- dispatch_workspace: &mut patch.dispatch_workspace,- requests: None,- completed: None,- prefix_states: Some((&mut states, &mut patch.prefix_context)),- deferred_prefix_matches: None,- },- );- let _ = states;-- if result.result.is_err() {- matches.release();- return None;- }- let replacement = matches.take();- Some(replacement)- }-- /// Patch one retained exact answer by re-evaluating only the rules reached by this transaction.- ///- /// `None` means the optional old side was absent or exact evaluation could not complete. The- /// caller then retires the answer and publishes an ordinary exact reaction.- pub(super) fn patch_retained_match_answer(- &mut self,- effects: &mut AnswerEffects,- node: StyleNodeID,- patch: &mut RetainedAnswerPatch,- truth_patch: SelectorTruthPatch<'_>,- ) -> Option<RetainedAnswerPatchOutcome> {- let old_identity = *self.retained_match_answers.lookup(node).sparse().ok()?;- self.match_answers.retained_answer(old_identity)?;- let old_cascade_input = effects.cascade_input(&self.retained_match_answers, node)?;- if !self.match_answer_is_comparable_across_elements(node) {- return None;- }- if let SelectorTruthPatch::Direct(deltas) = truth_patch- && let Some(changed) =- self.apply_retained_match_answer_deltas(effects, node, patch, old_identity, old_cascade_input, deltas)- {- return Some(changed);- }- let retained = self.match_answers.retained_answer(old_identity)?;- let mixed_deltas = match truth_patch {- SelectorTruthPatch::Refresh { deltas, .. } | SelectorTruthPatch::Attributed { deltas, .. } => Some(deltas),- SelectorTruthPatch::Full | SelectorTruthPatch::Direct(_) => None,- };- // Materializing the adjusted base has a fixed compact-answer copy cost. Require at least- // two avoided matcher queries so small mixed patches keep their cheaper existing path.- let delta_base = if patch.cascade_update_properties.is_empty() {- mixed_deltas.filter(|deltas| deltas.len() >= 2).and_then(|deltas| {- self.retained_answer_after_deltas(node, patch, retained, deltas)- .map(|(answer, _)| answer)- })- } else {- None- };- // The routes that planned this node named exactly these affected rules, so only they can- // have changed truth here; every other affected rule was proven unchanged on this node by- // its own narrowing. The filtered evaluation shrinks accordingly.- let narrowed_keys: Option<Vec<(RuleID, SelectorProgramID)>> = match truth_patch {- SelectorTruthPatch::Full => None,- SelectorTruthPatch::Direct(deltas) => Some(- deltas- .iter()- .map(|delta| (delta.rule, self.programs.entry_location(delta.entry).0))- .collect(),- ),- SelectorTruthPatch::Refresh { deltas, refreshes } => Some(match delta_base.is_some() {- true => refreshes- .iter()- .filter_map(|refresh| {- refresh- .rule- .map(|(rule, entry)| (rule, self.programs.entry_location(entry).0))- })- .collect(),- false => deltas- .iter()- .map(|delta| (delta.rule, self.programs.entry_location(delta.entry).0))- .chain(refreshes.iter().filter_map(|refresh| {- refresh- .rule- .map(|(rule, entry)| (rule, self.programs.entry_location(entry).0))- }))- .collect(),- }),- SelectorTruthPatch::Attributed {- deltas,- refreshes,- rules,- } => Some(match delta_base.is_some() {- true => refreshes- .iter()- .filter_map(|refresh| {- refresh- .rule- .map(|(rule, entry)| (rule, self.programs.entry_location(entry).0))- })- .chain(- rules- .iter()- .map(|&(rule, entry)| (rule, self.programs.entry_location(entry).0)),- )- .collect(),- false => deltas- .iter()- .map(|delta| (delta.rule, self.programs.entry_location(delta.entry).0))- .chain(refreshes.iter().filter_map(|refresh| {- refresh- .rule- .map(|(rule, entry)| (rule, self.programs.entry_location(entry).0))- }))- .chain(- rules- .iter()- .map(|&(rule, entry)| (rule, self.programs.entry_location(entry).0)),- )- .collect(),- }),- }- .map(|mut keys: Vec<_>| {- keys.retain(|key| patch.rule_keys.binary_search(key).is_ok());- keys.sort_unstable();- keys.dedup();- keys- });- if let Some(keys) = narrowed_keys.as_deref() {- self.counters.bump(Counter::RetainedMatchAnswerFilteredPatches);- if keys.is_empty() && patch.cascade_update_properties.is_empty() && !patch.orders_shifted_for(retained) {- if let Some(deltas) = mixed_deltas- && delta_base.is_some()- {- return self.apply_retained_match_answer_deltas(- effects,- node,- patch,- old_identity,- old_cascade_input,- deltas,- );- }- // Nothing this transaction affects reached the node through a rule-naming route.- self.publish_cascade_input_with_effects(effects, node, old_cascade_input);- self.counters.bump(Counter::RetainedMatchAnswerPatches);- if !patch.always_emit_for(node) {- self.counters.bump(Counter::RetainedMatchAnswerPatchStops);- }- return Some(RetainedAnswerPatchOutcome {- identity_preserved: true,- emit: patch.always_emit_for(node),- incremental_cascade_answer: None,- });- }- }-- self.facts.primary().row_of(node)?;- // One filtered cold match answers the affected rules through the same machinery a full- // match uses; both the unchanged-set stop and the full patch below consume its result.- let replacement = self.filtered_patch_replacement(node, patch, narrowed_keys.as_deref())?;- let retained = self.match_answers.retained_answer(old_identity)?;- let affected_keys: &[(RuleID, SelectorProgramID)] = narrowed_keys.as_deref().unwrap_or(&patch.rule_keys);- let retained_base: &[RetainedRuleMatch] = delta_base.as_deref().unwrap_or(retained.as_ref());-- // Reuse the replacement allocation and append only old entries which survive into the- // repaired answer. The compact retained slice is the old side for delta derivation below,- // so no materialized old snapshot is needed.- // Both inputs are ordered by (rule, program), so find survivors with a merge walk.- let mut affected_index = 0;- let unaffected = retained_base.iter().filter(move |entry| {- let key = (entry.rule, entry.program);- while affected_keys- .get(affected_index)- .is_some_and(|affected| *affected < key)- {- affected_index += 1;- }- affected_keys.get(affected_index) != Some(&key)- });- let mut patched_answer = replacement;- patched_answer.reserve_exact(unaffected.clone().count());- for &entry in unaffected {- let cascade_order = patch- .dispatch- .cascade_order_for_entry(entry.rule, entry.program, entry.entry)?;- patched_answer.push(entry.materialize(node, &self.programs, cascade_order)?);- }- // A refresh is a typed request for exact old/new truth, not an alternate match-answer- // update path. Turn the repaired relation into signed entry deltas and apply those through- // the same authoritative operator as routes which had complete facts during planning.- let repair_deltas = repaired_selector_truth_deltas(node, retained, &mut patched_answer, &self.programs);- if let Some((repair_deltas, changed)) = repair_deltas.as_deref().and_then(|repair_deltas| {- self.apply_retained_match_answer_deltas(- effects,- node,- patch,- old_identity,- old_cascade_input,- repair_deltas,- )- .map(|changed| (repair_deltas, changed))- }) {- for delta in repair_deltas {- self.counters.bump(match delta.change {- SetChange::Added => Counter::SelectorTruthRepairAdditions,- SetChange::Removed => Counter::SelectorTruthRepairRemovals,- });- }- return Some(changed);- }-- let patched_answer = self.in_cascade_order(patched_answer, false);-- verify_match_answer_against_cold(self, &patched_answer, node, "a retained match answer patch");-- // Most patches end where they began: the filtered match returns exactly the entries it- // displaced. An identical answer keeps its stored cascade input, so skip re-deriving and- // re-interning its cascade expansion.- let retained = self.match_answers.retained_answer(old_identity)?;- let matches_retained_answer = patched_answer.len() == retained.len()- && patched_answer.iter().all(|entry| {- retained- .binary_search(&RetainedRuleMatch::from_rule_match(*entry))- .is_ok()- });- let orders_shifted = patch.orders_shifted_for(retained)- || (patch.orders_shifted- && patched_answer- .iter()- .any(|entry| patch.cascade_update_rules.binary_search(&entry.rule).is_ok()));- if matches_retained_answer && !orders_shifted {- self.publish_cascade_input_with_effects(effects, node, old_cascade_input);- self.counters.bump(Counter::RetainedMatchAnswerPatches);- let emit = patch.always_emit_for(node);- if !emit {- self.counters.bump(Counter::RetainedMatchAnswerPatchStops);- }- return Some(RetainedAnswerPatchOutcome {- identity_preserved: true,- emit,- incremental_cascade_answer: None,- });- }-- self.remember_retained_match_answer_with_effects(effects, node, &patched_answer);- let mut new_input = patched_answer;- self.compact_matches_for_cascade_with_scratch(- effects,- &mut new_input,- false,- None,- &mut patch.cascade_compaction_workspace,- );- let new_cascade_input = self.intern_cascade_input(&new_input);- let changed = old_cascade_input != new_cascade_input;- if changed {- self.counters.bump(Counter::MatchAnswerChanges);- }- self.publish_cascade_input_with_effects(effects, node, new_cascade_input);- self.counters.bump(Counter::RetainedMatchAnswerPatches);- let emit =- patch.always_emit_for(node) || changed || orders_shifted || self.record_rolls_back_substitution(node);- if !emit {- self.counters.bump(Counter::RetainedMatchAnswerPatchStops);- }- Some(RetainedAnswerPatchOutcome {- identity_preserved: !changed && !orders_shifted,- emit,- incremental_cascade_answer: None,- })- }-- /// Name one ask's answer so the cascade can share its expansion within this transaction.- #[cfg(test)]- pub(super) fn remember_cascade_input(&mut self, node: StyleNodeID, matches: &[RuleMatch]) {- let mut effects = AnswerEffects::default();- self.remember_cascade_input_with_effects(&mut effects, node, matches);- self.install_answer_effects(effects);- }-- pub(super) fn remember_cascade_input_with_effects(- &mut self,- effects: &mut AnswerEffects,- node: StyleNodeID,- matches: &[RuleMatch],- ) {- if !self.match_answer_is_comparable_across_elements(node) {- effects.forget_cascade_input(node, &mut self.match_answers);- return;- }- let cascade_input = self.intern_cascade_input(matches);- self.publish_cascade_input_with_effects(effects, node, cascade_input);- }-- pub(super) fn intern_cascade_input(&mut self, matches: &[RuleMatch]) -> MatchAnswerID {- // The catalog converts matches to RetainedRuleMatch before canonicalizing them. That- // representation already omits the element identity and absolute cascade rank, so cloning,- // normalizing and sorting RuleMatch here would canonicalize fields the catalog discards.- let identity = self.match_answers.intern(matches);- let reused = self.match_answers.has_cascade_reference(identity);- self.counters.bump(if reused {- Counter::MatchAnswerSignatureReuses- } else {- Counter::MatchAnswerSignatures- });- identity- }-- pub fn match_element(&mut self, node: StyleNodeID) -> Result<Vec<RuleMatch>, Incomplete> {- self.match_element_for_purpose(node, false)- }-- /// Match one element and discard rules that cannot contribute to its cascade.- pub fn match_element_for_cascade(&mut self, node: StyleNodeID) -> Result<Vec<RuleMatch>, Incomplete> {- self.match_element_for_purpose(node, true)- }-- pub(super) fn match_element_for_purpose(- &mut self,- node: StyleNodeID,- compact_for_cascade: bool,- ) -> Result<Vec<RuleMatch>, Incomplete> {- self.match_element_for_purpose_with_compact_answer(- node,- compact_for_cascade,- CompletionExactness::AllowPruning,- None,- None,- )- }-- pub(super) fn complete_published_match_answer(- &mut self,- node: StyleNodeID,- retained_answer_dispatch: Option<&RuleDispatch>,- ) -> Result<PublishedMatchAnswer, Incomplete> {- self.prepare_scope_programs_for_nodes([node]);- let mut traversal = self.batch_matching_traversal.take();- let mut effects = traversal- .as_mut()- .map(|traversal| std::mem::take(&mut traversal.answer_effects))- .unwrap_or_default();- let result = self.complete_published_match_answer_in_traversal(- &mut effects,- node,- traversal.as_deref_mut(),- retained_answer_dispatch,- );- if traversal.is_none() {- self.install_witness_effects();- }- if let Some(traversal) = traversal.as_mut() {- traversal.answer_effects = effects;- } else if result.is_ok() {- self.install_answer_effects(effects);- } else {- effects.release_pending_all(&mut self.match_answers, &mut self.winner_groups);- }- self.batch_matching_traversal = traversal;- result- }-- pub(super) fn complete_published_match_answer_in_traversal(- &mut self,- effects: &mut AnswerEffects,- node: StyleNodeID,- traversal: Option<&mut BatchMatchingTraversal>,- retained_answer_dispatch: Option<&RuleDispatch>,- ) -> Result<PublishedMatchAnswer, Incomplete> {- if !self.match_answer_is_retainable(node) {- effects.forget_answer(node, &mut self.match_answers);- }- let tree_scope = self.tree.tree_scope(node);- let scoped_dispatch = (tree_scope != TreeScopeID::DOCUMENT).then(|| self.prepared_scope_program(tree_scope).1);- let retained_answer_dispatch = scoped_dispatch.or(retained_answer_dispatch);- let retained_answer = retained_answer_dispatch.and_then(|dispatch| {- let retained = self.retained_match_answer_with_effects(effects, node).sparse().ok()?;- let exact_answer = retained- .iter()- .copied()- .map(|entry| {- let cascade_order = dispatch.cascade_order_for_entry(entry.rule, entry.program, entry.entry)?;- entry.materialize(node, &self.programs, cascade_order)- })- .collect::<Option<Vec<_>>>()?;- let cascade_winners_are_complete =- self.cascade_winner_inventory_is_complete_in_transaction(effects, &exact_answer, node);- Some((exact_answer, cascade_winners_are_complete))- });- let (matches, cascade_winners_are_complete, compact_answer) =- if let Some((exact_answer, cascade_winners_are_complete)) = retained_answer {- let answer = self.matches_for_cascade(effects, exact_answer, false, Some(node));- self.remember_cascade_input_with_effects(effects, node, &answer);- self.counters.bump(Counter::RetainedMatchAnswerReuses);- (answer, cascade_winners_are_complete, None)- } else {- let mut compact_answer = None;- let mut cascade_winners_are_complete = false;- let answer = self.match_element_in_traversal(- effects,- node,- true,- CompletionExactness::Exact,- traversal,- Some(&mut compact_answer),- Some(&mut cascade_winners_are_complete),- );- let answer = answer?;- (answer, cascade_winners_are_complete, compact_answer)- };- let cascade_input = effects.cascade_input(&self.retained_match_answers, node);- Ok(PublishedMatchAnswer {- node,- cascade_input,- matches: compact_answer.is_none().then(|| matches.into_boxed_slice()),- cascade_winners_are_complete,- })- }-- /// A row whose selectors and declarations did not change keeps its exact cascade input and- /// current winner rows instead of compacting the same matches again.- pub(super) fn reuse_published_match_answer(- &mut self,- effects: &mut AnswerEffects,- node: StyleNodeID,- ) -> Option<PublishedMatchAnswer> {- effects- .winners- .view(&self.winner_groups)- .token_for(WinnerGroupKey::current(node, self.program.version()))- .sparse()- .ok()?;- if effects- .winners- .view(&self.winner_groups)- .pseudo_states(node)- .any(|(_, version, _, current)| version != self.program.version() || !current)- {- return None;- }- let Some(cascade_input) = effects.cascade_input(&self.retained_match_answers, node) else {- self.computed_group_sets.assigned_style_record(node)?;- // OPTIMIZATION: An answer holding rules of another tree scope, such as a shadow host's or a slotted- // element's, has no reusable document cascade identity, and neither does one whose input- // this flush dropped. Their current winner rows are sufficient for engine computation; a- // host computation can match on demand.- self.counters.bump(Counter::DeferredCascadeCompletions);- return Some(PublishedMatchAnswer {- node,- cascade_input: None,- matches: None,- cascade_winners_are_complete: false,- });- };- self.match_answers.answer(cascade_input)?;- let retained = self.retained_match_answer_with_effects(effects, node).sparse().ok()?;- let cascade_winners_are_complete = self.tree.tree_scope(node) == TreeScopeID::DOCUMENT- && retained.iter().all(|entry| {- entry.tree_scope == TreeScopeID::DOCUMENT- && !self.program.rule_is_gated_by_container_query(entry.rule)- && self.program.declarations_are_complete_for(entry.rule)- })- && self.facts.element_custom_declarations(node).is_empty();- self.counters.bump(Counter::RetainedMatchAnswerReuses);- Some(PublishedMatchAnswer {- node,- cascade_input: Some(cascade_input),- matches: None,- cascade_winners_are_complete,- })- }-- /// Complete a node from a matching node's already compacted cascade input and winner rows.- pub(super) fn complete_published_match_answer_from_cascade_input(- &mut self,- effects: &mut AnswerEffects,- node: StyleNodeID,- source: StyleNodeID,- cascade_input: MatchAnswerID,- cascade_winners_are_complete: bool,- ) -> Option<PublishedMatchAnswer> {- // Both nodes use this completion batch's document dispatch. The source already proved- // this answer, and the catalog can materialize it if a consumer needs individual matches.- // Most consumers use the cascade identity directly, so keep it shared until then.- self.match_answers.answer(cascade_input)?;- let published_rows =- effects- .winners- .copy_node_rows(&mut self.winner_groups, source, node, self.program.version())?;-- self.counters- .add(Counter::CascadeNodeHandlesPublished, published_rows as u64);- self.publish_cascade_input_with_effects(effects, node, cascade_input);- Some(PublishedMatchAnswer {- node,- cascade_input: Some(cascade_input),- matches: None,- cascade_winners_are_complete,- })- }-- pub(super) fn has_no_element_declarations(&self, node: StyleNodeID) -> bool {- self.facts.element_custom_declarations(node).is_empty()- && ElementDeclarationKind::ALL- .iter()- .all(|&kind| self.facts.element_declared_properties(node, kind).is_empty())- }-- /// Whether nodes with this exact answer can share one node's completed cascade: not when the- /// answer holds a container-gated rule, whose conditions decide for each node over its own- /// containers.- pub(super) fn shared_cascade_completion_is_node_independent(&self, answer: MatchAnswerID) -> bool {- self.match_answers.answer(answer).is_some_and(|full| {- !full- .iter()- .any(|matched| self.program.rule_is_gated_by_container_query(matched.rule))- })- }-- /// Sharing avoids collecting and ordering the full declaration candidates. The- /// copied winner rows refer to interned states, so retained declarations do not- /// need to be discounted from the work saved by sharing.- pub(super) fn shared_cascade_completion_is_profitable(&self, answer: MatchAnswerID) -> bool {- let Some(full) = self.match_answers.answer(answer) else {- return false;- };- full.iter()- .map(|matched| self.program.declared_properties_of(matched.rule).len())- .sum::<usize>()- >= MIN_SHARED_CASCADE_COMPLETION_DECLARATIONS- }-- /// Complete the transaction output over nodes added by the style consumer's inheritance- /// closure. The active traversal owns the current cascade orders for retained answers, so lend- /// them to the same completion path used before publication. A retained miss runs exact- /// matching here, before the closure node is handed to style computation.- pub(super) fn retained_closure_cascade_input(- &self,- effects: &AnswerEffects,- node: StyleNodeID,- ) -> Option<MatchAnswerID> {- let cascade_input = effects.cascade_input(&self.retained_match_answers, node)?;- let retained = self.match_answers.answer(cascade_input)?;- let winners = effects.winners.view(&self.winner_groups);- if !matches!(- winners.token_for(WinnerGroupKey::current(node, self.program.version())),- Lookup::Known(_)- ) {- return None;- }- // The node's pseudo-element rows stand for the retained answer as its element row does: a row- // from an older program, or one whose priorities went stale, is not what the answer derives now.- if winners- .pseudo_states(node)- .any(|(_, version, _, current)| version != self.program.version() || !current)- {- return None;- }- for matched in retained.iter() {- if matched.tree_scope != TreeScopeID::DOCUMENT- || self.program.rule_is_gated_by_container_query(matched.rule)- || !self.program.declarations_are_complete_for(matched.rule)- {- return None;- }- let entry = self- .programs- .get(matched.program)- .entries()- .get(matched.entry as usize)?;- if entry.scope_root.is_some() {- return None;- }- }- Some(cascade_input)- }-- pub(super) fn retained_cascade_input_is_exact(- &mut self,- effects: &AnswerEffects,- node: StyleNodeID,- cascade_input: MatchAnswerID,- ) -> bool {- let Ok((full_answer, verification_winner_groups)) = self.exact_cascade_answer_for_verification(node) else {- return false;- };- let prepared_answer = prepare_retained_match_answer(full_answer.into_iter());- let answer_is_equal = self- .match_answers- .answer(cascade_input)- .is_some_and(|retained_answer| retained_answer.as_ref() == prepared_answer);- let winner_rows_are_equal = effects- .winners- .view(&self.winner_groups)- .node_rows_are_semantically_equal(&verification_winner_groups, node, self.program.version());- answer_is_equal && winner_rows_are_equal- }-- /// Whether any entry of the answer observes sibling or positional relations, whose truth is- /// maintained state in the prefix automaton.- pub(super) fn answer_observes_sibling_relations(&self, input: MatchAnswerID) -> bool {- let Some(rows) = self.match_answers.answer(input) else {- return true;- };- rows.iter().any(|row| {- self.programs- .get(row.program)- .entries()- .get(row.entry as usize)- .is_none_or(|entry| entry.observes_sibling_relation())- })- }-- /// Prove that an added-only transition between two compact answers cannot change any cascade- /// winner, by checking every added rule's declared properties against the node's previously- /// published winner rows: O(delta) instead of a cold re-derivation, so it holds even where- /// the winner inventory is incomplete. Any gap answers false: a removal, a pseudo-targeted or- /// scoped or container-gated added rule, an added rule whose declaration list is incomplete- /// (custom properties), or provenance the previous state cannot answer for.- pub(super) fn answer_transition_cannot_change_cascade(- &mut self,- node: StyleNodeID,- previous_input: MatchAnswerID,- current_input: MatchAnswerID,- ) -> bool {- // Identity equality is NOT a proof: a stale retained answer compares equal to itself. Nor- // is an added losing rule harmless to a record that rolled back below its winners.- if previous_input == current_input- || self.record_rolls_back_substitution(node)- || self.backed_host_pseudo_element(node).is_some()- {- return false;- }- let target = computed::ComputedStyleTarget::new(node, u8::MAX);- let Some((previous_generation, previous_state)) = self.computed_group_sets.cascade_state(target) else {- self.counters.bump(Counter::TransitionProofNoPreviousState);- return false;- };- if previous_generation != self.winner_groups.generation() {- self.counters.bump(Counter::TransitionProofGenerationGap);- return false;- }- let Some(previous_rows) = self.match_answers.answer(previous_input) else {- self.counters.bump(Counter::TransitionProofMissingAnswer);- return false;- };- let Some(current_rows) = self.match_answers.answer(current_input) else {- self.counters.bump(Counter::TransitionProofMissingAnswer);- return false;- };- if !self.facts.element_custom_declarations(node).is_empty() {- self.counters.bump(Counter::TransitionProofElementDeclarations);- return false;- }- let (mut i, mut j) = (0, 0);- while i < previous_rows.len() || j < current_rows.len() {- let added = match (previous_rows.get(i), current_rows.get(j)) {- (Some(previous), Some(current)) if previous == current => {- i += 1;- j += 1;- continue;- }- (Some(previous), Some(current)) if previous < current => {- let _ = previous;- self.counters.bump(Counter::TransitionProofRemoval);- return false;- }- (Some(_), Some(current)) => {- j += 1;- *current- }- (Some(_), None) => {- self.counters.bump(Counter::TransitionProofRemoval);- return false;- }- (None, Some(current)) => {- j += 1;- *current- }- (None, None) => unreachable!(),- };- if added.tree_scope != TreeScopeID::DOCUMENT- || self.program.rule_is_gated_by_container_query(added.rule)- || !self.program.declarations_are_complete_for(added.rule)- {- self.counters.bump(Counter::TransitionProofUnsafeRule);- return false;- }- let Some(entry) = self.programs.get(added.program).entries().get(added.entry as usize) else {- self.counters.bump(Counter::TransitionProofUnsafeRule);- return false;- };- if entry.pseudo_element.is_some() || entry.scope_root.is_some() {- self.counters.bump(Counter::TransitionProofPseudoOrScope);- return false;- }- if !self.rule_has_complete_element_winners(added.rule, entry) {- self.counters.bump(Counter::TransitionProofElementWinnerGap);- return false;- }- for declared in self.program.declared_properties_of(added.rule) {- if matches!(- declared.operator,- CascadeOperator::Revert | CascadeOperator::RevertLayer- ) {- self.counters.bump(Counter::TransitionProofOperatorOrContinuation);- return false;- }- let Some(winner) = self.winner_groups.winner_in_state(previous_state, declared.property) else {- self.counters.bump(Counter::TransitionProofWinnerGap);- return false;- };- if winner.key.continuation != CascadeContinuationID::default() {- self.counters.bump(Counter::TransitionProofOperatorOrContinuation);- return false;- }- if winner.source == WinnerSource::ExactCascade {- self.counters.bump(Counter::TransitionProofWinnerGap);- return false;- }- let priority = self.cascade_priority_of(- node,- added.rule,- added.tree_scope,- entry.specificity,- added.scope_proximity,- declared.important,- );- if priority >= winner.priority {- self.counters.bump(Counter::TransitionProofPriorityWin);- return false;- }- }- }- self.counters.bump(Counter::TransitionProofConfirmed);- true- }-- pub(super) fn verify_retained_cascade_input(- &mut self,- effects: &AnswerEffects,- node: StyleNodeID,- cascade_input: MatchAnswerID,- ) {- assert!(- self.retained_cascade_input_is_exact(effects, node, cascade_input),- "retained cascade identity stop diverged from exact matching"- );- }-- pub fn complete_published_match_answers_for_closure(&mut self, nodes: &[StyleNodeID]) -> Result<(), Incomplete> {- self.prepare_scope_programs_for_nodes(nodes.iter().copied());- let retained_answer_dispatch = self- .batch_matching_traversal- .as_ref()- .and_then(|traversal| traversal.retained_answer_dispatch.clone());- let mut traversal = self.batch_matching_traversal.take();- let mut effects = traversal- .as_mut()- .map(|traversal| std::mem::take(&mut traversal.answer_effects))- .unwrap_or_default();- let mut pending = traversal- .as_mut()- .map(|traversal| std::mem::take(&mut traversal.pending_published))- .unwrap_or_default();- let result = (|| {- let mut completed = 0;- for &node in nodes {- if effects.published_lookup(&pending, node).is_some()- || self.published_match_answers.lookup(node).is_some()- {- continue;- }- let answer = if let Some(cascade_input) = self.retained_closure_cascade_input(&effects, node) {- self.counters.bump(Counter::PublishedClosureRetainedIdentityStops);- // NB: Verify mode proves the identity stop against the full completion on the- // side instead of disabling it; the check's own work must not disturb engine- // &self.counters, so they are restored around it.- verify_style_answer_patch(self, |verifier| {- verifier.verify_retained_cascade_input(&effects, node, cascade_input);- });- PublishedMatchAnswer {- node,- cascade_input: Some(cascade_input),- matches: None,- cascade_winners_are_complete: false,- }- } else {- self.complete_published_match_answer_in_traversal(- &mut effects,- node,- traversal.as_deref_mut(),- retained_answer_dispatch.as_deref(),- )?- };- effects.note_published(node, pending.entries.len());- pending.push(answer, &self.counters);- completed += 1;- }-- self.counters- .add(Counter::PublishedMatchAnswerClosureCompletions, completed);- Ok(())- })();- if traversal.is_none() {- self.install_witness_effects();- }- if let Some(traversal) = traversal.as_mut() {- traversal.pending_published = pending;- traversal.answer_effects = effects;- } else {- self.published_match_answers.append_pending(pending);- self.install_answer_effects(effects);- }- self.batch_matching_traversal = traversal;- result- }-- /// Compare the complete element cascade behind the published base style with the current exact- /// selector transaction. Pseudo-element rows are compared independently before the caller- /// stops the reaction.- pub(super) fn exact_cascade_output_is_unchanged(&self, effects: &AnswerEffects, node: StyleNodeID) -> bool {- // A record that rolled back below its winners holds declarations they do not name.- if self.record_rolls_back_substitution(node) || self.backed_host_pseudo_element(node).is_some() {- return false;- }- let target = computed::ComputedStyleTarget::new(node, u8::MAX);- let Some((previous_generation, previous)) = self.computed_group_sets.cascade_state(target) else {- return false;- };- let current = match effects- .winners- .view(&self.winner_groups)- .token_for(WinnerGroupKey::current(node, self.program.version()))- {- Lookup::Known((current_generation, current)) if current_generation == previous_generation => current,- Lookup::Known(_) | Lookup::KnownAbsent | Lookup::Missing(_) => return false,- };- self.winner_groups.states_are_semantically_equal(previous, current)- }-- /// Consume the complete current answer which the immediately preceding style plan retained.- ///- /// A miss is not an incomplete selector answer. It means this transaction did not publish an- /// answer for the node, so the caller may ask the ordinary exact matcher instead.- #[cfg(test)]- pub(super) fn current_published_answer(&self, node: StyleNodeID) -> Option<&PublishedMatchAnswer> {- Self::published_answer_lookup(- &self.published_match_answers,- self.batch_matching_traversal.as_deref(),- node,- )- .map(|(_, answer)| answer)- }-- /// Publish a driven row's winners again from its retained selector answer, or from a fresh- /// match where that answer is gone. Whether the winners are complete.- pub(super) fn republish_driven_winners(- &mut self,- node: StyleNodeID,- republication: publication::WinnerRepublication,- ) -> bool {- let matches = self.matches_to_republish(node);- debug_assert!(matches.is_some(), "a driven row without the facts to match it");- self.republish_winners_from_matches(node, matches.unwrap_or_default(), republication)- .0- }-- /// Publish new winners from the retained selector answer, matching from published facts when- /// there is none. `None` when neither can say what the node matches; else- /// whether the winners are complete.- pub(super) fn republish_winners_from_answer(- &mut self,- node: StyleNodeID,- republication: publication::WinnerRepublication,- ) -> Option<bool> {- let matches = self.matches_to_republish(node)?;- Some(self.republish_winners_from_matches(node, matches, republication).0)- }-- /// What `republish_winners_from_answer` does beside the record the host styled the node with,- /// outside any batch. Nothing retains the answer of a shadow host, or of a node slotted or- /// exposed into a shadow tree, so the matches its winners came from are published as this- /// update's answer for it, as a flush publishes its rows': what is settled beside the record- /// reads that answer.- pub(super) fn republish_winners_beside_host_record(- &mut self,- node: StyleNodeID,- republication: publication::WinnerRepublication,- ) -> Option<bool> {- let matches = self.matches_to_republish(node)?;- let (complete, matches) = self.republish_winners_from_matches(node, matches, republication);- if !self.match_answer_is_retainable(node) {- self.published_match_answers.publish(- PublishedMatchAnswer {- node,- cascade_input: None,- matches: Some(matches.into_boxed_slice()),- cascade_winners_are_complete: complete,- },- &self.counters,- );- }- Some(complete)- }-- /// Publish the pseudo-element winners again from the retained answer once the element's own- /// row was compared in this flush: the element row and its cascade-input identity stay, and- /// only the pseudo rows derived from the answer are published.- pub(super) fn republish_pseudo_winners_from_retained_answer(- &mut self,- node: StyleNodeID,- _republication: publication::WinnerRepublication,- ) -> Option<()> {- let identity = self.current_answer_identity(node)?;- let answer = Arc::clone(self.match_answers.answer(identity)?);- for entry in answer.iter() {- self.prepare_scope_program(entry.tree_scope);- }- let mut matches = Vec::new();- self.append_catalog_answer(identity, node, None, &mut matches)?;- let mut effects = AnswerEffects::default();- self.matches_for_cascade(&mut effects, matches, true, Some(node));- effects.winners.discard_element_row(&mut self.winner_groups, node);- effects- .winners- .preserve_equal_pseudo_states(&mut self.winner_groups, node);- self.install_answer_effects(effects);- Some(())- }-- /// Publish a driven row's winners from a fresh match, for when its retained answer could not- /// publish them.- pub(super) fn rematch_driven_winners(- &mut self,- node: StyleNodeID,- republication: publication::WinnerRepublication,- ) -> bool {- let matches = self.match_element_for_cascade(node).unwrap_or_default();- self.republish_winners_from_matches(node, matches, republication).0- }-- fn matches_to_republish(&mut self, node: StyleNodeID) -> Option<Vec<RuleMatch>> {- let retained = self.current_answer_identity(node).and_then(|identity| {- let answer = Arc::clone(self.match_answers.answer(identity)?);- for entry in answer.iter() {- self.prepare_scope_program(entry.tree_scope);- }- let mut matches = Vec::new();- self.append_catalog_answer(identity, node, None, &mut matches)?;- Some(matches)- });- match retained {- Some(matches) => Some(matches),- None => self.match_element_for_cascade(node).ok(),- }- }-- /// Whether the winners are complete, and the matches they were published from, compacted for- /// the cascade.- fn republish_winners_from_matches(- &mut self,- node: StyleNodeID,- matches: Vec<RuleMatch>,- _republication: publication::WinnerRepublication,- ) -> (bool, Vec<RuleMatch>) {- // Winners published on their own decide the node's gated rules over its containers as- // they stand, which the record loop checks again once the node's ancestors are settled.- self.container_gates_unheld.remove(&node);- let complete = self.cascade_winner_inventory_is_complete(&matches, Some(node));- let complete_but_for_custom_properties = matches- .iter()- .all(|entry| self.match_is_complete_but_for_custom_properties(node, entry.rule));- let mut effects = AnswerEffects::default();- // The answer's pseudo-element inventory, and the matches its custom-property cascade runs- // over where a record loop reads this transaction's.- let pseudo_style_mask = matches.iter().fold(0_u64, |mask, rule_match| {- mask | rule_match- .pseudo_element- .map(|pseudo| pseudo.kind.0)- .filter(|&kind| kind <= bridge::LAST_SYNTHETIC_PSEUDO_ELEMENT_KIND)- .map_or(0, |kind| 1 << kind)- });- let custom_property_matches = self.batch_custom_property_matches.contains_key(&node).then(|| {- matches- .iter()- .filter(|entry| !self.program.custom_declarations_of(entry.rule).is_empty())- .map(|entry| BatchCustomPropertyMatch {- rule: entry.rule,- tree_scope: entry.tree_scope,- specificity: entry.specificity,- scope_proximity: entry.scope_proximity,- pseudo: entry.pseudo_element.map(|target| target.kind.0),- })- .collect::<Vec<_>>()- });- let compact = self.matches_for_cascade(&mut effects, matches, true, Some(node));- self.remember_cascade_input_with_effects(&mut effects, node, &compact);- self.install_answer_effects(effects);- // A record loop reading this transaction's answers reads the one just published instead.- if let Some(batch) = self.batch_answers_complete_but_for_custom_properties.get_mut(&node) {- *batch = complete_but_for_custom_properties;- }- // The answer the batch named for these matches is not the one republished, so the matches no longer key an- // environment by it.- if let Some(matches) = custom_property_matches {- self.batch_custom_property_matches.insert(node, matches);- self.batch_custom_property_answers.remove(&node);- }- self.computed_group_sets- .set_node_pseudo_style_mask(node, Some(pseudo_style_mask));- let answer_is_incomplete = !complete && !self.cascade_winners_are_complete_but_for_custom_properties(node);- self.computed_group_sets- .set_node_answer_incomplete(node, answer_is_incomplete);- (complete, compact)- }-- pub(super) fn current_answer_identity(&self, node: StyleNodeID) -> Option<MatchAnswerID> {- let effects = self- .batch_matching_traversal- .as_ref()- .map(|traversal| &traversal.answer_effects)- .unwrap_or(&self.published_match_answers.answer_effects);- effects.answer_identity(&self.retained_match_answers, node)- }-- pub(super) fn published_answer_lookup<'a>(- published: &'a PublishedMatchAnswers,- traversal: Option<&'a BatchMatchingTraversal>,- node: StyleNodeID,- ) -> Option<(&'a PublishedMatchAnswers, &'a PublishedMatchAnswer)> {- if let Some(traversal) = traversal- && let Some(answer) = traversal- .answer_effects- .published_lookup(&traversal.pending_published, node)- {- return Some((&traversal.pending_published, answer));- }- published.lookup(node).map(|answer| (published, answer))- }-- pub(super) fn consume_published_match_answer_in_traversal(- &mut self,- effects: &mut AnswerEffects,- node: StyleNodeID,- traversal: Option<&BatchMatchingTraversal>,- ) -> Option<Vec<RuleMatch>> {- let pending = traversal.and_then(|traversal| {- effects- .published_lookup(&traversal.pending_published, node)- .map(|answer| (&traversal.pending_published, answer))- });- let (mut matches, cascade_input) = pending- .or_else(|| {- self.published_match_answers- .lookup(node)- .map(|answer| (&self.published_match_answers, answer))- })- .map_or((None, None), |(published, answer)| {- (- published.matches_for(answer).map(|matches| matches.to_vec()),- answer.cascade_input,- )- });- if matches.is_none()- && let Some(cascade_input) = cascade_input- {- let mut answer = Vec::new();- if self- .append_catalog_answer(cascade_input, node, None, &mut answer)- .is_some()- {- // The catalog canonicalizes rule identities independently of cascade rank.- self.order_matches_in_cascade(&mut answer, false);- matches = Some(answer);- }- }- if let Some(mut matches) = matches {- for entry in &mut matches {- entry.node = node;- }- self.counters.bump(Counter::PublishedMatchAnswerConsumptions);- return Some(matches);- }- None- }-- pub(super) fn current_winner_groups(&self) -> super::cascade::WinnerView<'_> {- self.batch_matching_traversal.as_ref().map_or_else(- || super::cascade::WinnerView::retained(&self.winner_groups),- |traversal| traversal.answer_effects.winners.view(&self.winner_groups),- )- }-- pub(super) fn pseudo_cascade_states_are_unchanged_with_effects(- &self,- effects: &AnswerEffects,- node: StyleNodeID,- ) -> bool {- self.pseudo_cascade_states_are_unchanged_in(node, effects.winners.view(&self.winner_groups))- }-- #[cfg(test)]- pub fn pseudo_cascade_states_are_unchanged(&self, node: StyleNodeID) -> bool {- self.pseudo_cascade_states_are_unchanged_in(node, self.current_winner_groups())- }-- fn pseudo_cascade_states_are_unchanged_in(- &self,- node: StyleNodeID,- winner_groups: super::cascade::WinnerView<'_>,- ) -> bool {- // A pseudo-element record that rolled back below its winners holds declarations they do- // not name.- if self.record_rolls_back_substitution(node) {- return false;- }- let generation = winner_groups.generation();- // A held pseudo style the engine has no record of cannot be vouched for: winner rows and- // computed cascade records are the only witnesses the two arms below can judge, and the- // consumer can hold a computed style with neither. With no witness the answer must be a- // recompute, never a vacuous pass.- let held_kinds_are_witnessed = self.computed_group_sets.assigned_pseudo_kinds(node).all(|kind| {- self.computed_group_sets- .pseudo_retained_cascade_state(node, kind)- .is_some()- || winner_groups- .pseudo_state(- node,- tree::PseudoElementTarget::new(tree::PseudoElementKind(u16::from(kind))),- )- .is_some()- });- let observed_are_current =- self.computed_group_sets- .pseudo_retained_cascade_states(node)- .all(|(pseudo_kind, computed)| {- let pseudo = tree::PseudoElementTarget::new(tree::PseudoElementKind(u16::from(pseudo_kind)));- match winner_groups.token_for(WinnerGroupKey::current_pseudo(node, pseudo, self.program.version()))- {- Lookup::Known((retained_generation, state)) if retained_generation == computed.0 => {- winner_groups.states_are_semantically_equal(computed.1, state)- }- Lookup::Known(_) | Lookup::KnownAbsent | Lookup::Missing(_) => false,- }- });- held_kinds_are_witnessed- && observed_are_current- && winner_groups- .pseudo_states(node)- .filter(|(pseudo, _, _, _)| {- matches!(pseudo.kind.0, 0 | 2 | 3 | 6 | 7 | 8)- || u8::try_from(pseudo.kind.0).ok().is_some_and(|kind| {- self.computed_group_sets- .assigned_pseudo_kinds(node)- .any(|assigned| assigned == kind)- })- })- .all(|(pseudo, version, state, priority_current)| {- // A state with custom declarations resolves them against the registrations as- // well, which move without its rows: it cannot vouch for its environment.- version == self.program.version()- && priority_current- && winner_groups.custom_declarations_of(state) == Default::default()- && u8::try_from(pseudo.kind.0).ok().is_some_and(|pseudo_kind| {- self.computed_group_sets- .pseudo_retained_cascade_states(node)- .find(|(observed_kind, _)| *observed_kind == pseudo_kind)- .map(|(_, state)| state)- .is_some_and(|computed| {- computed.0 == generation- && winner_groups.states_are_semantically_equal(computed.1, state)- })- })- })- }-- pub(super) fn append_exact_matches_in_scope(- &mut self,- node: StyleNodeID,- scope: TreeScopeID,- context: ExactMatchContext,- matches: &mut Vec<exact_matcher::ExactRuleMatch>,- ) -> Result<(), Incomplete> {- let shadow_root = self.scope_root(scope);- let mut matcher = ExactMatcher::new(- &self.tree,- self.facts.committed_for_verification(),- &self.programs,- &self.program,- )- .in_scope(scope)- .with_context(context);- if let Some(shadow_root) = shadow_root {- matcher = matcher.in_shadow_tree(shadow_root);- }- matcher.match_node(node, matches, &self.counters)- }-- /// Match one element from committed facts without consulting derived matching state.- #[cfg(test)]- pub(super) fn match_element_with_exact_matcher(- &mut self,- node: StyleNodeID,- compact_for_cascade: bool,- ) -> Result<Vec<RuleMatch>, Incomplete> {- self.prepare_scope_programs_for_nodes([node]);- let exact_answer = self.exact_match_answer(node)?;- let answer = match compact_for_cascade {- true => {- self.remember_retained_match_answer(node, &exact_answer);- self.matches_for_cascade_immediately(exact_answer, false, Some(node))- }- false => exact_answer,- };- self.remember_cascade_input(node, &answer);- Ok(answer)- }-- pub(super) fn exact_match_answer(&mut self, node: StyleNodeID) -> Result<Vec<RuleMatch>, Incomplete> {- let scope = self.tree.tree_scope(node);- let inner_scope = self- .tree- .shadow_root_of(node)- .and_then(|shadow_root| self.scope_by_root.get(shadow_root).filter(|&inner| inner != scope));- let slotted_scopes: SmallVec<[TreeScopeID; 1]> = self- .scopes_slotted_into(node)- .filter(|&slotted| slotted != scope && Some(slotted) != inner_scope)- .collect();- let part_scopes: SmallVec<[TreeScopeID; 1]> = self- .part_exposure_scopes(node)- .filter(|&exposed| exposed != scope && Some(exposed) != inner_scope && !slotted_scopes.contains(&exposed))- .collect();-- let mut exact = Vec::new();- for_each_matching_scope(scope, inner_scope, &slotted_scopes, &part_scopes, |scope, context| {- self.append_exact_matches_in_scope(node, scope, context, &mut exact)- })?;-- let mut matches = Vec::with_capacity(exact.len());- for matched in exact {- let (_, dispatch) = self.prepared_scope_program(matched.tree_scope);- let cascade_order = dispatch- .cascade_order_for_entry(matched.rule, matched.program, matched.entry)- .expect("every exact rule entry has a cascade rank");- matches.push(RuleMatch {- node: matched.node,- pseudo_element: matched.pseudo_element,- rule: matched.rule,- program: matched.program,- entry: matched.entry,- cascade_order,- specificity: matched.specificity,- tree_scope: matched.tree_scope,- scope_proximity: matched.scope_proximity,- });- }-- let can_have_scope_duplicates = inner_scope.is_some() || !slotted_scopes.is_empty() || !part_scopes.is_empty();- Ok(self.in_cascade_order(matches, can_have_scope_duplicates))- }-- pub(super) fn exact_match_answer_for_verification(- &mut self,- node: StyleNodeID,- ) -> Result<Vec<RuleMatch>, Incomplete> {- self.prepare_scope_programs_for_nodes([node]);- let counters_before_verification = self.counters.clone();- let answer = self.exact_match_answer(node);- self.counters.restore(&counters_before_verification);- answer- }-- pub(super) fn exact_cascade_answer_for_verification(- &mut self,- node: StyleNodeID,- ) -> Result<(Vec<RuleMatch>, WinnerGroups), Incomplete> {- self.prepare_scope_programs_for_nodes([node]);- let counters_before_verification = self.counters.clone();- let exact_answer = match self.exact_match_answer(node) {- Ok(answer) => answer,- Err(incomplete) => {- self.counters.restore(&counters_before_verification);- return Err(incomplete);- }- };- let mut verification_winner_groups = self.winner_groups.verification_copy();-- let mut verification_compaction_scratch = ordering::CascadeCompactionWorkspace::default();-- std::mem::swap(&mut *self.winner_groups, &mut verification_winner_groups);- std::mem::swap(- &mut self.cascade_compaction_scratch,- &mut verification_compaction_scratch,- );- let answer = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {- self.matches_for_cascade_immediately(exact_answer, false, Some(node))- }));- std::mem::swap(- &mut self.cascade_compaction_scratch,- &mut verification_compaction_scratch,- );- std::mem::swap(&mut *self.winner_groups, &mut verification_winner_groups);- self.counters.restore(&counters_before_verification);- match answer {- Ok(answer) => Ok((answer, verification_winner_groups)),- Err(payload) => std::panic::resume_unwind(payload),- }- }-- pub(super) fn match_element_for_purpose_with_compact_answer(- &mut self,- node: StyleNodeID,- compact_for_cascade: bool,- completion_exactness: CompletionExactness,- compact_answer: Option<&mut Option<MatchAnswerID>>,- cascade_winners_are_complete: Option<&mut bool>,- ) -> Result<Vec<RuleMatch>, Incomplete> {- self.prepare_scope_programs_for_nodes([node]);- let mut traversal = self.batch_matching_traversal.take();- let mut effects = traversal- .as_mut()- .map(|traversal| std::mem::take(&mut traversal.answer_effects))- .unwrap_or_default();- if let Some(traversal) = traversal.as_mut()- && let Some(batch) = traversal.batch.as_ref()- {- self.prepare_prefix_rows_for_scope(self.tree.tree_scope(node), batch, &mut traversal.prefix_contexts);- }- let result = self.match_element_in_traversal(- &mut effects,- node,- compact_for_cascade,- completion_exactness,- traversal.as_deref_mut(),- compact_answer,- cascade_winners_are_complete,- );- if traversal.is_none() {- self.install_witness_effects();- }- if let Some(traversal) = traversal.as_mut() {- traversal.answer_effects = effects;- } else if result.is_ok() {- self.install_answer_effects(effects);- } else {- effects.release_pending_all(&mut self.match_answers, &mut self.winner_groups);- }- self.batch_matching_traversal = traversal;- result- }-- #[allow(clippy::too_many_arguments)]- pub(super) fn match_element_in_traversal(- &mut self,- effects: &mut AnswerEffects,- node: StyleNodeID,- compact_for_cascade: bool,- completion_exactness: CompletionExactness,- mut traversal: Option<&mut BatchMatchingTraversal>,- mut compact_answer: Option<&mut Option<MatchAnswerID>>,- mut cascade_winners_are_complete: Option<&mut bool>,- ) -> Result<Vec<RuleMatch>, Incomplete> {- if compact_for_cascade- && traversal- .as_ref()- .and_then(|traversal| effects.published_lookup(&traversal.pending_published, node))- .or_else(|| self.published_match_answers.lookup(node))- .is_some()- && let Some(complete) = cascade_winners_are_complete.as_mut()- {- **complete = traversal- .as_ref()- .and_then(|traversal| effects.published_lookup(&traversal.pending_published, node))- .or_else(|| self.published_match_answers.lookup(node))- .is_some_and(|answer| answer.cascade_winners_are_complete);- }- if compact_for_cascade- && let Some(answer) = self.consume_published_match_answer_in_traversal(effects, node, traversal.as_deref())- {- return Ok(answer);- }- // Exact observations may deliberately ask for matched rules after a style transaction.- // Only a cascade rematch bypasses the complete answer the transaction published.- if compact_for_cascade- && traversal- .as_ref()- .and_then(|traversal| effects.published_lookup(&traversal.pending_published, node))- .or_else(|| self.published_match_answers.lookup(node))- .is_some()- {- self.counters- .bump(Counter::MatchElementCallsDuringPublishedStyleTransaction);- }-- self.counters.bump(Counter::MatchAnswerUpqueries);-- let scope = self.tree.tree_scope(node);- // A host stands outside the tree its own shadow root opens, and `:host` inside that tree- // names it, so the tree's own rules are asked of it as well.- let inner_scope = self- .tree- .shadow_root_of(node)- .and_then(|shadow_root| self.scope_by_root.get(shadow_root).filter(|&inner| inner != scope));- // A slotted element stands outside the tree it is slotted into, and `::slotted()` inside- // that tree names it, so that tree's rules are asked of it as well. A slot is itself a- // slottable, so an element can be re-slotted through several trees, and each of them names- // it: what stands in the flat tree at the end of the chain is the element, not the slots.- let slotted_scopes: SmallVec<[TreeScopeID; 1]> = self- .scopes_slotted_into(node)- .filter(|&slotted| slotted != scope && Some(slotted) != inner_scope)- .collect();- // A part is inside a tree the addressing scope does not decide in, and `::part()` in that- // scope names it. `exportparts` forwards a name outwards one host at a time, and a rule in- // every tree along that chain can address the element - under the name that level exposes it- // by - so each of those scopes is asked, not only the outermost one the exposure names.- let part_scopes: SmallVec<[TreeScopeID; 1]> = self- .part_exposure_scopes(node)- .filter(|&exposed| exposed != scope && Some(exposed) != inner_scope && !slotted_scopes.contains(&exposed))- .collect();-- // A reaction derived while applying the published transaction can extend the C++ pass- // beyond the region whose facts this transaction prepared. Keep using the shared batch- // for covered nodes, but let an unprepared node take the exact adaptive path below.- let prepared_batch_contains_node = traversal- .as_deref()- .and_then(|traversal| traversal.batch.as_ref())- .is_some_and(|batch| batch.row_of(node).is_some());- if prepared_batch_contains_node {- let traversal = traversal.as_deref_mut().unwrap();- let prefix_caches = std::sync::Arc::clone(&traversal.prefix_caches);- let facts = traversal.batch.as_ref().unwrap();- let mut matches = RuleMatches::new();- if compact_for_cascade && verify_selector_truth_derivation_is_enabled() {- matches.enable_selector_truth();- }- // OPTIMIZATION: Identical sheet sets share a scope program, so the prefix automaton's- // answer can be reused across otherwise independent shadow trees.- let can_defer_prefix_matches =- compact_for_cascade && inner_scope.is_none() && slotted_scopes.is_empty() && part_scopes.is_empty();- let mut deferred_prefix_matches = None;- let mut retained_match_answer_is_exact = compact_for_cascade;- let result = for_each_matching_scope(- scope,- inner_scope,- &slotted_scopes,- &part_scopes,- |asked_scope, context| {- let is_primary = context == ExactMatchContext::Ordinary;- self.match_node_in_kept_scope(- node,- asked_scope,- facts,- &mut traversal.dispatch_workspace,- &mut matches,- is_primary.then(|| {- traversal- .ancestor_requirements- .get(self.prepared_scope_program(asked_scope).1)- }),- is_primary.then_some(&prefix_caches),- &mut traversal.prefix_contexts,- Some(&mut traversal.match_workspace),- BatchMatchRetry {- requests: None,- completed: None,- deferred_prefix_matches: (is_primary && can_defer_prefix_matches)- .then_some(&mut deferred_prefix_matches),- answer_is_exact: Some(&mut retained_match_answer_is_exact),- cascade_only: is_primary- && can_defer_prefix_matches- && completion_exactness == CompletionExactness::AllowPruning,- },- )- },- );- let can_have_scope_duplicates =- inner_scope.is_some() || !slotted_scopes.is_empty() || !part_scopes.is_empty();- let mut cascade_input = None;- let mut retained_match_answer = None;- let mut retained_selector_truth = None;- let mut retained_match_answer_reused = false;- let mut retained_match_answer_key_to_remember = None;- let mut cached_cascade_winner_inventory_is_complete = None;- let mut non_prefix_matches = SmallVec::<[RetainedRuleMatch; 16]>::new();- let all = match (result, deferred_prefix_matches) {- (Ok(()), Some(prefix_matches)) => {- if retained_match_answer_is_exact {- retained_selector_truth = matches.take_prepared_selector_truth();- }- let (scope_program, _) = self.prepared_scope_program(scope);- non_prefix_matches.extend(- matches- .as_slice()- .iter()- .copied()- .map(RetainedRuleMatch::from_rule_match),- );- non_prefix_matches.spilled();- non_prefix_matches.sort_unstable();- let non_prefix_hash = super::intern_table::content_hash(non_prefix_matches.as_slice());- let contribution_key = PrefixContributionKey {- program: scope_program,- matches: prefix_matches,- };- let mut newly_materialized_exact_prefix = None;- if retained_match_answer_is_exact && scope == TreeScopeID::DOCUMENT {- let known_exact_prefix = match prefix_caches- .borrow()- .answers- .exact_prefix(&self.match_answers, contribution_key)- {- Lookup::Known((identity, _)) => Some(identity),- Lookup::KnownAbsent => {- unreachable!("exact prefix answers are sparse, never known absent")- }- Lookup::Missing(_) => None,- };- let exact_prefix_identity = match known_exact_prefix {- Some(answer) => answer,- None => {- let mut prefix_rules = RuleMatches::new();- let mut caches = prefix_caches.borrow_mut();- match caches.states.lookup_mut(scope_program) {- Lookup::Known(states) => append_prefix_matches(- &mut prefix_rules,- node,- scope,- self.prepared_scope_program(scope).1,- &self.program,- &self.programs,- states.matches_in(prefix_matches),- &self.counters,- CountRuleMatchEmission::No,- ),- Lookup::KnownAbsent | Lookup::Missing(_) => {- unreachable!("matching retained the scope's prefix states")- }- }- drop(caches);- let prepared = prepare_retained_match_answer(prefix_rules.as_slice().iter().copied());- let identity = prefix_caches.borrow_mut().answers.remember_exact_prefix(- &mut self.match_answers,- scope_program,- prefix_matches,- prepared,- &self.programs,- );- newly_materialized_exact_prefix = Some(prefix_rules);- identity- }- };- let exact_answer_key = PrefixAnswerKey {- prefix_contribution: exact_prefix_identity,- non_prefix_matches: &non_prefix_matches,- non_prefix_hash,- };- let known_exact_answer = match effects- .exact_answer(exact_answer_key)- .map(Lookup::Known)- .unwrap_or_else(|| prefix_caches.borrow().answers.exact_answer(exact_answer_key))- {- Lookup::Known(answer) => Some(answer),- Lookup::KnownAbsent => {- unreachable!("exact answers are sparse, never known absent")- }- Lookup::Missing(_) => None,- };- retained_match_answer_reused = known_exact_answer- .is_some_and(|answer| self.set_pending_answer_identity(effects, node, answer));- if !retained_match_answer_reused {- let mut retained = prepare_retained_match_answer(matches.as_slice().iter().copied());- merge_retained_match_answers(- &mut retained,- self.match_answers- .answer(exact_prefix_identity)- .expect("a remembered exact prefix answer must remain live"),- );- retained_match_answer = Some(retained);- if known_exact_answer.is_none() {- retained_match_answer_key_to_remember = Some(exact_answer_key);- }- }- } else if retained_match_answer_is_exact {- // Exact retained answers carry a concrete tree scope. Materialize that- // cheap payload locally while still sharing the selector evaluation.- let mut prefix_rules = RuleMatches::new();- let mut caches = prefix_caches.borrow_mut();- match caches.states.lookup_mut(scope_program) {- Lookup::Known(states) => append_prefix_matches(- &mut prefix_rules,- node,- scope,- self.prepared_scope_program(scope).1,- &self.program,- &self.programs,- states.matches_in(prefix_matches),- &self.counters,- CountRuleMatchEmission::No,- ),- Lookup::KnownAbsent | Lookup::Missing(_) => {- unreachable!("matching retained the scope's prefix states")- }- }- drop(caches);- let mut retained = prepare_retained_match_answer(matches.as_slice().iter().copied());- let exact_prefix = prepare_retained_match_answer(prefix_rules.as_slice().iter().copied());- merge_retained_match_answers(&mut retained, &exact_prefix);- retained_match_answer = Some(retained);- newly_materialized_exact_prefix = Some(prefix_rules);- }- // OPTIMIZATION: A prefix rule which loses every declaration to another prefix- // rule cannot become a winner after adding non-prefix contenders. Canonicalize- // that stable contribution before combining the two sets.- let known_contribution = match prefix_caches- .borrow()- .answers- .prefix_contribution(&self.match_answers, contribution_key)- {- Lookup::Known((identity, _)) => Some(identity),- Lookup::KnownAbsent => {- unreachable!("prefix contributions are sparse, never known absent")- }- Lookup::Missing(_) => None,- };- let prefix_contribution = match known_contribution {- Some(identity) => identity,- None => {- let mut prefix_rules = match newly_materialized_exact_prefix.take() {- Some(prefix_rules) => {- self.counters- .add(Counter::RuleMatchesEmitted, prefix_rules.len() as u64);- prefix_rules- }- None => {- let mut prefix_rules = RuleMatches::new();- let mut caches = prefix_caches.borrow_mut();- match caches.states.lookup_mut(scope_program) {- Lookup::Known(states) => append_prefix_matches(- &mut prefix_rules,- node,- scope,- self.prepared_scope_program(scope).1,- &self.program,- &self.programs,- states.matches_in(prefix_matches),- &self.counters,- CountRuleMatchEmission::Yes,- ),- Lookup::KnownAbsent | Lookup::Missing(_) => {- unreachable!("matching retained the scope's prefix states")- }- }- drop(caches);- prefix_rules- }- };- self.compact_matches_for_cascade_with_scratch(- effects,- prefix_rules.as_mut_vec(),- false,- None,- &mut traversal.cascade_compaction_workspace,- );- let contribution = prefix_rules.take();- prefix_caches.borrow_mut().answers.remember_prefix_contribution(- &mut self.match_answers,- scope_program,- prefix_matches,- &contribution,- )- }- };- if let Some(mut prefix_rules) = newly_materialized_exact_prefix {- prefix_rules.release();- }- let key = PrefixAnswerKey {- prefix_contribution,- non_prefix_matches: &non_prefix_matches,- non_prefix_hash,- };- let answer = if self.node_has_element_declaration_input(node) {- append_retained_matches(- &mut matches,- node,- scope,- &self.programs,- self.prepared_scope_program(scope).1,- self.match_answers- .answer(prefix_contribution)- .expect("a prefix contribution must remain live"),- )- .expect("a prefix contribution must reference live selector entries");- self.compact_matches_for_cascade_with_scratch(- effects,- matches.as_mut_vec(),- false,- Some(node),- &mut traversal.cascade_compaction_workspace,- );- let answer = matches.take();- cascade_input = Some(self.intern_cascade_input(&answer));- answer- } else {- let cached_answer = prefix_caches.borrow().answers.lookup(key).sparse().ok().map(|answer| {- (- answer.matches,- answer.winner_group,- answer- .pseudo_winner_groups- .as_ref()- .map(|(generation, states)| (*generation, Arc::clone(states))),- answer.cascade_input,- answer.cascade_winner_inventory_is_complete,- )- });- match cached_answer {- Some((- answer_matches,- winner_group,- pseudo_winner_groups,- answer_cascade_input,- cascade_winner_inventory_is_complete,- )) => {- self.counters.bump(Counter::PrefixAnswerCacheHits);- self.counters.bump(Counter::MatchAnswerSignatureReuses);- cascade_input = Some(answer_cascade_input);- cached_cascade_winner_inventory_is_complete =- Some(cascade_winner_inventory_is_complete);- let mut matches = if scope == TreeScopeID::DOCUMENT- && let Some(compact_answer) = compact_answer.as_mut()- {- **compact_answer = Some(answer_cascade_input);- Vec::new()- } else {- let mut matches = Vec::new();- self.append_catalog_answer(answer_matches, node, Some(scope), &mut matches)- .expect("a cached prefix answer must reference live selector entries");- matches- };- if scope != TreeScopeID::DOCUMENT {- // The shared answer stores the scope which first populated it.- // Rebind and compact against this node's contextual declarations.- self.compact_matches_for_cascade(effects, &mut matches, false, Some(node));- cascade_input = Some(self.intern_cascade_input(&matches));- cached_cascade_winner_inventory_is_complete = None;- } else {- self.order_matches_in_cascade(&mut matches, false);- }- let mut published_winner_rows = false;- if scope == TreeScopeID::DOCUMENT- && let Some((generation, group)) = winner_group- && effects- .winners- .set_from_token(- &mut self.winner_groups,- node,- generation,- group,- self.program.version(),- )- .is_ok()- {- published_winner_rows = true;- }- if scope == TreeScopeID::DOCUMENT- && let Some((generation, pseudo_winner_groups)) = pseudo_winner_groups- && generation == self.winner_groups.generation()- {- for &(pseudo, state) in pseudo_winner_groups.iter() {- let _ = effects.winners.set_pseudo(- &mut self.winner_groups,- node,- pseudo,- state,- self.program.version(),- );- }- published_winner_rows = true;- }- if published_winner_rows {- self.counters.bump(Counter::CascadeNodeHandlesPublished);- }- matches- }- None => {- self.counters.bump(Counter::PrefixAnswerCacheMisses);- append_retained_matches(- &mut matches,- node,- scope,- &self.programs,- self.prepared_scope_program(scope).1,- self.match_answers- .answer(prefix_contribution)- .expect("a prefix contribution must remain live"),- )- .expect("a prefix contribution must reference live selector entries");- self.compact_matches_for_cascade_with_scratch(- effects,- matches.as_mut_vec(),- false,- Some(node),- &mut traversal.cascade_compaction_workspace,- );- let answer = matches.take();- let winner_group = match effects- .winners- .view(&self.winner_groups)- .token_for(WinnerGroupKey::current(node, self.program.version()))- {- Lookup::Known(token) => Some(token),- Lookup::KnownAbsent => {- unreachable!("winner groups are sparse, never known absent")- }- Lookup::Missing(_) => None,- };- // The rows the engine settles pseudo-elements from travel with- // the group, a list item's ::marker included: a cohort hit must- // carry that cascade when the originating record makes the- // element a list item.- let pseudo_winner_groups = self.settled_pseudo_winner_states(effects, node);- let pseudo_winner_groups = (!pseudo_winner_groups.is_empty())- .then(|| (self.winner_groups.generation(), Arc::from(pseudo_winner_groups)));- let answer_cascade_input = self.intern_cascade_input(&answer);- // The winners of an answer holding a gated rule are this node's: its- // containers decided them, and another node's may not.- if !answer- .iter()- .any(|entry| self.program.rule_is_gated_by_container_query(entry.rule))- {- let cascade_winner_inventory_is_complete =- self.cascade_winner_inventory_is_complete(&answer, Some(node));- prefix_caches.borrow_mut().answers.remember(- &mut self.match_answers,- key,- &answer,- winner_group,- pseudo_winner_groups,- answer_cascade_input,- cascade_winner_inventory_is_complete,- );- }- cascade_input = Some(answer_cascade_input);- answer- }- }- };-- Ok(answer)- }- (Ok(()), None) => {- if retained_match_answer_is_exact {- retained_match_answer = Some(prepare_retained_match_answer(matches.as_slice().iter().copied()));- retained_selector_truth = matches.take_prepared_selector_truth();- }- if compact_for_cascade {- self.compact_matches_for_cascade_with_scratch(- effects,- matches.as_mut_vec(),- can_have_scope_duplicates,- Some(node),- &mut traversal.cascade_compaction_workspace,- );- } else if !retained_match_answer_is_exact {- self.order_matches_in_cascade(matches.as_mut_vec(), can_have_scope_duplicates);- }- Ok(matches.take())- }- (Err(incomplete), _) => Err(incomplete),- };-- matches.release();-- if let Ok(matches) = &all {- if let Some(retained_match_answer) = retained_match_answer {- self.remember_prepared_retained_match_answer_with_truth_with_effects(- effects,- node,- retained_match_answer,- retained_selector_truth,- );- if let Some(key) = retained_match_answer_key_to_remember- && let Some(identity) = effects.answer_identity(&self.retained_match_answers, node)- {- effects.remember_exact_answer(key, identity, &mut self.match_answers);- }- } else if compact_for_cascade && !retained_match_answer_reused {- // A cascade-only shortcut can answer the current style without proving the- // complete selector answer. Do not leave an older exact answer resident.- effects.forget(node, &mut self.match_answers);- }- if let Some(complete) = cascade_winners_are_complete.as_mut() {- **complete = retained_match_answer_is_exact- && matches!(self.retained_match_answer_with_effects(effects, node), Lookup::Known(_))- && cached_cascade_winner_inventory_is_complete- .unwrap_or_else(|| self.cascade_winner_inventory_is_complete(matches, Some(node)));- }- match cascade_input {- Some(cascade_input) => self.publish_cascade_input_with_effects(effects, node, cascade_input),- None => self.remember_cascade_input_with_effects(effects, node, matches),- }- }- return all;- }-- // Which other nodes a selector reads is a property of the selectors, not of the element:- // a descendant combinator climbs, a sibling combinator walks back, `:has()` descends. So- // the batch grows by exactly the node each miss names. A sibling, positional or descendant- // scan names the rest of the range it can read instead, and the batch takes a doubling- // window of that range, so a scan that reads its whole range needs a logarithmic number of- // restarts rather than one per row. Both requests converge because the tree is finite and- // cover only nodes the interrupted operator can still read.- //- // The ancestors are seeded because a descendant or child combinator reads them and one of- // those is in almost every stylesheet: without this a page of depth eight discovers one- // ancestor per retry. Other exact requests are collected across the candidate set, and a- // completion bit keeps candidates that already answered from being replayed while those- // requests are materialized.- let mut covered = vec![node];- covered.extend(self.tree.ancestors(node));- // The unified automaton's rightward states read the node's left context the same way its- // down axes read the ancestry, so a sibling-bearing automaton seeds the preceding- // siblings of the node and of each ancestor up front rather than discovering them one- // restart at a time.- if self.prepared_scope_program(scope).1.prefixes().has_sibling_steps() {- let spine_len = covered.len();- for level_index in 0..spine_len {- let mut previous = self.tree.previous_element_sibling(covered[level_index]);- while let Some(sibling) = previous {- covered.push(sibling);- previous = self.tree.previous_element_sibling(sibling);- }- }- }- let mut sibling_window = INITIAL_SIBLING_FACT_WINDOW;- let mut matches = RuleMatches::new();- if compact_for_cascade && verify_selector_truth_derivation_is_enabled() {- matches.enable_selector_truth();- }- let mut completed_by_scope: Column<Vec<bool>> = Column::default();- let mut dispatch_workspace = DispatchCandidateWorkspace::default();- let prefix_caches_return_to_completion_batch = traversal.is_some();- let prefix_caches = traversal- .as_deref()- .map(|traversal| std::sync::Arc::clone(&traversal.prefix_caches))- .unwrap_or_default();- let mut retained_match_answer_is_exact = compact_for_cascade;- let mut facts = traversal- .as_deref_mut()- .map(|traversal| std::mem::take(&mut traversal.unbatched_facts))- .unwrap_or_default();- let mut requests = Vec::new();- loop {- self.facts.materialize_missing(covered.iter().copied(), &mut facts);- let mut prefix_contexts = PrefixTransitionContexts::default();- if !self.prepared_scope_program(scope).1.prefixes().is_empty() {- let (program, _) = self.prepared_scope_program(scope);- prefix_contexts.prepare(- program,- prefix_caches.borrow_mut().states.prepare_program(program),- &facts,- );- }-- let requirements =- AncestorRequirements::build_for_node(&self.tree, &facts, self.prepared_scope_program(scope).1, node);-- requests.clear();- let result = for_each_matching_scope(- scope,- inner_scope,- &slotted_scopes,- &part_scopes,- |asked_scope, context| {- let is_primary = context == ExactMatchContext::Ordinary;- self.match_node_in_kept_scope(- node,- asked_scope,- &facts,- &mut dispatch_workspace,- &mut matches,- requirements.as_ref(),- is_primary.then_some(&prefix_caches),- &mut prefix_contexts,- None,- BatchMatchRetry {- requests: Some(&mut requests),- completed: Some(completed_by_scope.entry(asked_scope.0 as usize)),- deferred_prefix_matches: None,- answer_is_exact: Some(&mut retained_match_answer_is_exact),- cascade_only: is_primary- && compact_for_cascade- && completion_exactness == CompletionExactness::AllowPruning- && scope == TreeScopeID::DOCUMENT- && inner_scope.is_none()- && slotted_scopes.is_empty()- && part_scopes.is_empty(),- },- )- },- );-- let can_have_scope_duplicates =- inner_scope.is_some() || !slotted_scopes.is_empty() || !part_scopes.is_empty();-- match result {- Ok(()) => {- prefix_contexts.install(&mut prefix_caches.borrow_mut().states);- if retained_match_answer_is_exact {- self.order_matches_in_cascade(matches.as_mut_vec(), can_have_scope_duplicates);- let retained = prepare_retained_match_answer(matches.as_slice().iter().copied());- let truth = matches.take_prepared_selector_truth();- self.remember_prepared_retained_match_answer_with_truth_with_effects(- effects, node, retained, truth,- );- } else if compact_for_cascade {- // A cascade-only shortcut can answer the current style without proving the- // complete selector answer. Do not leave an older exact answer resident.- effects.forget(node, &mut self.match_answers);- }- if compact_for_cascade {- self.compact_matches_for_cascade(- effects,- matches.as_mut_vec(),- can_have_scope_duplicates,- Some(node),- );- } else if !retained_match_answer_is_exact {- self.order_matches_in_cascade(matches.as_mut_vec(), can_have_scope_duplicates);- }- let all = matches.take();- self.remember_cascade_input_with_effects(effects, node, &all);- if let Some(complete) = cascade_winners_are_complete.as_mut() {- **complete = retained_match_answer_is_exact- && matches!(self.retained_match_answer_with_effects(effects, node), Lookup::Known(_))- && self.cascade_winner_inventory_is_complete(&all, Some(node));- }-- if !prefix_caches_return_to_completion_batch {- prefix_caches.borrow_mut().states.release();- }- if let Some(traversal) = traversal.as_deref_mut() {- traversal.unbatched_facts = facts;- }- return Ok(all);- }- Err(incomplete) => {- let widened = match requests.is_empty() {- true => self.widen_fact_coverage(&mut covered, incomplete, &mut sibling_window),- false => self.widen_fact_coverage_for_requests(&mut covered, &requests, &mut sibling_window),- };- if let Err(missing) = widened {- matches.release();-- if !prefix_caches_return_to_completion_batch {- prefix_caches.borrow_mut().states.release();- }- if let Some(traversal) = traversal.as_deref_mut() {- traversal.unbatched_facts = facts;- }- return Err(Incomplete::MissingFacts(missing));- }- }- }- }- }-}diff --git a/Libraries/LibWeb/Rust/src/css/style/native_rules/identities.rs b/Libraries/LibWeb/Rust/src/css/style/native_rules/identities.rsdeleted file mode 100644index 77186f4f254..00000000000--- a/Libraries/LibWeb/Rust/src/css/style/native_rules/identities.rs+++ /dev/null@@ -1,96 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--use crate::css::style::fast_hash::FastMap as HashMap;-use crate::css::style::program::RuleID;-use std::num::NonZeroU32;--const IDENTITIES_PER_PAGE: usize = 128;--#[derive(Clone)]--struct IdentityPage {- slots: [Option<NonZeroU32>; IDENTITIES_PER_PAGE],- live_count: u16,-}--/// Native identities are allocated in ranges by parsed stylesheets. Hash only their page-/// number, then read the compact semantic identity directly from the page's slot.-#[derive(Clone, Default)]-pub(in crate::css::style) struct NativeRuleIdentities {- pages: HashMap<u64, Box<IdentityPage>>,-}--impl NativeRuleIdentities {- pub(in crate::css::style) fn get(&self, identity: &u64) -> Option<RuleID> {- let page = self.pages.get(&(identity / IDENTITIES_PER_PAGE as u64))?;- page.slots[(*identity % IDENTITIES_PER_PAGE as u64) as usize].map(|id| RuleID(id.get() - 1))- }-- pub(super) fn insert(&mut self, identity: u64, id: RuleID) {- let stored_id = NonZeroU32::new(id.0.checked_add(1).expect("semantic rule identity space exhausted")).unwrap();- let page = self- .pages- .entry(identity / IDENTITIES_PER_PAGE as u64)- .or_insert_with(|| {- Box::new(IdentityPage {- slots: [None; IDENTITIES_PER_PAGE],- live_count: 0,- })- });- if page.slots[(identity % IDENTITIES_PER_PAGE as u64) as usize]- .replace(stored_id)- .is_none()- {- page.live_count += 1;- }- }-- pub(super) fn remove(&mut self, identity: &u64) -> Option<RuleID> {- let page_number = identity / IDENTITIES_PER_PAGE as u64;- let page = self.pages.get_mut(&page_number)?;- let id = page.slots[(*identity % IDENTITIES_PER_PAGE as u64) as usize].take()?;- page.live_count -= 1;- if page.live_count == 0 {- self.pages.remove(&page_number);- }- Some(RuleID(id.get() - 1))- }-- #[cfg(test)]- pub(super) fn is_empty(&self) -> bool {- self.pages.is_empty()- }-- #[cfg(test)]- pub(super) fn contains_key(&self, identity: &u64) -> bool {- self.get(identity).is_some()- }-}--#[cfg(test)]-mod tests {- use super::*;-- #[test]- fn identity_pages_handle_sparse_ranges_overwrites_and_empty_page_release() {- let mut identities = NativeRuleIdentities::default();- for (identity, rule) in [(1, 0), (127, 1), (128, 2), (u64::MAX, 3)] {- identities.insert(identity, RuleID(rule));- }- assert_eq!(identities.pages.len(), 3);- identities.insert(1, RuleID(10));- assert_eq!(identities.get(&1), Some(RuleID(10)));- assert_eq!(identities.pages[&0].live_count, 2);- assert_eq!(identities.get(&u64::MAX), Some(RuleID(3)));- assert_eq!(identities.get(&2), None);- assert_eq!(identities.remove(&2), None);- for identity in [1, 127, 128, u64::MAX] {- assert!(identities.remove(&identity).is_some());- }- assert!(identities.is_empty());- }-}diff --git a/Libraries/LibWeb/Rust/src/css/style/order.rs b/Libraries/LibWeb/Rust/src/css/style/order.rsindex 9987da2f045..c62afd007cc 100644--- a/Libraries/LibWeb/Rust/src/css/style/order.rs+++ b/Libraries/LibWeb/Rust/src/css/style/order.rs@@ -20,18 +20,23 @@ define_id! {pub struct OrderToken();}-impl OrderToken {}-/// One totally ordered axis: stylesheet order within a tree context, nested rule order within a/// sheet, or layer order within an origin.-#[derive(Clone, Default)]+#[derive(Clone, Default, PartialEq, Eq, Hash)]pub struct OrderMaintenance {labels: Vec<u64>,free_entries: Vec<u32>,order: Vec<OrderToken>,+ /// How many times the labels were spread evenly again.+ relabels: u64,}impl OrderMaintenance {+ pub(super) fn heap_size(&self) -> usize {+ use crate::heap_size::vec_bytes;+ vec_bytes(&self.labels) + vec_bytes(&self.free_entries) + vec_bytes(&self.order)+ }+#[must_use]pub fn new() -> Self {Self::default()@@ -55,6 +60,13 @@ impl OrderMaintenance {self.labels[token.0 as usize]}+ /// How many times the order was relabeled, which moves the ranks of its positions without+ /// moving their order.+ #[must_use]+ pub fn relabels(&self) -> u64 {+ self.relabels+ }+/// Insert at the end of the order.pub fn insert_last(&mut self) -> OrderToken {self.insert_at(self.order.len())@@ -119,6 +131,7 @@ impl OrderMaintenance {let length = u64::try_from(self.order.len()).expect("order length exceeds label space");let step = u64::MAX / (length + 1);assert!(step >= 2, "order label space exhausted");+ self.relabels += 1;for (index, token) in self.order.iter().enumerate() {self.labels[token.0 as usize] = step * (index as u64 + 1);}diff --git a/Libraries/LibWeb/Rust/src/css/style/ordering.rs b/Libraries/LibWeb/Rust/src/css/style/ordering.rsindex 63b78eee11f..c82564c5723 100644--- a/Libraries/LibWeb/Rust/src/css/style/ordering.rs+++ b/Libraries/LibWeb/Rust/src/css/style/ordering.rs@@ -4,1699 +4,26 @@* SPDX-License-Identifier: BSD-2-Clause*/-use std::ops::ControlFlow;--use smallvec::SmallVec;--use super::cascade::{- CascadeAttachment, CascadeContinuationCeiling, CascadeContinuationID, Top1Winner, highest_candidate_below,-};use super::*;-#[derive(Clone, Copy)]-enum CascadeCompactionCandidate {- /// A declaration of the rule at this index of the match list.- Rule(usize, DeclaredProperty),- Element(ElementDeclarationKind, DeclaredProperty),-}--type CascadeCompactionTop1 =- Top1Cascade<(Option<tree::PseudoElementTarget>, u16), CascadePriority, CascadeCompactionCandidate>;--// Element declarations use the overwhelmingly common target and a dense property identity. Keep-// their winner lookup in a property-indexed table; pseudo targets remain in the sparse table above.-#[derive(Clone)]-struct ElementCascadeCompactionTop1 {- winners: Vec<Top1Winner<u16, CascadePriority, CascadeCompactionCandidate>>,- winner_by_property: Vec<u32>,-}--impl ElementCascadeCompactionTop1 {- fn clear(&mut self) {- for winner in &self.winners {- self.winner_by_property[winner.key as usize] = 0;- }- self.winners.clear();- }-- fn consider(&mut self, property: u16, priority: CascadePriority, payload: CascadeCompactionCandidate) {- let property_index = property as usize;- if self.winner_by_property.len() <= property_index {- self.winner_by_property.resize(property_index + 1, 0);- }- let winner = self.winner_by_property[property_index];- if winner == 0 {- self.winners.push(Top1Winner {- key: property,- priority,- payload,- });- self.winner_by_property[property_index] = u32::try_from(self.winners.len())- .expect("a property winner table cannot exceed the u16 property identity space");- } else if priority >= self.winners[winner as usize - 1].priority {- self.winners[winner as usize - 1] = Top1Winner {- key: property,- priority,- payload,- };- }- }-- fn winners(&mut self) -> &[Top1Winner<u16, CascadePriority, CascadeCompactionCandidate>] {- self.winners.sort_unstable_by_key(|winner| winner.key);- &self.winners- }-}--/// The winner state a compaction publishes for one of a node's targets.-#[derive(Clone, Copy)]-struct PublishedWinnerState {- target: Option<tree::PseudoElementTarget>,- state: CascadeStateID,- /// Whether a pseudo-element target's state holds a winner for everything its rules declare.- inventory_is_complete: bool,-}--/// What a match contributes to a compaction that depends on nothing but its match list. A match-/// from the node's own tree reaches the compaction only through its priority, which names-/// everything the tree decides about it, so alike rows of two instances of one shadow tree share-/// a compaction.-#[derive(Clone, Copy, PartialEq, Eq, Hash)]-struct CompactionMatch {- rule: RuleID,- pseudo_element: Option<tree::PseudoElementTarget>,- specificity: Specificity,- scope_proximity: u32,- /// The normal priority of a match from the node's own tree; none for a document rule's.- own_tree_priority: Option<CascadePriority>,-}--/// One part of what a remembered compaction is keyed by: a match, or a declaration of the element's own, which a-/// compaction decides over beside the matches at the priority of the element's tree.-#[derive(Clone, Copy, PartialEq, Eq, Hash)]-enum CompactionKeyPart {- Match(CompactionMatch),- TreeScope(TreeScopeID),- ElementDeclaration(ElementDeclarationKind, DeclaredProperty),- ElementCustomDeclaration(CustomDeclaration),-}--/// What compacting one match list decided: the states it published and, unless compaction was-/// blocked, which matches it kept.-#[derive(Clone)]-struct RememberedCompaction {- hash: u64,- matches: Box<[CompactionKeyPart]>,- states: SmallVec<[PublishedWinnerState; 2]>,- keep: Option<Box<[bool]>>,-}--/// Compactions that depend on nothing but their match lists and the elements' own declarations, by both, as decided-/// under one program version and winner group generation. A list is remembered the second time it is compacted:-/// most lists are one element's own, and remembering those would only fill the table.-#[derive(Clone, Default)]-struct RememberedCompactions {- decided_under: Option<(ProgramVersion, u64)>,- /// The hashes of the lists compacted once since the table was last cleared.- seen: HashSet<u64>,- by_matches: hashbrown::HashTable<RememberedCompaction>,-}--impl RememberedCompactions {- const LIMIT: usize = 1024;-- fn hash_of(matches: &[CompactionKeyPart]) -> u64 {- let mut hasher = fast_hash::fast_hasher();- matches.hash(&mut hasher);- hasher.finish()- }-- /// Forget everything decided under another program version or winner group generation.- fn settle(&mut self, version: ProgramVersion, generation: u64) {- if self.decided_under != Some((version, generation)) {- self.seen.clear();- self.clear();- self.decided_under = Some((version, generation));- }- }-- fn clear(&mut self) {- self.by_matches.clear();- }-- fn get(&self, hash: u64, matches: &[CompactionKeyPart]) -> Option<&RememberedCompaction> {- self.by_matches.find(hash, |remembered| {- remembered.hash == hash && *remembered.matches == *matches- })- }-- /// Whether the list hashing to `hash` was compacted before, noting that it is now.- fn seen_before(&mut self, hash: u64) -> bool {- if self.seen.len() >= 4 * Self::LIMIT {- self.seen.clear();- }- !self.seen.insert(hash)- }-- fn remember(- &mut self,- hash: u64,- matches: &[CompactionKeyPart],- states: &[PublishedWinnerState],- keep: Option<&[bool]>,- ) {- if self.by_matches.len() >= Self::LIMIT {- self.clear();- }- let remembered = RememberedCompaction {- hash,- matches: matches.into(),- states: states.into(),- keep: keep.map(Into::into),- };- self.by_matches- .insert_unique(hash, remembered, |remembered| remembered.hash);- }-}--#[derive(Clone)]--pub(super) struct CascadeCompactionWorkspace {- top_1: CascadeCompactionTop1,- element_top_1: ElementCascadeCompactionTop1,- keep: Vec<bool>,- /// The winners a compaction publishes, every target's in one run, and each target's range of- /// them.- published_winners: Vec<PropertyWinner>,- published_targets: Vec<(Option<tree::PseudoElementTarget>, std::ops::Range<usize>)>,- published_states: SmallVec<[PublishedWinnerState; 2]>,- /// The match list of a compaction that depends on nothing but it, as `remembered` keys it.- remembered_key: Vec<CompactionKeyPart>,- remembered: RememberedCompactions,-}--impl Default for CascadeCompactionWorkspace {- fn default() -> Self {- Self {- top_1: CascadeCompactionTop1::with_capacity(0),- element_top_1: ElementCascadeCompactionTop1 {- winners: Vec::new(),- winner_by_property: Vec::new(),- },- keep: Vec::new(),- published_winners: Vec::new(),- published_targets: Vec::new(),- published_states: SmallVec::new(),- remembered_key: Vec::new(),- remembered: RememberedCompactions::default(),- }- }-}--impl CascadeCompactionWorkspace {}--/// Whether a declared property names a longhand column; a shorthand declared whole does not.-fn property_is_longhand(property: u16) -> bool {- // Style-engine unit tests use small synthetic property IDs to keep their cascade fixtures- // independent of the generated property table.- #[cfg(test)]- if property != crate::css::property_metadata::property_id::CUSTOM- && property < crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID- {- return true;- }- (crate::css::property_metadata::FIRST_LONGHAND_PROPERTY_ID- ..=crate::css::property_metadata::LAST_LONGHAND_PROPERTY_ID)- .contains(&property)-}-impl RetainedState {- /// Order matches the way the cascade applies them, dropping repeats from asking more than one- /// tree scope when that could have happened.- pub(super) fn order_matches_in_cascade(&self, all: &mut Vec<RuleMatch>, can_have_scope_duplicates: bool) {- // One match per rule, target and context the rule is weighed in, not per scope that asked.- // The user-agent and user origins decide in every scope, so a node asked in two of them - a- // host, which is asked its own scope's rules and its shadow tree's - meets those rules- // twice, and both are weighed where their sheet is attached. A sheet several scopes adopt- // decides in each of them, at each one's own context.- let identity = |entry: &RuleMatch| {- (- entry.node,- entry.rule,- entry.pseudo_element.map_or(u32::MAX, |target| u32::from(target.kind.0)),- self.cascade_context_scope(entry.rule, entry.tree_scope),- )- };- if can_have_scope_duplicates {- all.sort_unstable_by_key(identity);- all.dedup_by_key(|entry| identity(entry));- }-- // Cascade order is meaningful only among declarations for the same element. Sorting the- // entire document by a key containing it makes the sort compare unrelated elements and- // retain one large cached key for every match. Keep the outer node order and sort only the- // contiguous answers that a style computation consumes together. Both callers emit one- // node at a time, and the duplicate-removal sort above restores that grouping when several- // tree scopes contributed answers.- let mut start = 0;- while start < all.len() {- let node = all[start].node;- let end = start + all[start..].partition_point(|entry| entry.node == node);- let matches = &mut all[start..end];- if !can_have_scope_duplicates && matches.iter().all(|entry| entry.scope_proximity == u32::MAX) {- matches.sort_unstable_by_key(|entry| {- (- entry.cascade_order,- entry.rule,- entry.pseudo_element.map_or(u32::MAX, |target| u32::from(target.kind.0)),- )- });- } else {- matches.sort_by_cached_key(|entry| {- self.cascade_priority_of(- entry.node,- entry.rule,- entry.tree_scope,- entry.specificity,- entry.scope_proximity,- false,- )- });- }- start = end;- }- }-- #[must_use]- pub(super) fn in_cascade_order(&self, mut all: Vec<RuleMatch>, can_have_scope_duplicates: bool) -> Vec<RuleMatch> {- self.order_matches_in_cascade(&mut all, can_have_scope_duplicates);- all- }-- /// The semantic key of one ordinary declared value.- #[must_use]- pub(super) fn retained_rule_winner_key(declared: DeclaredProperty) -> SpecifiedWinnerKey {- SpecifiedWinnerKey {- value: declared.value,- operator: declared.operator,- continuation: cascade::CascadeContinuationID::default(),- animation_relevance: 0,- important: declared.important,- }- }-- pub(super) fn cascade_stratum_of(- &self,- node: StyleNodeID,- rule: RuleID,- tree_scope: TreeScopeID,- important: bool,- ) -> CascadeStratum {- let sheet = self.program.rule_sheet(rule);- let context_scope = self.cascade_context_scope(rule, tree_scope);- let layer = self.program.rule_version(rule).layer;- CascadeStratum::new(- self.program.sheet_origin(sheet),- important,- self.encapsulation_context(node, context_scope),- layer,- self.program.layer_rank(context_scope, layer),- CascadeAttachment::StyleSheet,- )- }-- pub(super) fn element_cascade_stratum(- &self,- node: StyleNodeID,- kind: ElementDeclarationKind,- important: bool,- ) -> CascadeStratum {- let origin = match kind {- ElementDeclarationKind::InlineStyle => CascadeOrigin::Author,- ElementDeclarationKind::PresentationalHint | ElementDeclarationKind::SvgPresentationAttribute => {- CascadeOrigin::AuthorPresentationalHint- }- };- let tree_scope = self.tree.tree_scope(node);- CascadeStratum::new(- origin,- important,- self.tree_scope_depth(tree_scope),- CascadeLayerID::UNLAYERED,- self.program.layer_rank(tree_scope, CascadeLayerID::UNLAYERED),- if kind == ElementDeclarationKind::InlineStyle {- CascadeAttachment::InlineStyle- } else {- CascadeAttachment::StyleSheet- },- )- }-- /// What one property of the node's cascade falls back to once substitutions turned some of its- /// declarations into `revert` or `revert-layer`. `reverted` names each such declaration by its- /// priority, with the keyword it substituted to. The property's candidates are gathered again- /// from the node's match answer, which keeps every declaration beaten by a winner whose- /// substitution may come out as a revert keyword (see- /// `compact_matches_for_cascade_with_scratch`), and from its own declarations, as the- /// cascade gathers them, and the cascade is resolved again with each reverted declaration- /// acting as its keyword. `Ok(None)` leaves the property undeclared. `Err` when the candidates are not- /// the ones the node's winners were reduced from: they miss a declaration `reverted` names.- pub(super) fn winner_below_substitution(- &self,- node: StyleNodeID,- pseudo_kind: Option<u8>,- property: u16,- reverted: &[(CascadePriority, CascadeOperator)],- ) -> Result<Option<PropertyWinner>, ()> {- let mut candidates = Vec::new();- let wants = |declared: u16| declared == property;- let answered =- self.try_for_each_answer_match(node, pseudo_kind, |rule, tree_scope, specificity, scope_proximity| {- // A gated rule is a candidate where its conditions held for the target as the- // node's winners were published.- if self.published_container_verdict_holds(node, rule, pseudo_kind.is_some()) {- self.push_rule_cascade_candidates(- node,- rule,- tree_scope,- specificity,- scope_proximity,- &wants,- &mut candidates,- );- }- ControlFlow::Continue(())- });- if answered.is_none() {- return Err(());- }- if pseudo_kind.is_none() {- self.push_element_cascade_candidates(node, &wants, &mut candidates);- }- candidates.sort_unstable_by_key(|candidate| candidate.winner.priority);- // As `WinnerGroups::resolve_candidates` resolves, each revert keyword setting a ceiling the- // candidates below it have to be under.- let mut ceilings = SmallVec::<[CascadeContinuationCeiling; 2]>::new();- let mut end = candidates.len();- let mut reverted_reached = 0;- let winner = loop {- let Some(index) = highest_candidate_below(&candidates[..end], &ceilings) else {- break None;- };- let candidate = candidates[index];- let operator = match reverted- .iter()- .find(|(priority, _)| *priority == candidate.winner.priority)- {- Some(&(_, operator)) => {- reverted_reached += 1;- operator- }- None => candidate.winner.key.operator,- };- let Some(ceiling) = candidate.stratum.ceiling(operator) else {- break Some(candidate.winner);- };- ceilings.push(ceiling);- end = index;- };- if reverted_reached != reverted.len() {- return Err(());- }- Ok(winner)- }-- pub(super) fn resolved_cascade_winners_for_properties(- &mut self,- node: StyleNodeID,- matches: &[RuleMatch],- pseudo: Option<tree::PseudoElementTarget>,- properties: Option<&[u16]>,- ) -> Vec<PropertyWinner> {- self.resolved_cascade_winners_for_properties_with_scratch(node, matches, pseudo, properties, &mut Vec::new())- }-- fn resolved_cascade_winners_for_properties_with_scratch(- &mut self,- node: StyleNodeID,- matches: &[RuleMatch],- pseudo: Option<tree::PseudoElementTarget>,- properties: Option<&[u16]>,- candidates: &mut Vec<OrderedCascadeCandidate>,- ) -> Vec<PropertyWinner> {- let wants = |property: u16| properties.is_none_or(|properties| properties.binary_search(&property).is_ok());- candidates.clear();- // A gated rule is a candidate where its container conditions hold for the target now.- let conditions_hold = |rule: RuleID| {- !self.program.rule_is_gated_by_container_query(rule)- || self- .rule_container_verdict(rule, node, pseudo.is_some())- .is_some_and(|verdict| verdict.matches)- };- for entry in matches- .iter()- .filter(|entry| entry.pseudo_element == pseudo && conditions_hold(entry.rule))- {- self.push_rule_cascade_candidates(- node,- entry.rule,- entry.tree_scope,- entry.specificity,- entry.scope_proximity,- &wants,- candidates,- );- }- if pseudo.is_none() {- self.push_element_cascade_candidates(node, &wants, candidates);- }- candidates.sort_unstable_by_key(|candidate| candidate.winner.property);- let mut winners = Vec::new();- let mut start = 0;- while start < candidates.len() {- let property = candidates[start].winner.property;- let end = start + candidates[start..].partition_point(|candidate| candidate.winner.property == property);- if let Some(winner) = self.winner_groups.resolve_candidates(&mut candidates[start..end]) {- winners.push(winner);- }- start = end;- }- winners- }-- /// Push the cascade candidates a matched rule declares for the longhands `wants` names. A- /// shorthand written with a substitution is declared whole beside the longhands it pends; the- /// longhands are the candidates, the shorthand names no column.- #[allow(clippy::too_many_arguments)]- fn push_rule_cascade_candidates(- &self,- node: StyleNodeID,- rule: RuleID,- tree_scope: TreeScopeID,- specificity: Specificity,- scope_proximity: u32,- wants: &impl Fn(u16) -> bool,- candidates: &mut Vec<OrderedCascadeCandidate>,- ) {- let mut priority_and_stratum_by_importance = [None; 2];- for &declared in self.program.declared_properties_of(rule) {- if !wants(declared.property) || !property_is_longhand(declared.property) {- continue;- }- let (priority, stratum) = *priority_and_stratum_by_importance[declared.important as usize]- .get_or_insert_with(|| {- (- self.cascade_priority_of(- node,- rule,- tree_scope,- specificity,- scope_proximity,- declared.important,- ),- self.cascade_stratum_of(node, rule, tree_scope, declared.important),- )- });- candidates.push(OrderedCascadeCandidate {- winner: PropertyWinner {- property: declared.property,- important: declared.important,- key: Self::retained_rule_winner_key(declared),- priority,- source: WinnerSource::Rule(rule),- },- stratum,- });- }- }-- /// Push the cascade candidates a node's own declarations hold for the longhands `wants` names.- fn push_element_cascade_candidates(- &self,- node: StyleNodeID,- wants: &impl Fn(u16) -> bool,- candidates: &mut Vec<OrderedCascadeCandidate>,- ) {- for kind in ElementDeclarationKind::ALL {- // Custom properties an inline style declares beside its longhands leave those- // longhands as complete as any; the environment they decide is computed apart.- let declared_properties = self.facts.element_declared_properties(node, kind);- let mut priority_and_stratum_by_importance = [None; 2];- for &declared in declared_properties {- if !wants(declared.property) || !property_is_longhand(declared.property) {- continue;- }- let (priority, stratum) = *priority_and_stratum_by_importance[declared.important as usize]- .get_or_insert_with(|| {- (- self.element_cascade_priority(node, kind, declared.important),- self.element_cascade_stratum(node, kind, declared.important),- )- });- candidates.push(OrderedCascadeCandidate {- winner: PropertyWinner {- property: declared.property,- important: declared.important,- key: Self::retained_rule_winner_key(declared),- priority,- source: WinnerSource::Element(kind),- },- stratum,- });- }- }- }-- pub(super) fn intern_cascade_state(- &mut self,- winners: &[PropertyWinner],- previous: Option<CascadeStateID>,- ) -> CascadeStateID {- self.with_cascade_interning_counters(|groups| groups.intern_sorted(winners, previous))- }-- pub(super) fn with_cascade_interning_counters<T>(&mut self, intern: impl FnOnce(&mut WinnerGroups) -> T) -> T {- let previous_state_count = self.winner_groups.state_count();- let previous_group_count = self.winner_groups.payload_count();- let previous_winner_entry_count = self.winner_groups.winner_entry_count();- let result = intern(&mut self.winner_groups);- self.counters.add(- Counter::CascadeStatesInterned,- (self.winner_groups.state_count() - previous_state_count) as u64,- );- self.counters.add(- Counter::CascadeWinnerGroupsInterned,- (self.winner_groups.payload_count() - previous_group_count) as u64,- );- self.counters.add(- Counter::CascadeWinnerEntriesInterned,- (self.winner_groups.winner_entry_count() - previous_winner_entry_count) as u64,- );- result- }-- /// Keep only rules that can supply a winning declaration to the cascade.- ///- /// Matching has already resolved selector specificity, tree-scoped encapsulation, layers and- /// source order. A rule that loses every longhand it declares cannot affect the cascade, so it- /// need not cross the language boundary or be visited again by property cascading. Rules whose- /// declaration inventory is not exact, container-gated rules and non-document scopes- /// conservatively keep the full answer. Non-author rules are retained verbatim so compaction- /// does not change how the consumer resolves cascade origins. One otherwise-empty match per- /// pseudo target is retained because the originating element uses its presence to decide which- /// synthetic pseudo-elements to materialize.- pub(super) fn compact_matches_for_cascade(- &mut self,- effects: &mut AnswerEffects,- all: &mut Vec<RuleMatch>,- can_have_scope_duplicates: bool,- publish_winners_for: Option<StyleNodeID>,- ) {- let mut workspace = std::mem::take(&mut self.cascade_compaction_scratch);- self.compact_matches_for_cascade_with_scratch(- effects,- all,- can_have_scope_duplicates,- publish_winners_for,- &mut workspace,- );-- self.cascade_compaction_scratch = workspace;- }-- pub(super) fn compact_matches_for_cascade_with_scratch(- &mut self,- effects: &mut AnswerEffects,- all: &mut Vec<RuleMatch>,- can_have_scope_duplicates: bool,- publish_winners_for: Option<StyleNodeID>,- workspace: &mut CascadeCompactionWorkspace,- ) {- self.order_matches_in_cascade(all, can_have_scope_duplicates);- self.counters- .add(Counter::CascadeMatchesBeforeCompaction, all.len() as u64);- if let Some(node) = publish_winners_for- && all- .iter()- .any(|entry| self.program.rule_is_gated_by_container_query(entry.rule))- {- self.note_container_gates_for_publication(node, effects);- }- let compaction_blocked = !self.cascade_winner_inventory_is_complete(all, publish_winners_for);- let has_continuations = all.iter().any(|entry| {- self.program.declared_properties_of(entry.rule).iter().any(|declared| {- matches!(- declared.operator,- CascadeOperator::Revert | CascadeOperator::RevertLayer- )- })- }) || publish_winners_for.is_some_and(|node| {- ElementDeclarationKind::ALL.iter().any(|&kind| {- self.facts- .element_declared_properties(node, kind)- .iter()- .any(|declared| {- matches!(- declared.operator,- CascadeOperator::Revert | CascadeOperator::RevertLayer- )- })- })- });- if has_continuations && publish_winners_for.is_none() {- return;- }- if compaction_blocked && publish_winners_for.is_none() {- return;- }-- // A compaction that depends on nothing but its match list and the element's own declarations is decided once- // per list: rows built from one template repeat them, and each publishes what the first decided.- let mut remember_as = None;- if let Some(node) = publish_winners_for- && !has_continuations- && self.compaction_depends_only_on_its_key(effects, node, all)- {- let key = &mut workspace.remembered_key;- key.clear();- key.extend(all.iter().map(|entry| {- CompactionKeyPart::Match(CompactionMatch {- rule: entry.rule,- pseudo_element: entry.pseudo_element,- specificity: entry.specificity,- scope_proximity: entry.scope_proximity,- own_tree_priority: (entry.tree_scope != TreeScopeID::DOCUMENT).then(|| {- self.cascade_priority_of(- entry.node,- entry.rule,- entry.tree_scope,- entry.specificity,- entry.scope_proximity,- false,- )- }),- })- }));- // An element's own declarations cascade at the priority of its tree, which is all they read of it.- if self.node_has_element_declaration_input(node) {- key.push(CompactionKeyPart::TreeScope(self.tree.tree_scope(node)));- for kind in ElementDeclarationKind::ALL {- key.extend(- self.facts- .element_declared_properties(node, kind)- .iter()- .map(|&declared| CompactionKeyPart::ElementDeclaration(kind, declared)),- );- }- key.extend(- self.facts- .element_custom_declarations(node)- .iter()- .map(|&declared| CompactionKeyPart::ElementCustomDeclaration(declared)),- );- }- let remembered = &mut workspace.remembered;- remembered.settle(self.program.version(), self.winner_groups.generation());- let hash = RememberedCompactions::hash_of(key);- if let Some(remembered) = remembered.get(hash, key) {- self.publish_winner_states(effects, node, &remembered.states);- if let Some(keep) = &remembered.keep {- // The key holds every match, so the remembered decisions line up with the list; were one missing,- // keeping its match only keeps a rule the cascade finds losing again.- debug_assert_eq!(keep.len(), all.len());- let mut keep = keep.iter();- all.retain(|_| keep.next().copied().unwrap_or(true));- }- return;- }- if remembered.seen_before(hash) {- remember_as = Some(hash);- }- }-- // The number of declaration candidates can be orders of magnitude larger than the number- // of semantic outputs: every rule may declare the same properties, while this reduction- // stores only one winner per pseudo/property pair. Let the table grow with distinct keys- // instead of reserving for every losing declaration.- let top_1 = &mut workspace.top_1;- top_1.clear();- let element_top_1 = &mut workspace.element_top_1;- element_top_1.clear();- // A gated rule's conditions are decided for the node over its containers as they stand:- // the rule is a candidate only where they hold, and the verdicts are kept with the winners,- // which the record loop checks again once the node's ancestors have settled. One the engine- // cannot decide is kept as undecided, not as failed: it leaves the node to the host.- let mut container_verdicts = Vec::new();- for (match_index, entry) in all.iter().enumerate() {- if compaction_blocked && !self.container_gate_is_held(publish_winners_for, entry.rule) {- continue;- }- if self.program.rule_is_gated_by_container_query(entry.rule)- && let Some(node) = publish_winners_for- {- let pseudo = entry.pseudo_element.is_some();- let held = self- .rule_container_verdict(entry.rule, node, pseudo)- .map(|verdict| verdict.matches);- container_verdicts.push(PublishedContainerVerdict {- rule: entry.rule,- pseudo,- held,- });- if held != Some(true) {- continue;- }- }- let declared_properties = self.program.declared_properties_of(entry.rule);- let mut priorities = [None; 2];- for declared in declared_properties {- if !property_is_longhand(declared.property) {- continue;- }- let priority = *priorities[declared.important as usize].get_or_insert_with(|| {- self.cascade_priority_of(- entry.node,- entry.rule,- entry.tree_scope,- entry.specificity,- entry.scope_proximity,- declared.important,- )- });- match entry.pseudo_element {- Some(_) => top_1.consider(- (entry.pseudo_element, declared.property),- priority,- CascadeCompactionCandidate::Rule(match_index, *declared),- ),- None => element_top_1.consider(- declared.property,- priority,- CascadeCompactionCandidate::Rule(match_index, *declared),- ),- }- }- }- if let Some(node) = publish_winners_for {- self.publish_container_verdicts(node, container_verdicts);- for kind in ElementDeclarationKind::ALL {- let declared_properties = self.facts.element_declared_properties(node, kind);- let mut priorities = [None; 2];- for &declared in declared_properties {- if !property_is_longhand(declared.property) {- continue;- }- let priority = *priorities[declared.important as usize]- .get_or_insert_with(|| self.element_cascade_priority(node, kind, declared.important));- element_top_1.consider(- declared.property,- priority,- CascadeCompactionCandidate::Element(kind, declared),- );- }- }- }- let published_winners = &mut workspace.published_winners;- published_winners.clear();- let published_targets = &mut workspace.published_targets;- published_targets.clear();- if let Some(node) = publish_winners_for {- let mut targets: SmallVec<[Option<tree::PseudoElementTarget>; 6]> = SmallVec::new();- targets.push(None);- for target in all.iter().filter_map(|entry| entry.pseudo_element) {- if !targets.contains(&Some(target)) {- targets.push(Some(target));- }- }- // A target which lost its final matching rule still needs an empty winner state.- // Otherwise its previous sparse row would remain current and could incorrectly prove- // that the now-absent pseudo does not need recomputation.- for (target, _, _, _) in effects.winners.view(&self.winner_groups).pseudo_states(node) {- if !targets.contains(&Some(target)) {- targets.push(Some(target));- }- }- for target in targets {- let start = published_winners.len();- if has_continuations {- published_winners.extend(self.resolved_cascade_winners_for_properties(node, all, target, None));- } else {- let materialize = |priority, payload| {- let (declared, source) = match payload {- CascadeCompactionCandidate::Rule(match_index, declared) => {- (declared, WinnerSource::Rule(all[match_index].rule))- }- CascadeCompactionCandidate::Element(kind, declared) => {- (declared, WinnerSource::Element(kind))- }- };- PropertyWinner {- property: declared.property,- important: declared.important,- key: Self::retained_rule_winner_key(declared),- priority,- source,- }- };- match target {- None => published_winners.extend(- element_top_1- .winners()- .iter()- .map(|winner| materialize(winner.priority, winner.payload)),- ),- Some(_) => published_winners.extend(- top_1- .winners()- .filter(|winner| winner.key.0 == target)- .map(|winner| materialize(winner.priority, winner.payload)),- ),- }- }- published_targets.push((target, start..published_winners.len()));- }- }-- if let Some(node) = publish_winners_for {- let published_states = &mut workspace.published_states;- published_states.clear();- for (target, range) in published_targets.iter() {- let winners = &published_winners[range.clone()];- let key = target.map_or_else(- || WinnerGroupKey::current(node, self.program.version()),- |target| WinnerGroupKey::current_pseudo(node, target, self.program.version()),- );- let previous = effects- .winners- .view(&self.winner_groups)- .token_for(key)- .sparse()- .ok()- .map(|(_, state)| state);- // A pseudo-element whose rules declare custom properties past their longhand- // winners holds them in its state: the state then says all its rules declare.- let pseudo_custom_declarations = target- .filter(|&target| {- !self.cascade_winner_inventory_is_complete_for_target(all, Some(node), Some(target))- && self.cascade_winner_inventory_is_complete_but_for_custom_properties_for_target(- node, all, target,- )- })- .and_then(|target| self.cascaded_pseudo_custom_declarations_in(node, all, target));- let state = match &pseudo_custom_declarations {- Some(custom_declarations) => self.with_cascade_interning_counters(|groups| {- groups.intern_sorted_with_custom_declarations(winners, custom_declarations, previous)- }),- None => self.intern_cascade_state(winners, previous),- };- published_states.push(PublishedWinnerState {- target: *target,- state,- inventory_is_complete: target.is_none_or(|target| {- pseudo_custom_declarations.is_some()- || self.cascade_winner_inventory_is_complete_for_target(all, Some(node), Some(target))- }),- });- }- self.publish_winner_states(effects, node, published_states);- }-- if compaction_blocked {- if let Some(hash) = remember_as {- workspace- .remembered- .remember(hash, &workspace.remembered_key, &workspace.published_states, None);- }-- return;- }-- let keep = &mut workspace.keep;- keep.clear();- keep.extend(all.iter().map(|entry| self.compaction_keeps_verbatim(entry.rule)));- for winner in top_1.unordered_winners() {- if let CascadeCompactionCandidate::Rule(match_index, _) = winner.payload {- keep[match_index] = true;- }- }- for winner in &element_top_1.winners {- if let CascadeCompactionCandidate::Rule(match_index, _) = winner.payload {- keep[match_index] = true;- }- }- // A winner resolved through continuations names its rule but not the match it came from, so- // the matches it needs are found by scanning. The scan stays inside the winner's own target:- // a rule winning for one pseudo element says nothing about that rule's matches against- // another target, and retaining those would keep matches that reduction from winner states- // already drops. Every other published winner came from a top-1 candidate kept above.- if has_continuations {- for (target, range) in published_targets.iter() {- for &winner in &published_winners[range.clone()] {- let mut current = Some(winner);- while let Some(winner) = current {- if let WinnerSource::Rule(rule) = winner.source {- for (index, entry) in all.iter().enumerate() {- if entry.rule == rule && entry.pseudo_element == *target {- keep[index] = true;- }- }- }- current = self- .winner_groups- .continuation(winner.key.continuation)- .and_then(|continuation| continuation.winner);- }- }- }- }-- // A winner written with a substitution that may substitute a `revert` or `revert-layer`- // rolls its property back to the declarations it beat. A record computation gathers those- // from the answer again (`winner_below_substitution`), so a match declaring such a- // property is kept whatever else it loses.- if keep.iter().any(|kept| !kept) {- let may_substitute_revert = |value| {- self.specified_values- .value(value)- .is_some_and(custom_property_cascade::value_may_substitute_revert)- };- let mut substituted: SmallVec<[(Option<tree::PseudoElementTarget>, u16); 4]> = SmallVec::new();- let top_1_winners = top_1.unordered_winners().map(|winner| (winner.key, winner.payload));- let element_winners = element_top_1- .winners- .iter()- .map(|winner| ((None, winner.key), winner.payload));- for (key, payload) in top_1_winners.chain(element_winners) {- let (CascadeCompactionCandidate::Rule(_, declared) | CascadeCompactionCandidate::Element(_, declared)) =- payload;- if may_substitute_revert(declared.value) {- substituted.push(key);- }- }- // A winner a continuation reached is not a top candidate.- if has_continuations {- for (target, range) in published_targets.iter() {- for &winner in &published_winners[range.clone()] {- if let Some(winner) = self.winner_groups.resolved_winner(winner)- && may_substitute_revert(winner.key.value)- {- substituted.push((*target, winner.property));- }- }- }- }- if !substituted.is_empty() {- for (index, entry) in all.iter().enumerate() {- keep[index] |= self- .program- .declared_properties_of(entry.rule)- .iter()- .any(|declared| substituted.contains(&(entry.pseudo_element, declared.property)));- }- }- }-- let mut retained_pseudo_targets: SmallVec<[tree::PseudoElementTarget; 4]> = SmallVec::new();- for (index, entry) in all.iter().enumerate() {- if keep[index]- && let Some(target) = entry.pseudo_element- && !retained_pseudo_targets.contains(&target)- {- retained_pseudo_targets.push(target);- }- }- for (index, entry) in all.iter().enumerate() {- if let Some(target) = entry.pseudo_element- && !retained_pseudo_targets.contains(&target)- {- keep[index] = true;- retained_pseudo_targets.push(target);- }- }-- if let Some(hash) = remember_as {- workspace- .remembered- .remember(hash, &workspace.remembered_key, &workspace.published_states, Some(keep));- }- let mut index = 0;- all.retain(|_| {- let retained = keep[index];- index += 1;- retained- });- }-- /// Whether compacting `all` for `node` decides what it would for any other node with the same- /// matches: every match decides in the document or in the node's own tree, where its priority- /// depends on that tree alone and not on where the node is assigned or what it hosts, none- /// waits on a container, and the node has neither declarations of its own nor pseudo-element- /// rows its compaction would have to empty.- fn compaction_depends_only_on_its_key(- &self,- effects: &AnswerEffects,- node: StyleNodeID,- all: &[RuleMatch],- ) -> bool {- let tree_scope = self.tree.tree_scope(node);- all.iter().all(|entry| {- (entry.tree_scope == TreeScopeID::DOCUMENT || entry.tree_scope == tree_scope)- && !self.program.rule_is_gated_by_container_query(entry.rule)- }) && effects- .winners- .view(&self.winner_groups)- .pseudo_states(node)- .next()- .is_none()- }-- fn publish_winner_states(- &mut self,- effects: &mut AnswerEffects,- node: StyleNodeID,- states: &[PublishedWinnerState],- ) {- let mut published_row_count = 0;- for &PublishedWinnerState {- target,- state,- inventory_is_complete,- } in states- {- if let Some(target) = target {- let published =- effects- .winners- .set_pseudo(&mut self.winner_groups, node, target, state, self.program.version());- if published && !inventory_is_complete {- effects.winners.mark_pseudo_inventory_incomplete(node, target);- }- published_row_count += usize::from(published);- } else {- published_row_count += usize::from(effects.winners.set(- &mut self.winner_groups,- node,- state,- self.program.version(),- ));- }- }-- self.counters- .add(Counter::CascadeNodeHandlesPublished, published_row_count as u64);- }-- /// Whether a winner of the state may substitute a revert keyword, which rolls its property back- /// to the declarations it beat: the general compaction keeps those, which the winners do not- /// name.- fn state_may_substitute_revert(&self, state: CascadeStateID) -> bool {- self.winner_groups.winners_in_state(state).any(|winner| {- self.specified_values- .value(winner.key.value)- .is_some_and(custom_property_cascade::value_may_substitute_revert)- })- }-- /// Whether compacting a cascade input keeps a rule's matches whatever the winners say: a- /// non-author match keeps the origin the consumer resolves, and a container-gated one is- /// decided again when its containers move, where a rule that loses now may win.- pub(super) fn compaction_keeps_verbatim(&self, rule: RuleID) -> bool {- self.program.sheet_origin(self.program.rule_sheet(rule)) != CascadeOrigin::Author- || self.program.rule_is_gated_by_container_query(rule)- }-- /// Reuse a complete, freshly updated element winner state instead of reducing declarations- /// again. Cascade continuations retain the general compaction path.- pub(super) fn compact_matches_from_updated_winners(- &mut self,- effects: &mut AnswerEffects,- node: StyleNodeID,- all: &mut Vec<RuleMatch>,- ) -> bool {- let mut has_author_pseudo_rules = false;- if self.node_has_element_declaration_input(node)- || all.iter().any(|entry| {- has_author_pseudo_rules |= entry.pseudo_element.is_some()- && self.program.sheet_origin(self.program.rule_sheet(entry.rule)) == CascadeOrigin::Author;- self.program.declared_properties_of(entry.rule).iter().any(|declared| {- matches!(- declared.operator,- CascadeOperator::Revert | CascadeOperator::RevertLayer- )- })- })- {- return false;- }- if has_author_pseudo_rules {- return self.compact_pseudo_matches_from_updated_winners(effects, node, all);- }- let Some((_, state)) = effects- .winners- .view(&self.winner_groups)- .token_for(WinnerGroupKey::current(node, self.program.version()))- .sparse()- .ok()- else {- return false;- };- if self.state_may_substitute_revert(state) {- return false;- }- let Some(rules) = self.winner_groups.rules_for_compaction(state) else {- return false;- };- self.counters- .add(Counter::CascadeMatchesBeforeCompaction, all.len() as u64);- all.retain(|entry| self.compaction_keeps_verbatim(entry.rule) || rules.binary_search(&entry.rule).is_ok());- verify_style_answer_patch(self, |verifier| {- verifier.verify_cascade_answer(all, node, "compaction from updated winners");- });- true- }-- fn compact_pseudo_matches_from_updated_winners(- &mut self,- effects: &mut AnswerEffects,- node: StyleNodeID,- all: &mut Vec<RuleMatch>,- ) -> bool {- let Some((_, state)) = effects- .winners- .view(&self.winner_groups)- .token_for(WinnerGroupKey::current(node, self.program.version()))- .sparse()- .ok()- else {- return false;- };- if self.state_may_substitute_revert(state) {- return false;- }- let Some(element_rules) = self.winner_groups.rules_for_compaction(state) else {- return false;- };- type PseudoCompactionEntry<'a> = (tree::PseudoElementTarget, &'a [RuleID], Option<usize>);- let mut pseudo_rules: SmallVec<[PseudoCompactionEntry<'_>; 4]> = SmallVec::new();- for entry in all.iter() {- let Some(pseudo) = entry.pseudo_element else {- continue;- };- if self.program.sheet_origin(self.program.rule_sheet(entry.rule)) != CascadeOrigin::Author- || pseudo_rules.iter().any(|(target, _, _)| *target == pseudo)- {- continue;- }- let Some((_, state)) = effects- .winners- .view(&self.winner_groups)- .token_for(WinnerGroupKey::current_pseudo(node, pseudo, self.program.version()))- .sparse()- .ok()- else {- return false;- };- if self.state_may_substitute_revert(state) {- return false;- }- let Some(rules) = self.winner_groups.rules_for_compaction(state) else {- return false;- };- // A target with no winning declarations still needs one match to preserve its- // presence. A match already retained verbatim serves that purpose.- let marker = if rules.is_empty()- && !all- .iter()- .any(|entry| entry.pseudo_element == Some(pseudo) && self.compaction_keeps_verbatim(entry.rule))- {- all.iter().position(|entry| entry.pseudo_element == Some(pseudo))- } else {- None- };- pseudo_rules.push((pseudo, rules, marker));- }-- self.counters- .add(Counter::CascadeMatchesBeforeCompaction, all.len() as u64);- let mut index = 0;- all.retain(|entry| {- let retained = self.compaction_keeps_verbatim(entry.rule)- || match entry.pseudo_element {- None => element_rules.binary_search(&entry.rule).is_ok(),- Some(pseudo) => {- let (_, rules, marker) = pseudo_rules- .iter()- .find(|(target, _, _)| *target == pseudo)- .expect("every author pseudo target has a winner set");- *marker == Some(index) || rules.binary_search(&entry.rule).is_ok()- }- };- index += 1;- retained- });-- drop(pseudo_rules);- verify_style_answer_patch(self, |verifier| {- verifier.verify_cascade_answer(all, node, "pseudo compaction from updated winners");- });- true- }-- pub(super) fn matches_for_cascade_immediately(- &mut self,- all: Vec<RuleMatch>,- can_have_scope_duplicates: bool,- publish_winners_for: Option<StyleNodeID>,- ) -> Vec<RuleMatch> {- let mut effects = AnswerEffects::default();- let result = self.matches_for_cascade(&mut effects, all, can_have_scope_duplicates, publish_winners_for);- self.install_answer_effects(effects);- result- }-- pub(super) fn matches_for_cascade(- &mut self,- effects: &mut AnswerEffects,- mut all: Vec<RuleMatch>,- can_have_scope_duplicates: bool,- publish_winners_for: Option<StyleNodeID>,- ) -> Vec<RuleMatch> {- self.compact_matches_for_cascade(effects, &mut all, can_have_scope_duplicates, publish_winners_for);- all- }-- /// Re-reduce only the requested element properties from an exact retained match answer.- ///- /// This is the typed upquery for winner deletion repair. It consumes no selector facts and- /// returns `None` when the retained inventories do not completely describe the cascade.- pub(super) fn exact_cascade_winner_updates_for_properties(- &mut self,- node: StyleNodeID,- matches: &[RuleMatch],- pseudo: Option<tree::PseudoElementTarget>,- properties: &[u16],- ) -> Option<Vec<PropertyWinnerUpdate>> {- self.exact_cascade_winner_updates_for_properties_with_scratch(- node,- matches,- pseudo,- properties,- &mut Vec::new(),- )- }-- pub(super) fn exact_cascade_winner_updates_for_properties_with_scratch(- &mut self,- node: StyleNodeID,- matches: &[RuleMatch],- pseudo: Option<tree::PseudoElementTarget>,- properties: &[u16],- candidates: &mut Vec<OrderedCascadeCandidate>,- ) -> Option<Vec<PropertyWinnerUpdate>> {- debug_assert!(properties.windows(2).all(|pair| pair[0] < pair[1]));- if properties.is_empty() {- return Some(Vec::new());- }- if !self.cascade_winner_inventory_is_complete_for_target(matches, Some(node), pseudo) {- return None;- }-- let winners = self.resolved_cascade_winners_for_properties_with_scratch(- node,- matches,- pseudo,- Some(properties),- candidates,- );-- // Winners are an ordered subset of the requested properties.- let mut winners = winners.into_iter().peekable();- Some(- properties- .iter()- .copied()- .map(|property| PropertyWinnerUpdate {- property,- winner: winners.next_if(|winner| winner.property == property),- })- .collect(),- )- }-- /// Repair only the winner properties named by signed match changes.- ///- /// The retained exact answer supplies every contender, so deletion repair is a property-level- /// upquery over rule identities rather than another selector match or whole-cascade reduction.- pub(super) fn apply_cascade_winner_match_deltas(- &mut self,- effects: &mut AnswerEffects,- node: StyleNodeID,- matches: &[RuleMatch],- deltas: &[SelectorTruthDelta],- candidates: &mut Vec<OrderedCascadeCandidate>,- ) -> bool {- let mut targets: SmallVec<[Option<tree::PseudoElementTarget>; 3]> = SmallVec::new();- for delta in deltas {- let entry = self.programs.entry(delta.entry).1;- if !targets.contains(&entry.pseudo_element) {- targets.push(entry.pseudo_element);- }- }- targets.into_iter().all(|target| {- self.apply_cascade_winner_match_deltas_for_target(effects, node, matches, deltas, target, candidates)- })- }-- #[allow(clippy::too_many_arguments)]- pub(super) fn apply_cascade_winner_match_deltas_for_target(- &mut self,- effects: &mut AnswerEffects,- node: StyleNodeID,- matches: &[RuleMatch],- deltas: &[SelectorTruthDelta],- pseudo: Option<tree::PseudoElementTarget>,- candidates: &mut Vec<OrderedCascadeCandidate>,- ) -> bool {- if !self.cascade_winner_inventory_is_complete_for_target(matches, Some(node), pseudo) {- return false;- }- let key = pseudo.map_or_else(- || WinnerGroupKey::current(node, self.program.version()),- |pseudo| WinnerGroupKey::current_pseudo(node, pseudo, self.program.version()),- );- let Some((_, previous)) = effects.winners.view(&self.winner_groups).token_for(key).sparse().ok() else {- return false;- };-- let mut repair_properties = Vec::new();- let mut updates: Vec<PropertyWinnerUpdate> = Vec::new();- for delta in deltas {- let entry = *self.programs.entry(delta.entry).1;- if entry.pseudo_element != pseudo {- continue;- }- // A gated rule's declarations win only where its container conditions hold for the- // node, which the exact cascade decides.- if self.program.rule_is_gated_by_container_query(delta.rule) {- return false;- }- let mut matched_rule = None;- let mut priorities = [None; 2];- for &declared in self.program.declared_properties_of(delta.rule) {- if !property_is_longhand(declared.property) {- continue;- }- if delta.change == SetChange::Removed- && self- .winner_groups- .winner_in_state(previous, declared.property)- .is_some_and(|winner| {- winner.source != WinnerSource::Rule(delta.rule)- && winner.source != WinnerSource::ExactCascade- && winner.key.continuation == CascadeContinuationID::default()- })- {- continue;- }- if delta.change == SetChange::Removed- || matches!(- declared.operator,- CascadeOperator::Revert | CascadeOperator::RevertLayer- )- {- repair_properties.push(declared.property);- continue;- }- let previous_winner = self.winner_groups.winner_in_state(previous, declared.property);- if previous_winner.is_some_and(|winner| winner.key.continuation != CascadeContinuationID::default()) {- repair_properties.push(declared.property);- continue;- }- if matched_rule.is_none() {- matched_rule = matches.iter().find(|matched| {- matched.rule == delta.rule- && self.programs.entry_id(matched.program, matched.entry) == delta.entry- });- }- let Some(matched) = matched_rule else {- return false;- };- let priority = *priorities[declared.important as usize].get_or_insert_with(|| {- self.cascade_priority_of(- node,- delta.rule,- matched.tree_scope,- entry.specificity,- matched.scope_proximity,- declared.important,- )- });- if previous_winner.is_some_and(|winner| priority < winner.priority) {- continue;- }- let winner = PropertyWinner {- property: declared.property,- important: declared.important,- key: Self::retained_rule_winner_key(declared),- priority,- source: WinnerSource::Rule(delta.rule),- };- if let Some(update) = updates.iter_mut().find(|update| update.property == declared.property) {- let pending = update.winner.as_mut().expect("an added declaration carries a winner");- if priority >= pending.priority {- *pending = winner;- }- } else {- updates.push(PropertyWinnerUpdate {- property: declared.property,- winner: Some(winner),- });- }- }- }- repair_properties.sort_unstable();- repair_properties.dedup();- if !repair_properties.is_empty() {- let Some(repairs) = self.exact_cascade_winner_updates_for_properties_with_scratch(- node,- matches,- pseudo,- &repair_properties,- candidates,- ) else {- return false;- };- updates.retain(|update| repair_properties.binary_search(&update.property).is_err());- updates.extend(repairs);- }- updates.sort_unstable_by_key(|update| update.property);-- let (state, _) =- self.with_cascade_interning_counters(|groups| groups.apply_property_updates(previous, &updates));- let published = if let Some(pseudo) = pseudo {- effects- .winners- .set_pseudo(&mut self.winner_groups, node, pseudo, state, self.program.version())- } else {- effects- .winners- .set(&mut self.winner_groups, node, state, self.program.version())- };-- if published {- self.counters.bump(Counter::CascadeNodeHandlesPublished);- }- published- }-- pub(super) fn cascade_winner_inventory_is_complete_for_target(- &self,- matches: &[RuleMatch],- node: Option<StyleNodeID>,- pseudo: Option<tree::PseudoElementTarget>,- ) -> bool {- !(matches- .iter()- .filter(|entry| entry.pseudo_element == pseudo)- .any(|entry| {- !self.container_gate_is_held(node, entry.rule)- || !self.program.declarations_are_complete_for(entry.rule)- })- || (pseudo.is_none() && node.is_some_and(|node| !self.facts.element_custom_declarations(node).is_empty())))- }-- /// Whether a pseudo-element's rules declare nothing past its longhand winners but custom- /// properties, which its state holds itself.- fn cascade_winner_inventory_is_complete_but_for_custom_properties_for_target(- &self,- node: StyleNodeID,- matches: &[RuleMatch],- pseudo: tree::PseudoElementTarget,- ) -> bool {- !matches- .iter()- .filter(|entry| entry.pseudo_element == Some(pseudo))- .any(|entry| !self.container_gate_is_held(Some(node), entry.rule))- }-- /// Where a tree scope stands among the encapsulation contexts that decide for an element,- /// outermost first, the order its cascade applies them in: the document, the shadow trees the- /// element is in from the outermost inwards, the ones holding the slots it is assigned to along- /// its assignment chain, then the element's own shadow tree, for `:host`. That is the- /// shadow-including tree order of those trees. `None` when the scope is none of them.- pub(super) fn author_context_index(&self, node: StyleNodeID, scope: TreeScopeID) -> Option<u32> {- let tree_scope = self.tree.tree_scope(node);- let enclosing = std::iter::successors(Some(tree_scope), |¤t| {- let host = self.scope_root(current).and_then(|root| self.tree.host_of(root))?;- Some(self.tree.tree_scope(host))- });- let is_context = enclosing- .take(self.tree_scope_depth(tree_scope) as usize + 1)- .any(|enclosing| enclosing == scope)- || self.scopes_slotted_into(node).any(|slotted_into| slotted_into == scope)- || self.own_shadow_tree(node) == Some(scope);- is_context.then(|| self.encapsulation_context(node, scope))- }-- /// Where the cascade of `node` weighs a match from `scope`, as `author_context_index` places- /// it. Each tree the element is in or slotted into stands at its depth, one deeper than the+ /// Where the cascade of `node` weighs a match from `scope`. Each tree the element is in or slotted into stands at its depth, one deeper than the/// last, so only the element's own shadow tree, after all of those, stands elsewhere.- fn encapsulation_context(&self, node: StyleNodeID, scope: TreeScopeID) -> u32 {+ pub(super) fn encapsulation_context(&self, node: StyleNodeID, scope: TreeScopeID) -> u32 {if self.own_shadow_tree(node) != Some(scope) {return self.tree_scope_depth(scope);}let slotted_into = self.scopes_slotted_into(node).count() as u32;- self.tree_scope_depth(self.tree.tree_scope(node)) + slotted_into + 1+ self.tree_scope_depth(self.projection.tree_scope(node)) + slotted_into + 1}/// The tree the element's shadow root roots, where its `:host` rules decide from.fn own_shadow_tree(&self, node: StyleNodeID) -> Option<TreeScopeID> {- self.tree+ self.projection.shadow_root_of(node).and_then(|shadow_root| self.scope_by_root.get(shadow_root))}- pub(super) fn cascade_winner_inventory_is_complete(- &self,- matches: &[RuleMatch],- node: Option<StyleNodeID>,- ) -> bool {- // Checking every target covers every match. Check each inventory once instead- // of scanning the answer again for every rule matching the same pseudo target.- !matches.iter().any(|entry| {- !self.container_gate_is_held(node, entry.rule) || !self.program.declarations_are_complete_for(entry.rule)- }) && !node.is_some_and(|node| !self.facts.element_custom_declarations(node).is_empty())- }-- /// As `cascade_winner_inventory_is_complete`, for winners published in the transaction `effects`- /// belong to. Whether a gated rule is held is noted as the node's winners are published, so- /// before that it is what held for the winners published last; an ancestor's answer that- /// moves now leaves the rule undecided again.- pub(super) fn cascade_winner_inventory_is_complete_in_transaction(- &self,- effects: &AnswerEffects,- matches: &[RuleMatch],- node: StyleNodeID,- ) -> bool {- self.cascade_winner_inventory_is_complete(matches, Some(node))- && !(matches- .iter()- .any(|entry| self.program.rule_is_gated_by_container_query(entry.rule))- && self.container_ancestor_answer_moves(node, effects))- }-- /// Exactly match every style node in the document scope against the attached program.- ///- /// This is the optimized batch path running on the real document. It packs the facts the store- /// has published and evaluates the match programs its dispatch and prefix state reach. It- /// reports how many concrete rule matches it found, or the node whose facts were missing - never- /// a partial answer.- pub fn match_document(&mut self, root: StyleNodeID) -> Result<usize, Incomplete> {- let nodes = self.elements_under(root);-- let mut batch = StyleNodeFacts::new();- self.facts.materialize(nodes.iter().copied(), &mut batch);-- // One dispatch per tree, because a sheet decides only in the scopes it is attached to.- let mut by_scope: Column<Vec<StyleNodeID>> = Column::default();- for &node in &nodes {- let scope = self.tree.tree_scope(node);- by_scope.entry(scope.0 as usize).push(node);- // A slotted element is asked the rules of the tree it is slotted into as well, because- // `::slotted()` in that tree names it and no rule of its own tree can.- for slotted in self.scopes_slotted_into(node) {- if slotted != scope {- by_scope.entry(slotted.0 as usize).push(node);- }- }- // A part is asked the rules of the scope it is exposed to, because `::part()` there- // names it and no rule of its own tree can be addressed from outside.- for exposed in self.part_exposure_scopes(node) {- if exposed != scope {- by_scope.entry(exposed.0 as usize).push(node);- }- }- }- let can_have_scope_duplicates = by_scope.iter().filter(|nodes| !nodes.is_empty()).take(2).count() > 1;-- let mut matches = RuleMatches::new();- let mut dispatch_workspace = DispatchCandidateWorkspace::default();- let mut ancestor_requirements_cache = AncestorRequirementsCache::default();- let mut result = Ok(());- for (index, scope_nodes) in by_scope.into_iter().enumerate() {- if scope_nodes.is_empty() {- continue;- }- let scope = TreeScopeID(u32::try_from(index).expect("tree scope identity space exhausted"));- let (_, dispatch) = self.prepare_scope_program(scope);- let ancestor_requirements = ancestor_requirements_cache.prepare(&self.tree, &batch, &dispatch, None);- // `:host` names the host of this tree, which stands outside it, so the tree's own rules- // are asked of it as well.- let host = self.scope_root(scope).and_then(|root| self.tree.host_of(root));- for node in scope_nodes.into_iter().chain(host) {- let (matched, effects) = self.match_node_in_scope(- node,- scope,- &dispatch,- &batch,- &mut dispatch_workspace,- Some(ancestor_requirements),- None,- None,- BatchMatchAttempt {- matches: &mut matches,- requests: None,- completed: None,- deferred_prefix_matches: None,- answer_is_exact: None,- cascade_only: false,- },- );- self.append_witness_effects(effects);- if let Err(incomplete) = matched {- result = Err(incomplete);- break;- }- }- if result.is_err() {- break;- }- }- self.install_witness_effects();- ancestor_requirements_cache.release();-- // Within one style node the matches come out in the order the cascade applies them, so a- // consumer reads them rather than sorting them again.- let match_count = result.map(|()| {- self.order_matches_in_cascade(matches.as_mut_vec(), can_have_scope_duplicates);- matches.len()- });-- matches.release();-- match_count- }-/// Every tree whose `::slotted()` can name this element.////// A slot is itself a slottable, so an element can be assigned to a slot that is assigned to@@ -1707,7 +34,8 @@ impl RetainedState {// into: "find flattened slottables" recurses into its own slottables rather than appending// it. So no scope names it through `::slotted()`, even though its assignment is what carries// the chain onward for the nodes below it.- let is_reslotted_slot = self.facts.is_slot(node) && self.tree.tree_scope(node) != TreeScopeID::DOCUMENT;+ let is_reslotted_slot = self.projection.written_facts(node).is_some_and(|facts| facts.is_slot())+ && self.projection.tree_scope(node) != TreeScopeID::DOCUMENT;// A chain is at most as deep as the trees are nested, and a cycle is impossible - a slot// cannot be assigned to itself - but a bound keeps a corrupted column from spinning.const MAX_REASSIGNMENTS: usize = 32;@@ -1718,9 +46,9 @@ impl RetainedState {return None;}remaining -= 1;- let slot = self.tree.assigned_slot_of(current)?;+ let slot = self.projection.assigned_slot_of(current)?;current = slot;- Some(self.tree.tree_scope(slot))+ Some(self.projection.tree_scope(slot))})}@@ -1736,11 +64,11 @@ impl RetainedState {let Some(root) = self.scope_root(scope) else {break;};- let Some(host) = self.tree.host_of(root) else {+ let Some(host) = self.projection.host_of(root) else {break;};depth += 1;- let next = self.tree.tree_scope(host);+ let next = self.projection.tree_scope(host);if next == scope {break;}@@ -1749,114 +77,13 @@ impl RetainedState {depth}- /// The encapsulation context a match decides in, as the host whose shadow tree that is.- ///- /// A sheet the asking scope does not hold is one of the origins that decide everywhere, and- /// those are attached to the document, which is the outermost context - so the scope a match- /// carries is not always the context it is weighed in. The host is reported rather than the- /// scope because the host is an element, which is what the consumer can name.- #[must_use]- pub fn cascade_context_host(&self, rule: RuleID, tree_scope: TreeScopeID) -> u32 {- self.scope_root(self.cascade_context_scope(rule, tree_scope))- .and_then(|root| self.tree.host_of(root))- .map_or(0, StyleNodeID::raw)- }-- pub(super) fn cascade_context_scope(&self, rule: RuleID, tree_scope: TreeScopeID) -> TreeScopeID {- if tree_scope == TreeScopeID::DOCUMENT {- return tree_scope;- }- let sheet = self.program.rule_sheet(rule);- match self.program.attachment_in_scope(sheet, tree_scope).is_some() {- true => tree_scope,- false => TreeScopeID::DOCUMENT,- }- }-- /// Where one rule's declarations, matched from `tree_scope`, sit in the cascade of `node`.- ///- /// The components that change globally - layer topology, sheet order - are read through the- /// identities the rule references rather than copied into it, so moving a layer or a sheet- /// updates one token instead of every rule that lives in it.- #[must_use]- pub(super) fn cascade_priority_of(- &self,- node: StyleNodeID,- rule: RuleID,- tree_scope: TreeScopeID,- specificity: Specificity,- scope_proximity: u32,- important: bool,- ) -> CascadePriority {- let context_scope = self.cascade_context_scope(rule, tree_scope);- self.cascade_priority_in_context(- rule,- tree_scope,- self.encapsulation_context(node, context_scope),- specificity,- scope_proximity,- important,- )- }-- /// As `cascade_priority_of`, for any element of `tree_scope` itself, which weighs its own tree- /// and the document at their depths: a rule decides for such an element from no other context.- #[must_use]- pub(super) fn own_scope_cascade_priority_of(- &self,- rule: RuleID,- tree_scope: TreeScopeID,- specificity: Specificity,- scope_proximity: u32,- important: bool,- ) -> CascadePriority {- let context_scope = self.cascade_context_scope(rule, tree_scope);- self.cascade_priority_in_context(- rule,- tree_scope,- self.tree_scope_depth(context_scope),- specificity,- scope_proximity,- important,- )- }-- fn cascade_priority_in_context(- &self,- rule: RuleID,- tree_scope: TreeScopeID,- context_depth: u32,- specificity: Specificity,- scope_proximity: u32,- important: bool,- ) -> CascadePriority {- let sheet = self.program.rule_sheet(rule);- let version = self.program.rule_version(rule);- // A sheet the element's own scope does not hold is one of the origins that decide- // everywhere, and those are attached to the document, which is the outermost context.- let attachment = self.program.attachment_in_scope(sheet, tree_scope);- let context_scope = attachment.map_or(TreeScopeID::DOCUMENT, |attachment| attachment.tree_scope);- let attachment = attachment.or_else(|| self.program.attachment_in_scope(sheet, TreeScopeID::DOCUMENT));- CascadePriority::new(PriorityInputs {- origin: self.program.sheet_origin(sheet),- important,- context_depth,- element_attachment: ElementAttachment::Rule,- layer_rank: self.program.layer_rank(context_scope, version.layer),- specificity,- scope_proximity,- sheet_rank: attachment.map_or(0, |attachment| self.program.sheet_rank(attachment)),- rule_rank: self.program.rule_rank(rule),- })- }-pub(super) fn element_cascade_priority(&self,node: StyleNodeID,kind: ElementDeclarationKind,important: bool,) -> CascadePriority {- let tree_scope = self.tree.tree_scope(node);+ let tree_scope = self.projection.tree_scope(node);let (origin, element_attachment) = match kind {ElementDeclarationKind::InlineStyle => (CascadeOrigin::Author, ElementAttachment::InlineStyle),ElementDeclarationKind::PresentationalHint | ElementDeclarationKind::SvgPresentationAttribute => (@@ -1869,225 +96,35 @@ impl RetainedState {important,context_depth: self.tree_scope_depth(tree_scope),element_attachment,- layer_rank: self.program.layer_rank(tree_scope, CascadeLayerID::UNLAYERED),+ layer_rank: self.rules.layer_rank(tree_scope, CascadeLayerID::UNLAYERED),specificity: Specificity::default(),scope_proximity: u32::MAX,sheet_rank: u64::MAX,rule_rank: u64::MAX,})}-- pub(super) fn node_has_element_declaration_input(&self, node: StyleNodeID) -> bool {- !self.facts.element_custom_declarations(node).is_empty()- || ElementDeclarationKind::ALL- .iter()- .any(|&kind| !self.facts.element_declared_properties(node, kind).is_empty())- }-- /// Advance staged local facts to the transaction's final snapshot.- pub(super) fn apply_staged_facts(&mut self, transaction: &mut StyleTransaction) {- if self.facts.has_staged_input() {- transaction.install_before_facts(self.facts.staged_before_facts());- }- self.facts.apply_staged();- }-- /// Drop routing entry points for rules whose sheet is attached nowhere and not kept for reattachment.- ///- /// The router already skips such rules one route at a time, but enumerating their entry points- /// is itself a cost that grows with every sheet that ever came and went: a page that repeatedly- /// inserts and removes `<style>` elements would make every later mutation pay for all of the- /// dead ones. The rules stay compiled and keep their identity, so a sheet that reattaches gets- /// its routes back from `restore_routing_for_reattached_sheet`.- fn shed_routing_for_detached_sheets(&mut self) {- if !self.routing_needs_detachment_sweep {- return;- }- self.routing_needs_detachment_sweep = false;- let mut excluded_sheets = BitColumn::default();- let mut attached_sheets = Vec::new();- for (sheet, attached) in self.program.sheets_with_attachment_state() {- if attached || self.sheets_kept_for_reattachment.contains(sheet.0 as usize) {- attached_sheets.push(sheet);- } else {- excluded_sheets.set(sheet.0 as usize, true);- }- }- if excluded_sheets == self.sheets_excluded_from_routing {- return;- }- let mut rebuilt_routing = RoutingRegistry::new();- for sheet in attached_sheets {- for rule in self- .program- .rules_in_sheet(sheet)- .into_iter()- .filter(|&rule| self.program.rule_is_live(rule))- {- if let Some(program) = self.program.rule_version(rule).selector_program {- rebuilt_routing.add_rule(rule, program, &self.programs);- }- }- }- rebuilt_routing.prepare_route_liveness(&self.program, &self.programs);- self.routing = Arc::new(rebuilt_routing);- self.sheets_excluded_from_routing = excluded_sheets;- }-- pub(super) fn sweep_selector_programs(&mut self) {- if !self.selector_programs_need_sweep {- return;- }- let live_rules = self.program.live_selector_programs().collect::<Vec<_>>();- let mut referenced = Vec::new();- for &(_, program) in &live_rules {- if referenced.len() <= program.0 as usize {- referenced.resize(program.0 as usize + 1, false);- }- referenced[program.0 as usize] = true;- }- self.match_answers.mark_referenced_selector_programs(&mut referenced);- // NB: A scope program's shape names selector programs, and the templates follow the shapes of live scope- // programs. Keep the selector programs of those scopes resolve to, and drop below the ones no scope- // resolves to that name a recycled selector program, so that no live shape names a recycled identity.- for program in self.scope_programs.iter().flatten() {- if program.scope_count == 0 {- continue;- }- for &(selector_program, _) in program.shapes.dispatch.0.iter() {- if referenced.len() <= selector_program.0 as usize {- referenced.resize(selector_program.0 as usize + 1, false);- }- referenced[selector_program.0 as usize] = true;- }- }- if !self.programs.has_unreferenced_programs(&referenced) {- self.selector_programs_need_sweep = false;- return;- }-- let mut rebuilt_routing = RoutingRegistry::new();- let mut excluded_sheets = BitColumn::default();- for &(rule, program) in &live_rules {- // A detached sheet's rules keep no routing entry points; see- // `shed_routing_for_detached_sheets`.- let sheet = self.program.rule_sheet(rule);- if !self.sheet_keeps_routing(sheet) {- excluded_sheets.set(sheet.0 as usize, true);- continue;- }- rebuilt_routing.add_rule(rule, program, &self.programs);- }- self.sheets_excluded_from_routing = excluded_sheets;- rebuilt_routing.prepare_route_liveness(&self.program, &self.programs);- self.routing = Arc::new(rebuilt_routing);-- self.relational_witnesses.clear_all();-- self.scope_dispatch_templates.retain(|shape, _| {- shape- .0- .iter()- .all(|&(program, _)| referenced.get(program.0 as usize).copied().unwrap_or(false))- });- let names_swept_program = |shapes: &ScopeTemplateShapes| {- shapes- .dispatch- .0- .iter()- .any(|&(program, _)| !referenced.get(program.0 as usize).copied().unwrap_or(false))- };- let stale_scope_programs = (0..self.scope_programs.len())- .filter(|&index| {- self.scope_programs[index]- .as_ref()- .is_some_and(|program| names_swept_program(&program.shapes))- })- .map(|index| ScopeProgramID(u32::try_from(index).expect("scope program identity space exhausted")))- .collect::<Vec<_>>();- for id in stale_scope_programs {- self.remove_scope_program(id);- }- self.scope_cascade_templates.clear();- self.ancestor_dispatch_templates.clear();- // NB: The retired shapes may name swept selector programs, whose identities are recycled.- self.retired_scope_templates.clear();- self.programs.sweep_unreferenced(&referenced);-- self.selector_programs_need_sweep = false;- }}impl StyleEngine {/// Normalize the pending inputs without advancing the committed snapshot.- pub(super) fn drain_transaction(&mut self) -> StyleTransaction {- self.merge_deferred_geometry_transaction();- self.host.initial_tree_bulk_load_is_pending = false;+ pub(super) fn drain_transaction(&mut self) -> StyleUpdate {+ // A transaction taken other than to flush a geometry read's seal takes everything written.+ self.retained.projection.drop_seal();self.finalize_staged_sheet_rule_replacements();- // A diagnostic or retained planning snapshot may still hold this exact immutable routing- // program. It remains queryable in builder form; compact it at the next unshared boundary.- if let Some(routing) = Arc::get_mut(&mut self.retained.routing)- && routing.finish_directories()- {}- self.host.journal.take_transaction(&self.retained.counters)- }-- /// Advance staged program and tree state to the transaction's final snapshot.- pub(super) fn apply_staged_structural_state(&mut self) {- self.commit_staged_program();- self.host.program_staging.rule_change_is_carried_by_sheet.clear();- self.apply_staged_tree_deltas();- }-- /// Finish the transaction metadata which depends on committed program state.- pub(super) fn finish_staged_application(&mut self, transaction: &mut StyleTransaction) {- transaction.program_base_version = self.host.program_staging.base_version.take();- let mut program_joins = Vec::new();- for input in &transaction.inputs {- self.append_program_join_deltas(input, &mut program_joins);- }- transaction.install_program_joins(program_joins);- let mut declaration_changes = std::mem::take(&mut self.host.program_staging.rule_declaration_changes);- declaration_changes.retain(|change| {- transaction- .inputs- .binary_search_by_key(&InputKey::RuleField(change.rule, RuleField::Declarations), |input| {- input.key- })- .is_ok()- });- transaction.install_rule_declaration_changes(- declaration_changes- .into_iter()- .map(|change| RuleDeclarationChange {- rule: change.rule,- old_properties: change.old_properties,- new_properties: change.new_properties,- custom_declarations_changed: change.custom_declarations_changed,- })- .collect(),+ let transaction = self.host.element_inputs.take_transaction();+ self.retained.counters.add(+ Counter::NormalizedUniqueKeys,+ (transaction.declarations.len() + transaction.style_inputs.len()) as u64,);+ transaction}/// Settle inputs which cannot be planned while the document has no style root. Exact element/// style reactions are edge-triggered, so preserve them for the first transaction with a root.pub(crate) fn flush_without_document_root(&mut self) {let transaction = self.take_transaction();- // NB: Without routing, retained relations still describe the previous tree.- if !self.host.tree_staging.is_empty() {- self.discard_retained_prefix_caches();- }- for input in &transaction.inputs {- if let (- InputKey::ElementStyleInput(node),- InputValue::ElementStyleInput {- reaction,- inherited_style_groups,- },- ) = (input.key, input.new)- {- self.defer_element_style_input(node, reaction, inherited_style_groups);- }+ for &(node, input) in &transaction.style_inputs {+ self.defer_element_style_input(node, input.reaction, input.inherited_style_groups);}// Held back rather than owed: without a root there is no transaction to take them.self.host.deferred_element_style_inputs_are_pending = false;@@ -2110,33 +147,31 @@ impl StyleEngine {}/// Release a drained transaction's scratch charge.- pub fn release_transaction(&mut self, transaction: StyleTransaction) {+ pub fn release_transaction(&mut self, transaction: StyleUpdate) {transaction.release();self.forget_departed_elements();- self.host.tree_staging.clear();+ // NB: Nothing is written between the barrier and here, so this commits only the+ // departed elements' facts leaving.+ self.retained.projection.release();- self.retained.facts.release_staging();self.host.program_staging.clear();- self.host.environment_move_changed_names.clear();- self.sweep_selector_programs();- self.retained.drop_unused_scope_templates();- self.shed_routing_for_detached_sheets();+ // NB: With nothing staged, the committed versions are every version naming a sheet's+ // selectors. The store is asked first, as writing to it copies what a fork shares.+ if self.retained.rules.wants_letting_go_of_selectors() {+ self.retained.rules.let_go_of_unnamed_selectors();+ }}pub(super) fn collect_live_style_atoms(&self) -> (HashSet<StyleAtomID>, u64) {assert!(- self.host.tree_staging.is_empty(),- "style atom sweeping requires settled tree staging"- );- assert!(- self.retained.facts.staging_is_empty(),- "style atom sweeping requires settled fact staging"+ !self.retained.projection.has_written_links(),+ "style atom sweeping requires a settled tree");let mut atoms = HashSet::default();let mut visited = self.retained.tree.collect_atoms(&mut atoms);- visited += self.retained.facts.collect_atoms(&mut atoms);- visited += self.retained.program.collect_atoms(&mut atoms);- visited += self.retained.programs.collect_atoms(&mut atoms);+ visited += self.retained.projection.collect_atoms(&mut atoms);+ visited += self.retained.element_declarations.collect_atoms(&mut atoms);+ visited += self.retained.rules.collect_atoms(&mut atoms);if !self.retained.html_element_namespace.is_none() {atoms.insert(self.retained.html_element_namespace);}@@ -2147,31 +182,25 @@ impl StyleEngine {if !self.retained.atoms.should_sweep() || self.host.defers_atom_sweep {return;}- if self.retained.batch_matching_traversal.is_some() {- self.retained- .counters- .bump(Counter::AtomSweepsDeferredForActiveTraversal);- return;- }- self.retained.facts.sweep_auxiliary_catalogs_without_sync();let (mut live, visited) = self.collect_live_style_atoms();self.retained.atoms.mark_sweep_dependencies(&mut live);loop {let previous_live_count = live.len();- self.retained.facts.extend_live_attribute_name_forms(&mut live);+ self.retained.projection.extend_live_attribute_name_forms(&mut live);self.retained.atoms.mark_sweep_dependencies(&mut live);if live.len() == previous_live_count {break;}}let reclaimable = self.retained.atoms.reclaimable_for_sweep(&live);- self.retained.facts.forget_atoms(&reclaimable);+ // NB: The host forgets what its catalogs spell of the reclaimed atoms as it learns of them.self.retained.custom_property_environments.forget_names(&reclaimable);let is_reclaimed = |atom: &StyleAtomID| reclaimable.binary_search(atom).is_ok();if self.retained.tested_attribute_names.iter().any(is_reclaimed) {Arc::make_mut(&mut self.retained.tested_attribute_names).retain(|atom| !is_reclaimed(atom));}- let relational_arrival_key_is_reclaimed = |key: &RoutingKey| key.atom().is_some_and(|atom| is_reclaimed(&atom));+ let relational_arrival_key_is_reclaimed =+ |key: &DispatchKey| key.atom().is_some_and(|atom| is_reclaimed(&atom));if self.retained.relational_arrival_keys@@ -2204,64 +233,35 @@ impl StyleEngine {/// left behind here would be read as the next occupant's. Dropping it at the transaction/// boundary keeps the row alive for exactly as long as routing needs it.pub(super) fn forget_departed_elements(&mut self) {- let departed: Vec<StyleNodeID> = self- .host- .tree_staging- .rows()- .filter_map(|(node, _, after)| after.is_none().then_some(node))+ let projection = &self.retained.projection;+ let departed: Vec<StyleNodeID> = projection+ .relations_written()+ .filter(|&node| projection.written_relations(node).is_none()).collect();if departed.is_empty() {return;}- // Routing walks a retained prefix relation through the departures it plans for. A- // transaction that planned nothing for them (a rootless flush does not route at all) left- // them live in it, and the relation would go on answering for nodes that have no facts.- if self- .retained- .prefix_caches- .borrow()- .states- .relation_holds_any(&departed)- {- self.discard_retained_prefix_caches();- }for node in departed {- self.retained.facts.forget(node);- self.retained.shadow_host_backing_pseudo_matches.remove(&node);- self.retained- .retained_match_answers- .forget(&mut self.retained.match_answers, node);+ // NB: The host forgot the element's row as it published its departure.+ self.retained.element_declarations.forget(node);if let Some(tree_scope) = self.retained.scope_by_root.remove(node) {self.retained.scope_roots[tree_scope.0 as usize] = None;}}- // The catalog sweep needs unique primary rows, like the atom sweep; while a traversal- // borrows them the dead entries wait for the next boundary.- if self.retained.batch_matching_traversal.is_none() {- self.retained.facts.sweep_auxiliary_catalogs();- }- }-- /// The journal's entry limit is written in connected elements, so it has to follow the live- /// element count rather than a high-water mark.- pub(super) fn update_journal_entry_limit(&mut self) {- self.host- .journal- .set_document_entry_limit(self.retained.tree.connected_element_count());}}impl StyleEngine {/// Advance every staged input family to the transaction's final snapshot.- pub(super) fn apply_staged_transaction(&mut self, transaction: &mut StyleTransaction) {- self.apply_staged_structural_state();- self.apply_staged_facts(transaction);- self.finish_staged_application(transaction);+ pub(super) fn apply_staged_transaction(&mut self, transaction: &mut StyleUpdate) {+ transaction.rule_changes = self.commit_staged_program();+ self.settle_tree_at_barrier();+ self.retained.projection.commit();}/// Normalize and apply the staged inputs into one transaction. A required style observation/// drains here first, so normalization never combines changes across an observation boundary.- pub fn take_transaction(&mut self) -> StyleTransaction {+ pub fn take_transaction(&mut self) -> StyleUpdate {let mut transaction = self.drain_transaction();self.apply_staged_transaction(&mut transaction);transaction@@ -2270,8 +270,19 @@ impl StyleEngine {/// Release a transaction taken through the bridge and reclaim atoms before the bridge installs/// a new primary view. The returned reclamation batch lets C++ purge its atom memos before any/// reclaimed identity can be reused.- pub(super) fn release_transaction_and_sweep_atoms(&mut self, transaction: StyleTransaction) {+ pub(super) fn release_transaction_and_sweep_atoms(&mut self, transaction: StyleUpdate) {self.release_transaction(transaction);self.sweep_style_atoms();+ self.sweep_specified_values();+ }++ /// Drop the canonical values no element declares any more, once the set doubled since the+ /// last sweep: a script rewriting an inline style enters a value for each write, which nothing+ /// else would let go of.+ pub(super) fn sweep_specified_values(&mut self) {+ if !self.retained.canonical_values.should_sweep() || self.host.defers_atom_sweep {+ return;+ }+ self.retained.canonical_values.sweep();}}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/bloom.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/bloom.rsnew file mode 100644index 00000000000..d2f70b51438--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/bloom.rs@@ -0,0 +1,324 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The ancestor Bloom filter: a counting filter over the ids, classes and tag names of the elements+//! above the one being matched, maintained as the traversal descends and climbs. A selector whose+//! combinator chain requires an ancestor key the filter lacks cannot match, so its ancestor walk is+//! never run.++use super::super::*;+use crate::css::selector_arena::IdOrClass;+use smallvec::SmallVec;++const KEY_BITS: u32 = 12;+const SLOT_COUNT: usize = 1 << KEY_BITS;+const KEY_MASK: u32 = (1 << KEY_BITS) - 1;++/// The most ancestor keys one selector checks against the filter. More would cost more probes than+/// the rejections they add.+const MAX_REQUIRED_HASHES: usize = 4;++/// The bits of a hash, all of which the filters read.+const HASH_BITS: u32 = 2 * KEY_BITS;+const HASH_MASK: u32 = (1 << HASH_BITS) - 1;++/// A filter hash of `HASH_BITS` bits, never zero, so that zero can stand for no hash.+fn hash_of(kind: u32, atom: StyleAtomID) -> u32 {+ let mixed = (u64::from(atom.0) | (u64::from(kind) << 32)).wrapping_mul(0x9E37_79B9_7F4A_7C15);+ ((mixed >> 32) as u32 & HASH_MASK).max(1)+}++pub(super) fn id_hash(atom: StyleAtomID) -> u32 {+ hash_of(1, atom)+}++pub(super) fn class_hash(atom: StyleAtomID) -> u32 {+ hash_of(2, atom)+}++pub(super) fn tag_hash(atom: StyleAtomID) -> u32 {+ hash_of(3, atom)+}++pub(super) fn attribute_hash(atom: StyleAtomID) -> u32 {+ hash_of(4, atom)+}++/// The ancestor keys a selector entry requires, as filter hashes, in a fixed number of slots so a+/// rule bucket holds them inline: three in the low bits of the words, and the fourth spread over+/// their high bytes. An unused slot is zero.+#[derive(Clone, Copy, Default)]+pub(super) struct AncestorHashes {+ packed: [u32; 3],+}++const _: () = assert!(size_of::<AncestorHashes>() == 12);+const _: () = assert!(HASH_BITS == 24 && MAX_REQUIRED_HASHES == 4);++impl AncestorHashes {+ /// The keys every ancestor compound reached through `A B` and `A > B` from `compound`+ /// necessarily carries, past `A + B` and `A ~ B` too, since siblings share their ancestors.+ /// Only features standing directly in such a compound count, and those of the one selector of+ /// a `:is()`, `:where()` or `&` holding a single one: anything under a negation, a disjunction or+ /// a relative query may hold elsewhere or not at all. Only names written in ASCII lowercase+ /// count, which every document carries as written, and attribute names only where no namespace+ /// is named.+ pub(super) fn required_left_of(compound: crate::css::selector::Selector<'_>) -> Self {+ let mut hashes: SmallVec<[u32; MAX_REQUIRED_HASHES]> = SmallVec::new();+ collect_ancestor_hashes(compound, false, &mut hashes);+ let slot = |index: usize| hashes.get(index).copied().unwrap_or(0);+ let fourth = slot(3);+ Self {+ packed: std::array::from_fn(|index| slot(index) | ((fourth >> (8 * index)) & 0xFF) << HASH_BITS),+ }+ }++ /// The words the hashes are packed in, for a holder to keep those not zero.+ pub(super) fn packed_words(&self) -> [u32; 3] {+ self.packed+ }++ pub(super) fn from_packed_words(packed: [u32; 3]) -> Self {+ Self { packed }+ }++ /// The hashes, without the unused slots.+ fn hashes(&self) -> impl Iterator<Item = u32> {+ let [first, second, third] = self.packed;+ let fourth = (first >> HASH_BITS) | (second >> HASH_BITS) << 8 | (third >> HASH_BITS) << 16;+ [first & HASH_MASK, second & HASH_MASK, third & HASH_MASK, fourth]+ .into_iter()+ .filter(|&hash| hash != 0)+ }+}++/// Add the keys of the compounds of `selector` an ancestor of its subject matches to `hashes`, from+/// the compound left of the subject's, or from the subject's own where `from_subject`, as for the+/// one selector of a `:is()` standing in a compound an ancestor matches.+fn collect_ancestor_hashes(+ selector: crate::css::selector::Selector<'_>,+ from_subject: bool,+ hashes: &mut SmallVec<[u32; MAX_REQUIRED_HASHES]>,+) {+ use crate::css::selector::Combinator;+ let mut current = selector;+ let mut collects = from_subject;+ loop {+ if collects && !collect_compound_hashes(current, hashes) {+ return;+ }+ let Some((combinator, left)) = current.left() else {+ return;+ };+ current = left;+ collects = match combinator {+ Combinator::Descendant | Combinator::ImmediateChild => true,+ // A sibling's own keys say nothing of the subject's ancestors.+ Combinator::NextSibling | Combinator::SubsequentSibling => false,+ _ => return,+ };+ }+}++/// Add the keys of the first compound of `compound`, one an ancestor matches, to `hashes`, or+/// answer false where the walk goes no further: the compound names the host, which stands above a+/// shadow tree's elements in no tree the filter walks.+fn collect_compound_hashes(+ compound: crate::css::selector::Selector<'_>,+ hashes: &mut SmallVec<[u32; MAX_REQUIRED_HASHES]>,+) -> bool {+ use crate::css::selector::{NamespaceType, PseudoClassType, SimpleSelector};+ use crate::css::selector_arena::Nesting;+ let simple_selectors = compound.first_compound().simple_selectors;+ if simple_selectors.iter().any(|simple| {+ super::super::component_matching::mentions(&simple, &|simple| {+ matches!(simple, SimpleSelector::PseudoClass(pseudo_class) if pseudo_class.pseudo_class == PseudoClassType::Host)+ })+ }) {+ return false;+ }+ let push = |hash: u32, hashes: &mut SmallVec<[u32; MAX_REQUIRED_HASHES]>| {+ if hashes.len() < MAX_REQUIRED_HASHES && !hashes.contains(&hash) {+ hashes.push(hash);+ }+ };+ for simple in simple_selectors.iter() {+ let nested = match &simple {+ SimpleSelector::Id(name) if name.is_ascii_lowercase => {+ push(id_hash(name.name), hashes);+ None+ }+ SimpleSelector::Class(name) if name.is_ascii_lowercase => {+ push(class_hash(name.name), hashes);+ None+ }+ SimpleSelector::TagName(name) if name.name_is_ascii_lowercase => {+ push(tag_hash(name.name), hashes);+ None+ }+ SimpleSelector::Attribute(attribute)+ if attribute.qualified_name.name_is_ascii_lowercase+ && !matches!(+ attribute.qualified_name.namespace_type,+ NamespaceType::Named | NamespaceType::Any+ ) =>+ {+ push(attribute_hash(attribute.qualified_name.name), hashes);+ None+ }+ SimpleSelector::PseudoClass(pseudo_class)+ if matches!(pseudo_class.pseudo_class, PseudoClassType::Is | PseudoClassType::Where) =>+ {+ pseudo_class.argument_selector_list.single()+ }+ SimpleSelector::Nesting(Nesting::Rule(parent)) => parent.single(),+ _ => None,+ };+ // NB: The one selector of a `:is()` describes the element its compound does, from its own+ // subject leftwards.+ if let Some(nested) = nested {+ collect_ancestor_hashes(nested, true, hashes);+ }+ }+ true+}++/// A counting Bloom filter of the keys of the current element's ancestors.+pub(super) struct AncestorFilter {+ counters: Box<[u8; SLOT_COUNT]>,+}++impl AncestorFilter {+ /// The bytes the filter holds on the heap.+ pub(super) fn heap_size(&self) -> usize {+ size_of_val(&*self.counters)+ }++ pub(super) fn new() -> Self {+ Self {+ counters: Box::new([0; SLOT_COUNT]),+ }+ }++ fn slots(hash: u32) -> (usize, usize) {+ ((hash & KEY_MASK) as usize, ((hash >> KEY_BITS) & KEY_MASK) as usize)+ }++ /// Hold every key, rejecting nothing.+ pub(super) fn fill(&mut self) {+ self.counters.fill(u8::MAX);+ }++ pub(super) fn insert(&mut self, hash: u32) {+ let (first, second) = Self::slots(hash);+ self.counters[first] = self.counters[first].saturating_add(1);+ self.counters[second] = self.counters[second].saturating_add(1);+ }++ /// Removes a hash inserted before. A saturated counter stays saturated, which only costs the+ /// filter some rejections.+ pub(super) fn remove(&mut self, hash: u32) {+ let (first, second) = Self::slots(hash);+ for slot in [first, second] {+ if self.counters[slot] != u8::MAX {+ self.counters[slot] -= 1;+ }+ }+ }++ pub(super) fn might_contain_all(&self, hashes: &AncestorHashes) -> bool {+ hashes.hashes().all(|hash| {+ let (first, second) = Self::slots(hash);+ self.counters[first] != 0 && self.counters[second] != 0+ })+ }+}++/// A Bloom filter of the keys of the earlier siblings of the element being matched, which a+/// subsequent-sibling combinator rejects on as a descendant combinator does on the ancestor filter.+#[derive(Clone, Copy, Default)]+pub(super) struct SiblingFilter {+ bits: [u64; 4],+}++impl SiblingFilter {+ fn bits_of(hash: u32) -> [(usize, u64); 2] {+ [hash & 0xff, (hash >> 8) & 0xff].map(|bit| ((bit / 64) as usize, 1_u64 << (bit % 64)))+ }++ /// Hold every key, rejecting nothing.+ pub(super) fn fill(&mut self) {+ self.bits = [u64::MAX; 4];+ }++ pub(super) fn insert(&mut self, hash: u32) {+ for (word, bit) in Self::bits_of(hash) {+ self.bits[word] |= bit;+ }+ }++ pub(super) fn might_contain(&self, hash: u32) -> bool {+ Self::bits_of(hash)+ .iter()+ .all(|&(word, bit)| self.bits[word] & bit != 0)+ }+}++/// The filter hash of a key every element the compound left of the subject of `selector` matches carries, where the+/// subject is right of `~`: what the filter of an element's earlier siblings rejects the selector on. Only names+/// written in ASCII lowercase count, which every document carries as written.+pub(super) fn earlier_sibling_key(selector: crate::css::selector::Selector<'_>) -> Option<u32> {+ let (combinator, left) = selector.left()?;+ if combinator != crate::css::selector::Combinator::SubsequentSibling || left.is_relative_anchor() {+ return None;+ }+ let mut id = None;+ for name in left.ids_and_classes() {+ match name {+ IdOrClass::Class(class) if class.is_ascii_lowercase => return Some(class_hash(class.name)),+ IdOrClass::Id(name) if name.is_ascii_lowercase => id = id.or(Some(id_hash(name.name))),+ _ => {}+ }+ }+ id+}++#[cfg(test)]+mod tests {+ use super::*;++ fn required_hash_count(text: &str) -> usize {+ let parsed = crate::css::selector_parser::parse_selector_list(+ &text.encode_utf16().collect::<Vec<u16>>()[..],+ &[],+ crate::css::selector_parser::SelectorType::Standalone,+ crate::css::selector_parser::SelectorParsingMode::Standard,+ )+ .expect("a test writes valid selectors");+ let selectors = crate::css::selector::SelectorListRef::pack(&parsed.selectors);+ let selector = selectors.iter().next().expect("a test writes a selector");+ AncestorHashes::required_left_of(selector).hashes().count()+ }++ #[test]+ fn ancestors_are_required_to_carry_attribute_names_and_the_keys_of_a_lone_is() {+ for (selector, count) in [+ ("[data-x] .a", 1),+ ("[data-X] .a", 0),+ ("[*|data-x] .a", 0),+ (".p > [data-x=y] .a", 2),+ (":is(.p .q) .a", 2),+ (":where(.p) > .a", 1),+ (":is(.p, .q) .a", 0),+ (":not(.p) .a", 0),+ (".p :is(.q + .r) .a", 2),+ (".s + .a", 0),+ (":is(.p) .a:is(.q .r)", 1),+ ] {+ assert_eq!(required_hash_count(selector), count, "{selector}");+ }+ }+}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/extent_map.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/extent_map.rsnew file mode 100644index 00000000000..d3ca344a494--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/extent_map.rs@@ -0,0 +1,600 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! A map from keys to lists of values, all held in one flat backing, of which each key names an+//! extent: a key costs its extent, rather than a vector and the allocation behind it.+//!+//! NB: A list growing past the room of its extent moves to the end of the backing with twice the+//! room, so appends in any order cost amortized constant time, and `shrink_to_fit` packs the+//! lists again, once a map is built.++use super::super::*;+use super::shared_pages::{PagePool, SharedPages};+use std::ops::Range;+use std::sync::Arc;++/// Where one key's list stands in the backing, and how much room it has there.+#[derive(Clone, Copy, Default, PartialEq, Eq, Hash)]+pub(super) struct Extent {+ start: u32,+ len: u32,+ room: u32,+}++impl Extent {+ fn range(self) -> Range<usize> {+ self.start as usize..(self.start + self.len) as usize+ }+}++#[derive(Clone)]+pub(super) struct ExtentMap<K, V> {+ extents: HashMap<K, Extent>,+ backing: Vec<V>,+ /// The slots of the backing no list holds: the room lists left as they moved, shrank or went,+ /// and the room past their ends.+ unused: usize,+}++impl<K, V> Default for ExtentMap<K, V> {+ fn default() -> Self {+ Self {+ extents: HashMap::default(),+ backing: Vec::new(),+ unused: 0,+ }+ }+}++impl<K: Copy + Eq + std::hash::Hash, V: Copy> ExtentMap<K, V> {+ /// The list of `key`, where the map has it, which may be empty.+ pub(super) fn get(&self, key: &K) -> Option<&[V]> {+ self.extents.get(key).map(|extent| &self.backing[extent.range()])+ }++ pub(super) fn get_mut(&mut self, key: &K) -> Option<&mut [V]> {+ self.extents.get(key).map(|extent| &mut self.backing[extent.range()])+ }++ pub(super) fn contains_key(&self, key: &K) -> bool {+ self.extents.contains_key(key)+ }++ /// Whether the map has no list, not even an empty one.+ pub(super) fn is_empty(&self) -> bool {+ self.extents.is_empty()+ }++ pub(super) fn keys(&self) -> impl Iterator<Item = &K> {+ self.extents.keys()+ }++ /// Append `value` to the list of `key`, which the map starts where it has none.+ pub(super) fn push(&mut self, key: K, value: V) {+ let extent = self.extents.entry(key).or_default();+ if extent.len == extent.room {+ let room = (extent.room * 2).max(1);+ let end = (extent.start + extent.room) as usize;+ if end == self.backing.len() && extent.room != 0 {+ // The list ends the backing, which grows under it.+ self.backing.resize(end + extent.room as usize, value);+ } else {+ let start = self.backing.len();+ self.backing.extend_from_within(extent.range());+ self.backing.resize(start + room as usize, value);+ self.unused += extent.room as usize;+ extent.start = u32::try_from(start).expect("extent map space exhausted");+ }+ self.unused += (room - extent.room) as usize;+ extent.room = room;+ }+ self.backing[(extent.start + extent.len) as usize] = value;+ extent.len += 1;+ self.unused -= 1;+ }++ /// Note an empty list for `key`, where the map has none.+ pub(super) fn ensure(&mut self, key: K) {+ self.extents.entry(key).or_default();+ }++ /// Keep only the values of the list of `key` that `keep` holds to, answering how many are+ /// left, or none where the map has no list for `key`.+ pub(super) fn retain(&mut self, key: &K, mut keep: impl FnMut(&V) -> bool) -> Option<usize> {+ let extent = self.extents.get_mut(key)?;+ let range = extent.range();+ let mut kept = range.start;+ for index in range.clone() {+ if keep(&self.backing[index]) {+ self.backing[kept] = self.backing[index];+ kept += 1;+ }+ }+ let len = kept - range.start;+ self.unused += range.len() - len;+ extent.len = u32::try_from(len).expect("extent map space exhausted");+ Some(len)+ }++ /// Sort the list of `key` by what `by` says of each value, and keep one of the values it says+ /// the same of.+ pub(super) fn sort_and_dedup_by_key<T: Ord>(&mut self, key: &K, mut by: impl FnMut(&V) -> T) {+ let Some(list) = self.get_mut(key) else {+ return;+ };+ list.sort_unstable_by_key(&mut by);+ let mut kept = 0;+ for index in 0..list.len() {+ if kept == 0 || by(&list[kept - 1]) != by(&list[index]) {+ list[kept] = list[index];+ kept += 1;+ }+ }+ let removed = list.len() - kept;+ if removed != 0 {+ let extent = self.extents.get_mut(key).expect("the list was just found");+ extent.len -= u32::try_from(removed).expect("extent map space exhausted");+ self.unused += removed;+ }+ }++ pub(super) fn remove(&mut self, key: &K) {+ // NB: The room past the list's end is unused already.+ if let Some(extent) = self.extents.remove(key) {+ self.unused += extent.len as usize;+ }+ }++ /// Whether at least half the backing is room no list holds, which `shrink_to_fit` gives back.+ pub(super) fn has_slack(&self) -> bool {+ self.unused != 0 && self.unused * 2 >= self.backing.len()+ }++ /// Pack the lists next to one another, with no room past their ends, and give back what+ /// they left unused.+ pub(super) fn shrink_to_fit(&mut self) {+ self.extents.shrink_to_fit();+ if self.unused == 0 {+ self.backing.shrink_to_fit();+ return;+ }+ let mut backing = Vec::with_capacity(self.backing.len() - self.unused);+ for extent in self.extents.values_mut() {+ let start = u32::try_from(backing.len()).expect("extent map space exhausted");+ backing.extend_from_slice(&self.backing[extent.range()]);+ *extent = Extent {+ start,+ len: extent.len,+ room: extent.len,+ };+ }+ self.backing = backing;+ self.unused = 0;+ }++ /// The bytes of the extents and the backing.+ pub(super) fn heap_size(&self) -> usize {+ crate::heap_size::map_bytes(&self.extents) + crate::heap_size::vec_bytes(&self.backing)+ }+}++impl<K: Copy + Eq + std::hash::Hash, V: Copy> std::ops::Index<&K> for ExtentMap<K, V> {+ type Output = [V];++ fn index(&self, key: &K) -> &[V] {+ self.get(key).expect("the extent map has a list for the key")+ }+}++/// An extent map that no longer changes, which holds a key, where its list starts and how long it+/// is, in that order, and finds them by a table of one word per slot: the slot's tag rejects other+/// keys without reading them, so a lookup that misses touches the table alone, and a hit one record.+#[derive(Clone)]+pub(super) struct FrozenExtentMap<K, V> {+ /// A record's number plus one in the low bits, none being zero, under the high bits of its+ /// key's hash. Its length is a power of two, at most three of four slots taken.+ slots: Box<[u32]>,+ records: Box<[FrozenRecord<K>]>,+ backing: Box<[V]>,+}++#[derive(Clone, Copy)]+struct FrozenRecord<K> {+ key: K,+ start: u32,+ len: u32,+}++const FROZEN_TAG_SHIFT: u32 = 24;+const FROZEN_RECORD_MASK: u32 = (1 << FROZEN_TAG_SHIFT) - 1;++impl<K, V> Default for FrozenExtentMap<K, V> {+ fn default() -> Self {+ Self {+ slots: Box::default(),+ records: Box::default(),+ backing: Box::default(),+ }+ }+}++impl<K: Copy + Eq + std::hash::Hash, V: Copy> FrozenExtentMap<K, V> {+ fn hash_of(key: &K) -> u64 {+ use std::hash::Hasher;+ let mut hasher = super::super::fast_hash::fast_hasher();+ key.hash(&mut hasher);+ hasher.finish()+ }++ /// The lists of `map`, packed.+ pub(super) fn of(mut map: ExtentMap<K, V>) -> Self {+ map.shrink_to_fit();+ let count = map.extents.len();+ assert!(count < FROZEN_RECORD_MASK as usize, "extent map space exhausted");+ let records: Box<[FrozenRecord<K>]> = map+ .extents+ .iter()+ .map(|(&key, extent)| FrozenRecord {+ key,+ start: extent.start,+ len: extent.len,+ })+ .collect();+ let length = match count {+ 0 => 0,+ _ => (count * 4 / 3 + 1).next_power_of_two(),+ };+ let mut slots = vec![0_u32; length].into_boxed_slice();+ for (number, record) in records.iter().enumerate() {+ let hash = Self::hash_of(&record.key);+ let mut slot = hash as usize & (length - 1);+ while slots[slot] != 0 {+ slot = (slot + 1) & (length - 1);+ }+ let tag = (hash >> (64 - (32 - FROZEN_TAG_SHIFT))) as u32;+ slots[slot] = tag << FROZEN_TAG_SHIFT | (number as u32 + 1);+ }+ Self {+ slots,+ records,+ backing: map.backing.into_boxed_slice(),+ }+ }++ /// The list of `key`, where the map has it, which may be empty.+ #[inline]+ pub(super) fn get(&self, key: &K) -> Option<&[V]> {+ if self.slots.is_empty() {+ return None;+ }+ let hash = Self::hash_of(key);+ let mask = self.slots.len() - 1;+ let tag = (hash >> (64 - (32 - FROZEN_TAG_SHIFT))) as u32;+ let mut slot = hash as usize & mask;+ loop {+ let held = self.slots[slot];+ if held == 0 {+ return None;+ }+ if held >> FROZEN_TAG_SHIFT == tag {+ let record = &self.records[(held & FROZEN_RECORD_MASK) as usize - 1];+ if record.key == *key {+ let start = record.start as usize;+ return Some(&self.backing[start..start + record.len as usize]);+ }+ }+ slot = (slot + 1) & mask;+ }+ }++ pub(super) fn contains_key(&self, key: &K) -> bool {+ self.get(key).is_some()+ }++ /// Whether the map has no list, not even an empty one.+ pub(super) fn is_empty(&self) -> bool {+ self.records.is_empty()+ }++ pub(super) fn keys(&self) -> impl Iterator<Item = &K> {+ self.records.iter().map(|record| &record.key)+ }++ /// The bytes of the table, the records and the lists.+ pub(super) fn heap_size(&self) -> usize {+ size_of_val::<[u32]>(&self.slots)+ + size_of_val::<[FrozenRecord<K>]>(&self.records)+ + size_of_val::<[V]>(&self.backing)+ }+}++/// An extent map that starts with the lists of a frozen one it shares with others, and goes on with+/// lists of its own: the list of a key is the shared one's, followed by its own.+#[derive(Clone)]+pub(super) struct SharedExtentMap<K, V> {+ shared: Arc<FrozenExtentMap<K, V>>,+ own: ExtentMap<K, V>,+}++impl<K, V> Default for SharedExtentMap<K, V> {+ fn default() -> Self {+ Self {+ shared: Arc::new(FrozenExtentMap::default()),+ own: ExtentMap::default(),+ }+ }+}++impl<K: Copy + Eq + std::hash::Hash, V: Copy> SharedExtentMap<K, V> {+ /// The list of `key`, the shared values first, where either map has one, which may be empty.+ pub(super) fn get(&self, key: &K) -> Option<impl Iterator<Item = &V> + Clone + use<'_, K, V>> {+ let (shared, own) = (self.shared.get(key), self.own.get(key));+ (shared.is_some() || own.is_some()).then(|| shared.into_iter().flatten().chain(own.into_iter().flatten()))+ }++ /// The list of `key`, which is empty where neither map has one.+ pub(super) fn values(&self, key: &K) -> impl Iterator<Item = &V> + Clone + use<'_, K, V> {+ self.get(key).into_iter().flatten()+ }++ pub(super) fn contains_key(&self, key: &K) -> bool {+ self.own.contains_key(key) || self.shared.contains_key(key)+ }++ pub(super) fn push(&mut self, key: K, value: V) {+ self.own.push(key, value);+ }++ /// Keep only the values of the map's own list of `key` that `keep` holds to, answering how many+ /// are left, or none where it has no list of its own for `key`. The shared lists never change.+ pub(super) fn retain_own(&mut self, key: &K, keep: impl FnMut(&V) -> bool) -> Option<usize> {+ self.own.retain(key, keep)+ }++ pub(super) fn sort_and_dedup_own_by_key<T: Ord>(&mut self, key: &K, by: impl FnMut(&V) -> T) {+ self.own.sort_and_dedup_by_key(key, by);+ }++ pub(super) fn remove_own(&mut self, key: &K) {+ self.own.remove(key);+ }++ /// The keys the map's own lists are of.+ pub(super) fn own_keys(&self) -> impl Iterator<Item = &K> {+ self.own.keys()+ }++ pub(super) fn has_slack(&self) -> bool {+ self.own.has_slack()+ }++ pub(super) fn shrink_to_fit(&mut self) {+ self.own.shrink_to_fit();+ }++ /// Make every list shared, packed: clones of the map then share all of them.+ pub(super) fn freeze(&mut self) {+ if self.own.keys().next().is_none() {+ return;+ }+ let mut all = ExtentMap::default();+ let keys: Vec<K> = self.shared.keys().chain(self.own.keys()).copied().collect();+ for key in keys {+ if all.contains_key(&key) {+ continue;+ }+ for &value in self.values(&key).collect::<Vec<_>>() {+ all.push(key, value);+ }+ if !all.contains_key(&key) {+ all.ensure(key);+ }+ }+ self.shared = Arc::new(FrozenExtentMap::of(all));+ self.own = ExtentMap::default();+ }++ /// The bytes of the map's own lists.+ pub(super) fn heap_size(&self) -> usize {+ self.own.heap_size()+ }++ /// The bytes of the lists the map shares.+ pub(super) fn shared_heap_size(&self) -> usize {+ self.shared.heap_size()+ }+}++/// An extent map keyed by dense numbers, its extents and its backing held in pages that the+/// documents of a process holding equal pages share: frames of a site whose rules are numbered+/// alike hold one copy of the lists of their rules.+#[derive(Clone)]+pub(super) struct PagedExtentMap<V> {+ extents: SharedPages<Extent>,+ backing: SharedPages<V>,+ unused: usize,+}++impl<V> Default for PagedExtentMap<V> {+ fn default() -> Self {+ Self {+ extents: SharedPages::default(),+ backing: SharedPages::default(),+ unused: 0,+ }+ }+}++impl<V: Copy + Default + PartialEq + std::hash::Hash> PagedExtentMap<V> {+ fn extent(&self, key: usize) -> Extent {+ self.extents.get(key).copied().unwrap_or_default()+ }++ /// The list of `key`, which is empty where it has none.+ pub(super) fn get(&self, key: usize) -> impl Iterator<Item = V> + '_ {+ self.extent(key).range().map(|index| self.backing[index])+ }++ pub(super) fn push(&mut self, key: usize, value: V) {+ while self.extents.len() <= key {+ self.extents.push(Extent::default());+ }+ let mut extent = self.extents[key];+ if extent.len == extent.room {+ let room = (extent.room * 2).max(1);+ let end = (extent.start + extent.room) as usize;+ if end == self.backing.len() && extent.room != 0 {+ // The list ends the backing, which grows under it.+ for _ in extent.room..room {+ self.backing.push(V::default());+ }+ } else {+ let start = self.backing.len();+ for index in extent.range() {+ let value = self.backing[index];+ self.backing.push(value);+ }+ for _ in extent.len..room {+ self.backing.push(V::default());+ }+ self.unused += extent.room as usize;+ extent.start = u32::try_from(start).expect("extent map space exhausted");+ }+ self.unused += (room - extent.room) as usize;+ extent.room = room;+ }+ *self.backing.get_mut((extent.start + extent.len) as usize) = value;+ extent.len += 1;+ self.unused -= 1;+ *self.extents.get_mut(key) = extent;+ }++ /// Keep only the values of the list of `key` that `keep` holds to, answering how many are left.+ pub(super) fn retain(&mut self, key: usize, mut keep: impl FnMut(&V) -> bool) -> usize {+ let mut extent = self.extent(key);+ let range = extent.range();+ let mut kept = range.start;+ for index in range.clone() {+ let value = self.backing[index];+ if keep(&value) {+ if kept != index {+ *self.backing.get_mut(kept) = value;+ }+ kept += 1;+ }+ }+ let len = kept - range.start;+ if len != range.len() {+ self.unused += range.len() - len;+ extent.len = u32::try_from(len).expect("extent map space exhausted");+ *self.extents.get_mut(key) = extent;+ }+ len+ }++ pub(super) fn remove(&mut self, key: usize) {+ let extent = self.extent(key);+ if extent.room != 0 {+ // NB: The room past the list's end is unused already.+ self.unused += extent.len as usize;+ *self.extents.get_mut(key) = Extent::default();+ }+ }++ pub(super) fn has_slack(&self) -> bool {+ self.unused != 0 && self.unused * 2 >= self.backing.len()+ }++ pub(super) fn shrink_to_fit(&mut self) {+ if self.unused != 0 {+ let mut backing = SharedPages::default();+ for key in 0..self.extents.len() {+ let extent = self.extents[key];+ let start = u32::try_from(backing.len()).expect("extent map space exhausted");+ for index in extent.range() {+ backing.push(self.backing[index]);+ }+ if extent+ != (Extent {+ start,+ len: extent.len,+ room: extent.len,+ })+ {+ *self.extents.get_mut(key) = Extent {+ start,+ len: extent.len,+ room: extent.len,+ };+ }+ }+ self.backing = backing;+ self.unused = 0;+ }+ self.extents.shrink_to_fit();+ self.backing.shrink_to_fit();+ }++ /// Publish the pages of the map to the pools, taking equal pages others published instead.+ pub(super) fn share(&mut self, extents: &PagePool<Extent>, backing: &PagePool<V>) {+ self.extents.share(extents);+ self.backing.share(backing);+ }++ pub(super) fn heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {+ self.extents.heap_size(sizer, |_, _| 0) + self.backing.heap_size(sizer, |_, _| 0)+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_frozen_map_holds_the_lists_it_was_made_of() {+ let mut map = ExtentMap::<u32, u32>::default();+ for value in 0..1000 {+ map.push(value % 97, value);+ }+ map.ensure(500);+ let frozen = FrozenExtentMap::of(map);+ for key in 0..97 {+ let expected: Vec<u32> = (0..1000).filter(|value| value % 97 == key).collect();+ assert_eq!(frozen.get(&key).unwrap(), &expected[..]);+ }+ assert_eq!(frozen.get(&500).unwrap(), &[] as &[u32]);+ assert!(frozen.get(&501).is_none());+ assert_eq!(frozen.keys().count(), 98);+ assert!(FrozenExtentMap::<u32, u32>::default().get(&0).is_none());+ }++ #[test]+ fn lists_appended_in_any_order_keep_their_values_and_pack_again() {+ let mut map = ExtentMap::<u32, u32>::default();+ for value in 0..100 {+ map.push(value % 7, value);+ }+ for key in 0..7 {+ let expected: Vec<u32> = (0..100).filter(|value| value % 7 == key).collect();+ assert_eq!(map.get(&key).unwrap(), &expected[..]);+ }+ assert!(map.has_slack());+ map.retain(&3, |value| value % 2 == 0);+ map.remove(&5);+ let held: usize = map.extents.values().map(|extent| extent.len as usize).sum();+ assert_eq!(held, map.backing.len() - map.unused);+ map.shrink_to_fit();+ assert!(!map.has_slack());+ assert_eq!(map.unused, 0);+ assert_eq!(map.backing.len(), 100 - 14 - 7);+ assert_eq!(map.get(&3).unwrap(), &[10, 24, 38, 52, 66, 80, 94]);+ assert!(map.get(&5).is_none());+ map.push(5, 1);+ map.push(5, 1);+ map.sort_and_dedup_by_key(&5, |value| *value);+ assert_eq!(map.get(&5).unwrap(), &[1]);+ }+}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/matched_rules.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/matched_rules.rsnew file mode 100644index 00000000000..219def24dbd--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/matched_rules.rs@@ -0,0 +1,184 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The rules the engine matches to an element, in the order its cascade applies them, which tests+//! read to see what an element's matching decided without reading its computed style.++use super::super::engine_calls::with_engine;+use super::super::*;+use super::bloom::AncestorFilter;+use super::matching::{ElementMatch, Matcher};+use super::rules::RuleIndex;+use crate::css::selector::Specificity;+use crate::render_state::{BegunRead, DocumentHost};++/// One rule matching an element, for the element at `node` among the elements asked about.+#[repr(C)]+#[derive(Clone, Copy)]+pub struct FfiMatchedRule {+ /// The position of the element among those asked about.+ pub node: u32,+ /// The rule identity as the boundary numbers it, one more than the engine's, or zero where+ /// the element could not be matched.+ pub rule: u32,+ /// The pseudo-element the rule targets, or `u32::MAX` for the element itself.+ pub pseudo_element: u32,+}++/// The rules that match one element, one per rule and target with the greatest specificity among+/// its matching selectors, in the order the cascade applies them. User agent rules are left out+/// unless `include_user_agent` says otherwise.+fn matched_rules(+ state: &RetainedState,+ index: &RuleIndex,+ matcher: &mut Matcher<'_>,+ node: StyleNodeID,+ include_user_agent: bool,+) -> Result<Vec<(RuleID, u8)>, Incomplete> {+ let projection = &state.projection;+ let Some(facts) = projection.facts(node) else {+ return Ok(Vec::new());+ };+ let mut filter = AncestorFilter::new();+ for ancestor_row in projection+ .ancestors(node)+ .filter_map(|ancestor| projection.row_of(ancestor))+ {+ for key in super::ancestor_keys_of(ancestor_row) {+ filter.insert(key);+ }+ }+ let mut matches: Vec<ElementMatch> = Vec::new();+ matcher.match_element(node, facts, &filter, &mut matches)?;++ // NB: Container conditions are not applied: the rules behind them are reported as matching,+ // whatever the container they ask about says.+ let mut merged: Vec<(RuleID, u8, TreeScopeID, Specificity, u32, u32)> = Vec::new();+ for matched in &matches {+ if !include_user_agent && index.entries.placement(matched.entry as usize).origin == CascadeOrigin::UserAgent {+ continue;+ }+ let same_block = |existing: &&mut (RuleID, u8, TreeScopeID, Specificity, u32, u32)| {+ existing.0 == matched.rule && existing.1 == matched.pseudo_kind && existing.2 == matched.scope+ };+ match merged.iter_mut().find(same_block) {+ Some(existing) => {+ existing.3 = existing.3.max(matched.specificity);+ existing.4 = existing.4.min(matched.scope_proximity);+ }+ None => merged.push((+ matched.rule,+ matched.pseudo_kind,+ matched.scope,+ matched.specificity,+ matched.scope_proximity,+ matched.entry,+ )),+ }+ }+ let context_depth_of = |entry: u32| {+ matches+ .iter()+ .find(|matched| matched.entry == entry)+ .map_or(0, |matched| matched.context_depth)+ };+ let mut ordered: Vec<(CascadePriority, RuleID, u8)> = merged+ .into_iter()+ .map(|(rule, pseudo_kind, _, specificity, scope_proximity, first_entry)| {+ let entry = index.entries.view(first_entry as usize);+ let placement = index.entries.placement_of(entry);+ let priority = CascadePriority::new(PriorityInputs {+ origin: placement.origin,+ important: false,+ context_depth: context_depth_of(first_entry),+ element_attachment: ElementAttachment::Rule,+ layer_rank: placement.layer_rank,+ specificity,+ scope_proximity,+ sheet_rank: placement.sheet_rank,+ rule_rank: entry.rule_rank(),+ });+ (priority, rule, pseudo_kind)+ })+ .collect();+ ordered.sort_by_key(|(priority, _, _)| *priority);+ Ok(ordered+ .into_iter()+ .map(|(_, rule, pseudo_kind)| (rule, pseudo_kind))+ .collect())+}++impl StyleEngine {+ /// The rules matching each of `nodes`, with the index of the engine where it is live, or one+ /// built from the document's rules as a cold pass builds it where it is not.+ fn matched_rules(&self, nodes: &[u32], include_user_agent: bool) -> Vec<FfiMatchedRule> {+ let state = &self.retained;+ let cold;+ let index: &RuleIndex = match state.live_style.as_deref() {+ Some(live) => live.index(),+ None => {+ cold = RuleIndex::build(&state.rules, state.process_rule_indexes());+ &cold+ }+ };+ let mut matcher = Matcher::new(index, state);+ let mut out = Vec::new();+ for (position, &raw) in nodes.iter().enumerate() {+ let position = u32::try_from(position).expect("element count fits the boundary");+ let answer = StyleNodeID::from_raw(raw)+ .map(|node| matched_rules(state, index, &mut matcher, node, include_user_agent));+ let Some(Ok(rules)) = answer else {+ out.push(FfiMatchedRule {+ node: position,+ rule: 0,+ pseudo_element: u32::MAX,+ });+ continue;+ };+ out.extend(rules.into_iter().map(|(rule, pseudo_kind)| FfiMatchedRule {+ node: position,+ rule: rule.0 + 1,+ pseudo_element: match pseudo_kind {+ u8::MAX => u32::MAX,+ kind => u32::from(kind),+ },+ }));+ }+ out+ }+}++/// Writes the rules the engine matches to each of the `node_count` elements at `nodes` into `out`,+/// element by element in the order asked and each element's in cascade order, with a rule of zero+/// for an element that could not be matched. User agent rules are written where+/// `include_user_agent` is set.+///+/// Returns the number written, or a count larger than `capacity` when nothing was written because+/// the buffer was too small.+///+/// # Safety+/// `host` must be a live document host, on its document's thread, `nodes` must point at+/// `node_count` readable identities, and `out` at `capacity` writable `FfiMatchedRule` values.+#[unsafe(no_mangle)]+pub unsafe extern "C" fn style_engine_matched_rules(+ host: &DocumentHost,+ read: &BegunRead,+ nodes: *const u32,+ node_count: usize,+ out: *mut FfiMatchedRule,+ capacity: usize,+ include_user_agent: bool,+) -> usize {+ // SAFETY: Guaranteed by the caller.+ let nodes = unsafe { super::super::bridge::borrow(nodes, node_count) };+ let rules = with_engine(read, host, |engine| engine.matched_rules(nodes, include_user_agent));+ if rules.len() > capacity {+ return rules.len();+ }+ // SAFETY: Guaranteed by the caller.+ unsafe { std::ptr::copy_nonoverlapping(rules.as_ptr(), out, rules.len()) };+ rules.len()+}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/matching.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/matching.rsnew file mode 100644index 00000000000..1d52a4d3a90--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/matching.rs@@ -0,0 +1,627 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Matching one element against the rule index: gather the bucket candidates its keys reach,+//! reject those whose required ancestor keys the filter lacks, and evaluate the rest.++use super::super::component_matching::EntrySelector;+use super::super::selector_evaluation::StructuralRead;+use super::super::transaction_view::TransactionFactSide;+use super::super::*;+use super::bloom::{AncestorFilter, SiblingFilter};+use super::projection::{ElementFacts, Projection, ProjectionEvaluator};+use super::rules::{BucketSlots, BucketSource, Buckets, RuleIndex, ScopeGroupID, ScopeIndex};+use crate::css::selector::Specificity;+use smallvec::SmallVec;++/// One rule entry matching the element.+#[derive(Clone, Copy)]+pub(super) struct ElementMatch {+ /// The entry in the rule index.+ pub(super) entry: u32,+ pub(super) rule: RuleID,+ pub(super) specificity: Specificity,+ pub(super) scope_proximity: u32,+ /// The kind of pseudo-element the entry styles, or `ELEMENT_PSEUDO_KIND` for the element itself.+ pub(super) pseudo_kind: u8,+ /// Where the encapsulation context the entry's rule decides from stands among the element's,+ /// which its cascade weighs the match by.+ pub(super) context_depth: u32,+ /// The tree scope whose sheets the entry's rule decides from: the document for the document's+ /// sheets, and otherwise the shadow tree the entry reached the element from.+ pub(super) scope: TreeScopeID,+}++impl ElementMatch {+ /// Whether the entry styles a pseudo-element.+ #[cfg(test)]+ pub(super) fn pseudo_element(&self) -> bool {+ self.pseudo_kind != super::rules::ELEMENT_PSEUDO_KIND+ }+}++/// Which of a scope's bucket families an element is matched against.+#[derive(Clone, Copy, PartialEq, Eq)]+enum Family {+ Own,+ OwnRevalidation,+ Host,+ Slotted,+ Part,+}++impl ScopeIndex {+ fn family(&self, family: Family) -> &Buckets {+ match family {+ Family::Own => &self.own,+ Family::OwnRevalidation => &self.own_revalidation,+ Family::Host => &self.host,+ Family::Slotted => &self.slotted,+ Family::Part => &self.part,+ }+ }+}++/// How an element is reached by the entries of one bucket family of a scope.+#[derive(Clone, Copy)]+struct Reach<'a> {+ scope: TreeScopeID,+ family: Family,+ /// Where the matches of the entries of the scope's own sheets stand among the element's+ /// encapsulation contexts; the document's stand outermost.+ scope_depth: u32,+ /// The filter of the element's ancestors, for the entries of its own tree, whose ancestors it+ /// holds.+ filter: Option<&'a AncestorFilter>,+ /// The tree scope the element is exposed to as a part, for the rules of a `::part()` reaching it.+ part_exposure: Option<TreeScopeID>,+}++/// What a bucket's candidates are rejected or proven on of the element they are offered to.+#[derive(Clone, Copy)]+struct ElementKeys {+ /// The dispatch bloom bits of the keys the element carries.+ bloom: u64,+ /// Whether the element's tag is its own ASCII-lowercase form.+ tag_is_lowercase: bool,+}++/// The dispatch bloom bits of the element being matched, or every bit where its ids and classes+/// compare to the selectors' folded, which the bits the selectors carry are not.+fn element_bloom_of(facts: &ElementFacts, is_document_root: bool, folds_ids_and_classes: bool) -> u64 {+ match folds_ids_and_classes {+ true => u64::MAX,+ false => facts.dispatch_bloom(is_document_root),+ }+}++#[derive(Default)]+pub(super) struct MatchCounters {+ pub(super) candidates: u64,+ pub(super) bloom_rejections: u64,+ pub(super) evaluations: u64,+ pub(super) matches: u64,+ /// The walks of the argument of a `:has()` that answered it for an anchor.+ pub(super) relative_walks: u64,+}++impl MatchCounters {+ pub(super) fn add(&mut self, other: &Self) {+ self.candidates += other.candidates;+ self.bloom_rejections += other.bloom_rejections;+ self.evaluations += other.evaluations;+ self.matches += other.matches;+ self.relative_walks += other.relative_walks;+ }+}++pub(super) struct Matcher<'a> {+ index: &'a RuleIndex,+ /// The buckets elements reach entries of `index` by: its own, or those of a part of it.+ buckets: &'a RuleIndex,+ state: &'a RetainedState,+ evaluator: ProjectionEvaluator<'a>,+ projection: &'a Projection,+ /// The node stamp each entry was last offered under, so an entry in several buckets an element+ /// reaches is evaluated once.+ offered: Vec<u32>,+ stamp: u32,+ /// The filter of the element asked for last, which its candidates ask for one after another.+ last_earlier_siblings: Option<(StyleNodeID, SiblingFilter)>,++ pub(super) statistics: MatchCounters,+}++impl<'a> Matcher<'a> {+ pub(super) fn new(index: &'a RuleIndex, state: &'a RetainedState) -> Self {+ Self::reaching(index, index, state)+ }++ /// A matcher of the entries of `index` that the buckets of `buckets` hold alone.+ pub(super) fn reaching(index: &'a RuleIndex, buckets: &'a RuleIndex, state: &'a RetainedState) -> Self {+ let projection = &state.projection;+ Self {+ index,+ buckets,+ state,+ // NB: A matcher lives for one pass, over which the projection holds still, so its+ // evaluator keeps the sibling positions and positional answers it finds for the+ // elements after: a long sibling list costs one walk, not one per element.+ evaluator: projection.evaluator().with_owned_match_workspace(),+ projection,+ offered: vec![0; index.entries.len()],+ stamp: 0,+ last_earlier_siblings: None,++ statistics: MatchCounters::default(),+ }+ }++ /// What the matcher measured, with the walks its evaluator took.+ pub(super) fn counters(&self) -> MatchCounters {+ MatchCounters {+ relative_walks: self.evaluator.relative_walks(),+ ..self.statistics+ }+ }++ /// Append the element's matches to `out`, in index order.+ pub(super) fn match_element(+ &mut self,+ node: StyleNodeID,+ facts: &ElementFacts,+ filter: &AncestorFilter,+ out: &mut Vec<ElementMatch>,+ ) -> Result<(), Incomplete> {+ self.match_in(Family::Own, node, facts, filter, out)+ }++ /// Append the element's matches among the entries that revalidate to `out`, in index order.+ pub(super) fn match_revalidation_entries(+ &mut self,+ node: StyleNodeID,+ facts: &ElementFacts,+ filter: &AncestorFilter,+ out: &mut Vec<ElementMatch>,+ ) -> Result<(), Incomplete> {+ self.match_in(Family::OwnRevalidation, node, facts, filter, out)+ }++ /// The filter of the keys of the earlier siblings of `node`. The traversal styles siblings one+ /// after another, so this mostly adds the keys of the sibling before to the filter of the element+ /// asked for last; an element that does not follow it has its earlier siblings gathered again, up+ /// to a bound past which the filter holds every key.+ fn earlier_siblings(&mut self, node: StyleNodeID) -> SiblingFilter {+ if let Some((last, filter)) = self.last_earlier_siblings+ && last == node+ {+ return filter;+ }+ let previous = self.projection.previous_element_sibling(node);+ let projection = self.projection;+ let add_keys = |filter: &mut SiblingFilter, sibling| {+ if let Some(row) = projection.row_of(sibling) {+ for key in super::ancestor_keys_of(row) {+ filter.insert(key);+ }+ }+ };+ let filter = match self.last_earlier_siblings {+ Some((last, filter)) if previous == Some(last) => {+ let mut filter = filter;+ add_keys(&mut filter, last);+ filter+ }+ _ => {+ const MAX_GATHERED_SIBLINGS: usize = 32;+ let mut filter = SiblingFilter::default();+ let mut sibling = previous;+ for _ in 0..MAX_GATHERED_SIBLINGS {+ let Some(current) = sibling else {+ break;+ };+ add_keys(&mut filter, current);+ sibling = self.projection.previous_element_sibling(current);+ }+ if sibling.is_some() {+ filter.fill();+ }+ filter+ }+ };+ self.last_earlier_siblings = Some((node, filter));+ filter+ }++ /// Whether `node`, with `facts`, matches the entry, outside the buckets and the ancestor filter.+ /// An entry whose rule does not decide in the element's own tree matches nothing.+ pub(super) fn matches_entry(&mut self, node: StyleNodeID, entry: u32) -> Result<bool, Incomplete> {+ // NB: The invalidation map of a segment goes on naming the entries that died for this index.+ if !self.index.entries.view(entry as usize).live() {+ return Ok(false);+ }+ let scope = self.projection.tree_scope(node);+ let placement = self.index.entries.placement(entry as usize);+ let applies = self.index.group_of(scope) == Some(placement.group)+ || (placement.group == ScopeGroupID::DOCUMENT+ && (self.state.rules.scope_uses_document_sheets(scope)+ || matches!(placement.origin, CascadeOrigin::UserAgent | CascadeOrigin::User)));+ if !applies {+ return Ok(false);+ }+ // An element is rejected on the keys of its earlier siblings as a candidate of the buckets is.+ let selector = self.index.entry_selector(entry);+ if !self.index.entries.view(entry as usize).scoped()+ && let Some(key) = super::bloom::earlier_sibling_key(selector.selector)+ && !self.earlier_siblings(node).might_contain(key)+ {+ self.projection+ .note_structural_read(TransactionFactSide::After, node, StructuralRead::EarlierSiblings);+ return Ok(false);+ }+ self.enter_scope(scope, None);+ self.statistics.evaluations += 1;+ self.evaluator+ .matches_entry_selector(selector, node, self.state.document_matching())+ }++ /// The match of an unscoped entry of the own tree of `node`.+ pub(super) fn element_match(&self, node: StyleNodeID, entry: u32) -> ElementMatch {+ let indexed = self.index.entries.view(entry as usize);+ let scope = match self.index.entries.placement_of(indexed).group {+ ScopeGroupID::DOCUMENT => TreeScopeID::DOCUMENT,+ _ => self.projection.tree_scope(node),+ };+ ElementMatch {+ entry,+ rule: self.index.rule_of_view(indexed),+ specificity: indexed.specificity(),+ scope_proximity: u32::MAX,+ pseudo_kind: indexed.pseudo_kind(),+ context_depth: self.depth_of(scope),+ scope,+ }+ }++ /// How deeply `scope` is nested, which the matches of the rules of the trees an element is in+ /// stand at.+ fn depth_of(&self, scope: TreeScopeID) -> u32 {+ match scope {+ TreeScopeID::DOCUMENT => 0,+ _ => self.state.tree_scope_depth(scope),+ }+ }++ /// Evaluate the rules of `scope` from here on, for a part exposed to `part_exposure` if any.+ fn enter_scope(&mut self, scope: TreeScopeID, part_exposure: Option<TreeScopeID>) {+ let shadow_root = match scope {+ TreeScopeID::DOCUMENT => None,+ _ => self.state.scope_root(scope),+ };+ self.evaluator.set_scope_shadow_root(shadow_root);+ self.evaluator.set_part_exposure_scope(part_exposure);+ }++ /// Whether the rules of trees other than the element's own can match it: it hosts a shadow+ /// tree, is slotted, or is a part exposed outside its tree.+ pub(super) fn is_reached_from_other_trees(&self, node: StyleNodeID) -> bool {+ self.projection.is_reached_from_other_trees(node)+ }++ /// Append the element's matches among the entries of the trees other than its own that reach+ /// it to `out`: `:host` rules of its shadow tree, `::slotted()` rules of the trees it is slotted+ /// into, and `::part()` rules of the trees it is exposed to, or only the `::slotted()` rules+ /// for `revalidation`.+ ///+ /// https://drafts.csswg.org/css-scoping-1/#shadow-cascading+ fn match_other_trees(+ &mut self,+ node: StyleNodeID,+ facts: &ElementFacts,+ revalidation: bool,+ out: &mut Vec<ElementMatch>,+ ) -> Result<(), Incomplete> {+ if !self.is_reached_from_other_trees(node) {+ return Ok(());+ }+ let state = self.state;+ let scope = self.projection.tree_scope(node);+ let inner_scope = self+ .projection+ .shadow_root_of(node)+ .and_then(|shadow_root| state.scope_by_root.get(shadow_root))+ .filter(|&inner| inner != scope);+ if let Some(inner_scope) = inner_scope+ && !revalidation+ {+ let reach = Reach {+ scope: inner_scope,+ family: Family::Host,+ scope_depth: state.encapsulation_context(node, inner_scope),+ filter: None,+ part_exposure: None,+ };+ self.match_family(reach, node, facts, out)?;+ }+ let slotted_scopes: SmallVec<[TreeScopeID; 2]> = state+ .scopes_slotted_into(node)+ .filter(|&slotted| slotted != scope && Some(slotted) != inner_scope)+ .collect();+ for &slotted_scope in &slotted_scopes {+ let reach = Reach {+ scope: slotted_scope,+ family: Family::Slotted,+ scope_depth: self.depth_of(slotted_scope),+ filter: None,+ part_exposure: None,+ };+ self.match_family(reach, node, facts, out)?;+ }+ if revalidation {+ return Ok(());+ }+ let part_scopes: SmallVec<[TreeScopeID; 2]> = state+ .part_exposure_scopes(node)+ .filter(|&exposed| exposed != scope && Some(exposed) != inner_scope && !slotted_scopes.contains(&exposed))+ .collect();+ for part_scope in part_scopes {+ let reach = Reach {+ scope: part_scope,+ family: Family::Part,+ scope_depth: self.depth_of(part_scope),+ filter: None,+ part_exposure: Some(part_scope),+ };+ self.match_family(reach, node, facts, out)?;+ }+ Ok(())+ }++ fn match_in(+ &mut self,+ family: Family,+ node: StyleNodeID,+ facts: &ElementFacts,+ filter: &AncestorFilter,+ out: &mut Vec<ElementMatch>,+ ) -> Result<(), Incomplete> {+ let start = out.len();+ let scope = self.projection.tree_scope(node);+ let reach = Reach {+ scope,+ family,+ scope_depth: self.depth_of(scope),+ filter: Some(filter),+ part_exposure: None,+ };+ let result = self+ .match_family(reach, node, facts, out)+ .and_then(|()| self.match_other_trees(node, facts, family == Family::OwnRevalidation, out));+ if result.is_err() {+ out.truncate(start);+ }+ result?;+ out[start..].sort_unstable_by_key(|matched| (matched.entry, matched.scope));+ // An entry of the document's sheets can reach an element from more than one tree. One of a+ // group of shadow trees decides from each tree of the group that reaches the element.+ let mut kept = start;+ for index in start..out.len() {+ if kept == start || (out[kept - 1].entry, out[kept - 1].scope) != (out[index].entry, out[index].scope) {+ out[kept] = out[index];+ kept += 1;+ }+ }+ out.truncate(kept);+ Ok(())+ }++ /// Append the element's matches among the entries of one bucket family of `scope` to `out`:+ /// those of the scope's own sheets, and of the document's sheets that decide in it.+ fn match_family(+ &mut self,+ reach: Reach<'_>,+ node: StyleNodeID,+ facts: &ElementFacts,+ out: &mut Vec<ElementMatch>,+ ) -> Result<(), Incomplete> {+ let (scope, family) = (reach.scope, reach.family);+ let index = self.buckets;+ // https://drafts.csswg.org/css-scoping-1/#shadow-cascading+ // NB: A shadow tree decides with the document's user agent and user sheets, and with its+ // author sheets as well where it is built from the document's styles.+ let mut sources: SmallVec<[BucketSource<'_>; 8]> = SmallVec::new();+ match scope {+ TreeScopeID::DOCUMENT => sources.extend(index.bucket_sources(ScopeGroupID::DOCUMENT, false)),+ _ => {+ if let Some(group) = index.group_of(scope) {+ sources.extend(index.bucket_sources(group, false));+ }+ // NB: A tree built from the document's styles stands in for what they were written for, whose host they do+ // not name.+ let non_author = family == Family::Host || !self.state.rules.scope_uses_document_sheets(scope);+ sources.extend(index.bucket_sources(ScopeGroupID::DOCUMENT, non_author));+ }+ }+ sources.extend(index.user_agent_buckets());+ if sources.is_empty() {+ return Ok(());+ }+ // NB: An entry is offered once for each tree that reaches the element: the shadow trees of+ // one group share their entries.+ self.stamp = self.stamp.wrapping_add(1);+ if self.stamp == 0 {+ self.offered.fill(0);+ self.stamp = 1;+ }+ self.enter_scope(scope, reach.part_exposure);+ let projection = self.projection;+ let is_document_root = projection.parent(node).is_none();+ let keys = ElementKeys {+ bloom: element_bloom_of(+ facts,+ is_document_root,+ self.state.document_matching().fold_ids_and_classes,+ ),+ // NB: A tag that is its own ASCII-lowercase form has no folding of its own.+ tag_is_lowercase: facts.folded_tag().is_none(),+ };+ for source in sources {+ let buckets = source.buckets.family(family);+ if buckets.is_empty() {+ continue;+ }+ let mut result = Ok(());+ projection.for_each_dispatch_probe(facts, is_document_root, |key, _| {+ if result.is_err() {+ return;+ }+ if let Some(bucket) = buckets.get(&key) {+ result = self.offer_all(bucket, source, node, reach, keys, out);+ }+ });+ result?;+ }+ Ok(())+ }++ /// Offer the entries of `bucket` to the element, as `reach` reaches it.+ fn offer_all(+ &mut self,+ bucket: BucketSlots<'_>,+ source: BucketSource<'_>,+ node: StyleNodeID,+ reach: Reach<'_>,+ keys: ElementKeys,+ out: &mut Vec<ElementMatch>,+ ) -> Result<(), Incomplete> {+ let Reach {+ scope,+ family: _,+ scope_depth,+ filter,+ part_exposure: _,+ } = reach;+ let dead_in = source.binding_with_dead_entries();+ for bucket_entry in bucket {+ self.statistics.candidates += 1;+ // The subject compound's ids and classes, which the element's bits tell it lacks, first, as+ // they reject most candidates a bucket of one of its keys holds.+ if bucket_entry.subject_bloom() & !keys.bloom != 0 {+ self.statistics.bloom_rejections += 1;+ continue;+ }+ if filter.is_some_and(|filter| !filter.might_contain_all(&bucket_entry.ancestor_hashes())) {+ self.statistics.bloom_rejections += 1;+ continue;+ }+ let entry = source.first + bucket_entry.entry();+ if dead_in.is_some_and(|bound| bound.is_dead(entry)) {+ continue;+ }+ if bucket_entry.in_other_buckets() {+ let offered = &mut self.offered[entry as usize];+ if *offered == self.stamp {+ continue;+ }+ *offered = self.stamp;+ }+ // An element of the entry's own tree is rejected on the keys of its earlier siblings as on those of its+ // ancestors.+ if filter.is_some()+ && let Some(key) = bucket_entry.sibling_key()+ && !self.earlier_siblings(node).might_contain(key)+ {+ // NB: What the element's earlier siblings carry rejected it, which an element arriving among them+ // can move.+ self.projection+ .note_structural_read(TransactionFactSide::After, node, StructuralRead::EarlierSiblings);+ self.statistics.bloom_rejections += 1;+ continue;+ }+ // NB: An entry its bucket's key proves matches without its selector being read, and+ // matches unscoped.+ let scope_proximity = match bucket_entry.covered(keys.tag_is_lowercase) {+ true => u32::MAX,+ false => {+ let selector = match bucket_entry.scoped() {+ true => self.index.entry_selector(entry),+ false => EntrySelector::unscoped(source.space.resolve(bucket_entry.selector())),+ };+ self.statistics.evaluations += 1;+ let matches = match bucket_entry.subject_covered(keys.tag_is_lowercase) {+ true => {+ self.evaluator+ .matches_left_of_subject(selector, node, self.state.document_matching())?+ }+ false => {+ self.evaluator+ .matches_entry_selector(selector, node, self.state.document_matching())?+ }+ };+ if !matches {+ continue;+ }+ self.evaluator.scope_proximity_of_match(node)+ }+ };+ // NB: The entry is read once, in place from the segment holding it where the buckets are one's.+ let matched = source.matched(self.index, entry);+ let (group, rule) = (matched.group, matched.rule);+ // A document sheet the scope holds too decides from the scope.+ if self.index.group_of(scope) != Some(group)+ && self+ .state+ .rules+ .attachment_in_scope(self.state.rules.rule_sheet(rule), scope)+ .is_some()+ {+ continue;+ }+ self.statistics.matches += 1;+ out.push(ElementMatch {+ entry,+ rule,+ specificity: matched.specificity,+ scope_proximity,+ pseudo_kind: matched.pseudo_kind,+ context_depth: match group {+ ScopeGroupID::DOCUMENT => 0,+ _ => scope_depth,+ },+ scope: match group {+ ScopeGroupID::DOCUMENT => TreeScopeID::DOCUMENT,+ _ => scope,+ },+ });+ }+ Ok(())+ }+}++impl crate::css::style::RetainedState {+ /// Every scope a `::part()` rule can address this element from, nearest host first.+ ///+ /// One per level of `exportparts` forwarding: the tree each forwarding host stands in holds+ /// rules that can name the element under the name that host exposed it by. Duplicates are+ /// dropped because two levels can stand in one tree.+ pub(in crate::css::style) fn part_exposure_scopes(+ &self,+ node: StyleNodeID,+ ) -> impl Iterator<Item = TreeScopeID> + '_ {+ let mut seen: Vec<TreeScopeID> = Vec::new();+ self.projection+ .part_hosts_of(node)+ .iter()+ .map(|&(_, host)| self.projection.tree_scope(host))+ .filter(move |scope| match seen.contains(scope) {+ true => false,+ false => {+ seen.push(*scope);+ true+ }+ })+ }+}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_changes.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_changes.rsnew file mode 100644index 00000000000..784c3b19fe8--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_changes.rs@@ -0,0 +1,386 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What an update of the rule index changed, and the elements those changes can restyle: the ones+//! that matched an entry that died or moved in the cascade order, and the ones that match an entry+//! that arrived.+//!+//! NB: An element is restyled only where it matches one of those rules, or matched one, rather than+//! wherever the features of the rules a sheet change adds or removes reach in the tree scope.++use super::super::*;+use super::bloom::AncestorFilter;+use super::matching::{ElementMatch, Matcher};+use super::records::RetainedRecords;+use super::rules::{RuleIndex, ScopeGroupID};++/// The entries of the rule index an update changed.+#[derive(Default)]+pub(super) struct RuleIndexChanges {+ /// By their number, whether each entry died or moved against another in the cascade order: an+ /// element that matched one is restyled.+ before: Vec<bool>,+ /// The entries that arrived, in the buckets the index holds them in: an element that matches+ /// one now is restyled.+ arrived: RuleIndex,+ /// The entries that died, whose numbers a user agent index the document shares instead may+ /// give to other selectors.+ died: Vec<u32>,+ /// Whether the document shares another user agent index, whose entries the invalidation map+ /// takes in only as it is built again.+ pub(super) user_agent_moved: bool,+ /// How many entries arrived.+ pub(super) arrived_entries: usize,+ /// The first entry that arrived. Those after it arrived too, or pad a page of entries.+ pub(super) first_arrived_entry: Option<u32>,+ /// The tree scopes of the entries that changed, and those that moved to another group, in no+ /// order, each once.+ pub(super) scopes: Vec<TreeScopeID>,+ /// The shadow trees that stopped deciding with the entries of one group, or started deciding+ /// with those of another that was there before.+ regrouped: Vec<Regrouped>,+}++/// A shadow tree whose sheets or layers moved, which decides with the entries of another group of+/// trees: the elements that matched an entry of the group it left, or that match one of the+/// group it joined, are restyled.+pub(super) struct Regrouped {+ pub(super) scope: TreeScopeID,+ pub(super) left: Option<ScopeGroupID>,+ /// The group it joined, where it held entries before; the entries of a new one arrived.+ pub(super) joined: Option<ScopeGroupID>,+}++/// An entry an update kept, with the ranks it held before it.+pub(super) struct StayedEntry {+ id: u32,+ ranks: Ranks,+}++impl StayedEntry {+ pub(super) fn of(id: u32, entries: &super::rules::IndexEntries) -> Self {+ Self {+ id,+ ranks: Ranks::of(entries, id),+ }+ }+}++/// Where an entry's layer, sheet and rule stand.+#[derive(Clone, Copy)]+struct Ranks {+ layer: u64,+ sheet: u64,+ rule: u64,+}++impl Ranks {+ fn of(entries: &super::rules::IndexEntries, id: u32) -> Self {+ let placement = entries.placement(id as usize);+ Self {+ layer: placement.layer_rank,+ sheet: placement.sheet_rank,+ rule: entries.view(id as usize).rule_rank(),+ }+ }+}++/// Note in `moved` the entries of `stayed` that moved against another of them in the cascade+/// order, where `entries` holds the ranks they hold now.+pub(super) fn note_moved(entries: &super::rules::IndexEntries, stayed: &[StayedEntry], moved: &mut Vec<u32>) {+ // The entries that stayed decide against one another as they did where they keep their+ // order, for declarations of either importance: of those that do not, as few as can be+ // are taken to have moved.+ for important in [false, true] {+ let mut order: Vec<&StayedEntry> = stayed+ .iter()+ .filter(|stayed| !important || entries.entry(stayed.id as usize).declares_important())+ .collect();+ let now = |stayed: &StayedEntry| cascade_key(entries, stayed.id, Ranks::of(entries, stayed.id), important);+ let before = |stayed: &StayedEntry| cascade_key(entries, stayed.id, stayed.ranks, important);+ order.sort_unstable_by_key(|stayed| (now(stayed), before(stayed)));+ let keys: Vec<_> = order.iter().map(|stayed| before(stayed)).collect();+ let kept = longest_ordered_run(&keys);+ for (position, stayed) in order.iter().enumerate() {+ // NB: An entry that moved matches the elements it matched.+ if !kept[position] {+ moved.push(stayed.id);+ }+ }+ }+}++impl RuleIndexChanges {+ /// The changes of an update of `index` that killed `died`, moved `moved` and added `added`.+ pub(super) fn new(+ index: &RuleIndex,+ died: Vec<u32>,+ moved: &[u32],+ added: &[u32],+ user_agent_moved: bool,+ regrouped: Vec<Regrouped>,+ ) -> Self {+ let mut before = vec![false; index.entries.len()];+ let mut scopes: Vec<TreeScopeID> = Vec::new();+ for &id in died.iter().chain(moved) {+ before[id as usize] = true;+ }+ let mut groups: Vec<ScopeGroupID> = Vec::new();+ for &id in died.iter().chain(moved).chain(added) {+ // NB: A user agent entry that died may have no entry of its number any more.+ let group = index+ .entries+ .get(id as usize)+ .map_or(ScopeGroupID::DOCUMENT, |_| index.entries.placement(id as usize).group);+ if !groups.contains(&group) {+ groups.push(group);+ }+ }+ // NB: The trees of a group that died moved to other groups, as `regrouped` says.+ for scope in groups+ .iter()+ .flat_map(|&group| index.scopes_of(group).iter().copied())+ .chain(regrouped.iter().map(|regrouped| regrouped.scope))+ {+ if !scopes.contains(&scope) {+ scopes.push(scope);+ }+ }+ Self {+ before,+ arrived: match added.is_empty() {+ true => RuleIndex::default(),+ false => index.buckets_of(added),+ },+ died,+ user_agent_moved,+ arrived_entries: added.len(),+ first_arrived_entry: added.iter().copied().min(),+ scopes,+ regrouped,+ }+ }++ /// Each entry as itself where it lives and did not die in this update, and none otherwise:+ /// the number of a user agent entry that died may stand for another selector now.+ pub(super) fn numbering(&self, index: &RuleIndex) -> Vec<Option<u32>> {+ let mut numbering = index.live_numbering();+ for &id in &self.died {+ numbering[id as usize] = None;+ }+ numbering+ }++ /// Whether any entry died.+ pub(super) fn any_died(&self) -> bool {+ !self.died.is_empty()+ }++ /// The entries that died.+ pub(super) fn died(&self) -> &[u32] {+ &self.died+ }++ /// Whether no entry changed.+ pub(super) fn is_empty(&self) -> bool {+ self.scopes.is_empty()+ }++ /// Visit each element under `roots` in the flat tree that the changes restyle, where `records`+ /// holds what the elements matched against the index before and `index` is the updated one,+ /// with the entries that arrived it matches, where those and what left its matches are all+ /// that moved of them, and none where it has to be matched anew.+ ///+ /// NB: No other entry's answer depends on the sheets: its selector and `@scope` levels are+ /// its own. What an entry that died matched leaves the element's matches as it is renumbered.+ pub(super) fn for_each_restyled(+ &self,+ state: &RetainedState,+ index: &RuleIndex,+ records: &RetainedRecords,+ roots: &[StyleNodeID],+ mut visit: impl FnMut(StyleNodeID, Option<&[ElementMatch]>),+ ) {+ let mut matcher = Matcher::reaching(index, &self.arrived, state);+ // NB: The arrived entries are few, and each is evaluated where an element reaches its+ // bucket, without the ancestor filter of a traversal.+ let mut filter = AncestorFilter::new();+ filter.fill();+ let mut matches = Vec::new();+ let left_any = self.before.iter().any(|&changed| changed);+ // NB: Match lists are interned, and a run of alike elements holds one of them.+ let mut last_list: Option<(&super::records::MatchList, bool)> = None;+ // NB: An element sharing no bit with these reaches no bucket of the entries that arrived,+ // and so matches none of them. Elements compare to selectors folded where ids and+ // classes do, which the bits are not.+ let reaching_bits = match state.document_matching().fold_ids_and_classes {+ true => u64::MAX,+ false => self.arrived.bucket_key_bits(),+ };+ for &root in roots {+ for node in state.projection.style_preorder(root) {+ let Some(facts) = state.projection.facts(node) else {+ continue;+ };+ // An element holding no record is under one that is not displayed, or arrived and+ // is styled for it.+ if records.get(node).is_none() {+ continue;+ }+ let mut matched_one = false;+ if left_any {+ matched_one = match (records.matches_of(node), last_list) {+ (Some(matched), Some((list, answer))) if std::sync::Arc::ptr_eq(matched, list) => answer,+ (Some(matched), _) => {+ let answer = matched.iter().any(|&entry| self.before[entry as usize]);+ last_list = Some((matched, answer));+ answer+ }+ (None, _) => {+ visit(node, None);+ continue;+ }+ };+ }+ matches.clear();+ if self.arrived_entries > 0 && facts.dispatch_bloom(true) & reaching_bits != 0 {+ // NB: An element whose match is not known is restyled, which finds out.+ if matcher.match_element(node, facts, &filter, &mut matches).is_err() {+ visit(node, None);+ continue;+ }+ }+ if matched_one || !matches.is_empty() {+ visit(node, Some(&matches));+ }+ }+ }+ for regrouped in &self.regrouped {+ Self::for_each_regrouped(regrouped, state, index, records, &filter, &mut |node| visit(node, None));+ }+ }++ /// Visit each element the shadow tree of `regrouped` reaches whose matches can have moved with+ /// the group its entries are of: one that matched an entry of the group it left, or that+ /// matches one of the group it joined.+ fn for_each_regrouped(+ regrouped: &Regrouped,+ state: &RetainedState,+ index: &RuleIndex,+ records: &RetainedRecords,+ filter: &AncestorFilter,+ visit: &mut impl FnMut(StyleNodeID),+ ) {+ let tree = &state.projection;+ // NB: A tree with no root, or a root with no host, holds no element the flat tree reaches.+ let Some(host) = state+ .scope_root(regrouped.scope)+ .and_then(|root| tree.host_of(root))+ .filter(|&host| tree.is_live(host))+ else {+ return;+ };+ let joined = regrouped+ .joined+ .map(|group| index.buckets_of(&index.live_entries_of(group)));+ let mut matcher = joined.as_ref().map(|joined| Matcher::reaching(index, joined, state));+ let mut matches = Vec::new();+ for node in tree.style_preorder(host) {+ let Some(facts) = tree.facts(node) else {+ continue;+ };+ if records.get(node).is_none() {+ continue;+ }+ let left_one = regrouped.left.is_some_and(|left| {+ records.matches_of(node).is_none_or(|matched| {+ matched.iter().any(|&entry| {+ index+ .entries+ .get(entry as usize)+ .is_none_or(|_| index.entries.placement(entry as usize).group == left)+ })+ })+ });+ if left_one {+ visit(node);+ continue;+ }+ let Some(matcher) = matcher.as_mut() else {+ continue;+ };+ matches.clear();+ if matcher+ .match_element(node, facts, filter, &mut matches)+ .map_or(true, |()| !matches.is_empty())+ {+ visit(node);+ }+ }+ }+}++/// Where the declarations of `entry` of the given importance stand in the cascade order against+/// those of the other entries of its tree scope. Entries of different scopes reach an element+/// from different encapsulation contexts, which the tree orders, or from different origins.+fn cascade_key(+ entries: &super::rules::IndexEntries,+ id: u32,+ ranks: Ranks,+ important: bool,+) -> (ScopeGroupID, CascadePriority) {+ let entry = entries.view(id as usize);+ let placement = entries.placement(id as usize);+ (+ placement.group,+ CascadePriority::new(PriorityInputs {+ origin: placement.origin,+ important,+ context_depth: 0,+ element_attachment: ElementAttachment::Rule,+ layer_rank: ranks.layer,+ specificity: entry.specificity(),+ scope_proximity: u32::MAX,+ sheet_rank: ranks.sheet,+ rule_rank: ranks.rule,+ }),+ )+}++/// Whether each element of `keys` is in a longest run of them that never decreases.+fn longest_ordered_run<T: Ord>(keys: &[T]) -> Vec<bool> {+ // The index of the element ending the least-keyed run of each length, and the element before+ // each one in its run.+ let mut ends: Vec<usize> = Vec::new();+ let mut previous: Vec<Option<usize>> = Vec::with_capacity(keys.len());+ for (index, key) in keys.iter().enumerate() {+ let length = ends.partition_point(|&end| keys[end] <= *key);+ previous.push(length.checked_sub(1).map(|shorter| ends[shorter]));+ match ends.get_mut(length) {+ Some(end) => *end = index,+ None => ends.push(index),+ }+ }+ let mut kept = vec![false; keys.len()];+ for index in std::iter::successors(ends.last().copied(), |&index| previous[index]) {+ kept[index] = true;+ }+ kept+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn the_longest_ordered_run_keeps_the_most_elements_in_order() {+ assert_eq!(longest_ordered_run::<u32>(&[]), Vec::<bool>::new());+ assert_eq!(longest_ordered_run(&[1, 2, 3]), [true, true, true]);+ assert_eq!(longest_ordered_run(&[2, 1]).iter().filter(|&&kept| kept).count(), 1);+ assert_eq!(longest_ordered_run(&[1, 5, 2, 3, 4]), [true, false, true, true, true]);+ assert_eq!(longest_ordered_run(&[1, 1, 2]), [true, true, true]);+ }+}diff --git a/Libraries/LibWeb/Rust/src/css/style/program.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store.rssimilarity index 52%rename from Libraries/LibWeb/Rust/src/css/style/program.rsrename to Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store.rsindex b74fb2ce499..b420f3a741c 100644--- a/Libraries/LibWeb/Rust/src/css/style/program.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store.rs@@ -4,187 +4,59 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The semantic stylesheet program.+//! The rules the engine decides with.//!-//! CSSOM objects and the program are deliberately separate things. CSSOM objects preserve API-//! identity, ownership, indices, and serialization behaviour; the program is an immutable,+//! CSSOM objects and the rule store are deliberately separate things. CSSOM objects preserve API+//! identity, ownership, indices, and serialization behavior; the store is an immutable,//! content-keyable representation used for computation. Editing a CSSOM object creates a new//! semantic version without replacing the wrapper object, which is what lets a collection reflect//! an API-required mutation synchronously while the semantic work stays queued until the next//! required observation.//!//! Identity is split finely on purpose. A declaration edit preserves the rule's identity and its-//! selector program while creating a new rule version and declaration block, so selector truth is-//! not invalidated by an edit that cannot change it. A selector edit preserves CSSOM identity but-//! changes the selector program, so exactly the match relation is affected.+//! selectors while creating a new rule version and declaration block, so selector truth is not+//! invalidated by an edit that cannot change it. A selector edit preserves CSSOM identity but+//! changes the selectors, so exactly the match relation is affected.//!//! Nested group rules form a persistent tree. Editing one descendant creates new versions only//! along the path to it; unchanged selectors, declarations, and conditions keep their identities,//! and a group rule detached from a sheet takes its subtree with it while shared descendants stay//! alive if something else still references them.+mod identities;+pub(in crate::css::style) mod native;mod rule_records;mod rule_versions;+pub(in crate::css::style) use native::TargetPages;+pub(in crate::css::style) use rule_records::RuleRecordPages;+pub(in crate::css::style) use rule_versions::RuleVersionPages;+mod sheet_occurrences;+mod staging;+mod user_agent;+use crate::css::declaration_block::DeclarationEntry;+use crate::css::declaration_block::{DeclarationBlockHeader, SharedDeclarationBlock};+pub use identities::*;use rule_records::RuleRecordTable;use rule_versions::RuleVersionTable;--pub use crate::css::cascaded_properties::CascadeOrigin;--use super::cascade::CascadeOperator;-use super::cascade::SpecifiedValueID;-use super::column::BitColumn;-use super::column::Column;-use super::fast_hash::FastMap as HashMap;-use super::fast_hash::FastSet as HashSet;-use super::index::StyleAtomID;-use super::order::OrderMaintenance;-use super::order::OrderToken;-use super::transaction::ProgramVersion;-use super::tree::TreeScopeID;-use super::weak_pool::WeakPool;+pub(in crate::css::style) use sheet_occurrences::ScopeSheetOccurrences;+pub(in crate::css::style) use staging::{ProgramStaging, RuleChanges, SheetRuleReplacement};+use user_agent::UserAgentBinding;+pub(in crate::css::style) use user_agent::{UserAgentRules, UserAgentVariant};++use super::super::column::BitColumn;+use super::super::column::Column;+use super::super::fast_hash::FastMap as HashMap;+use super::super::fast_hash::FastSet as HashSet;+use super::super::index::StyleAtomID;+use super::super::order::OrderMaintenance;+use super::super::order::OrderToken;+use super::super::tree::TreeScopeID;use crate::css::style_value::RetainedStyleValueData;use std::hash::{Hash, Hasher};use std::num::NonZeroU32;-use std::sync::{Arc, Mutex, MutexGuard, OnceLock};--define_id! {- /// Identity of a CSSOM `CSSStyleSheet` wrapper object. Assigned by C++, which owns the wrapper.- pub struct StyleSheetObjectID(pub);-}-define_id! {- /// Semantic identity of a sheet, stable across edits to its contents.- pub struct SheetID(pub);-}-define_id! {- /// Semantic identity of a rule, stable across edits to its declarations or selector.- pub struct RuleID(pub);-}-define_id! {- /// Immutable identity of a compiled selector program.- pub struct SelectorProgramID(pub);-}-define_id! {- /// Dense document identity of one entry in a compiled selector program.- pub struct EntryID(pub);-}--/// One longhand property a rule declares, and whether it declares it important. Importance is part-/// of the identity because it moves the declaration to a different rung of the cascade, not because-/// it is a different property.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]-pub struct DeclaredProperty {- pub property: u16,- pub important: bool,- pub operator: CascadeOperator,- pub value: SpecifiedValueID,-}--/// One custom property a declaration block declares. The cascade tracks no winner per custom-/// property name: an element's custom-property environment cascades these by name when it is-/// computed, so a block carries them beside its longhand declarations.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]-pub struct CustomDeclaration {- pub name: StyleAtomID,- pub important: bool,- pub operator: CascadeOperator,- pub value: SpecifiedValueID,-}--define_id! {- /// Immutable identity of a declaration block, whether it came from a rule or a style node.- pub struct DeclarationBlockID(pub);-}-define_id! {- /// Collision-checked semantic identity of one complete rule declaration inventory.- default pub(super) struct SemanticDeclarationID(pub(super));-}-define_id! {- /// Immutable identity of a compiled condition program: `@media`, `@supports`, `@container`.- pub struct ActivationPredicateID(pub);-}--define_id! {- /// Identity of a cascade layer: the interned qualified layer name. Rules reference the identity- /// rather than a copied numeric rank, so each tree scope can order the same name independently- /// and a layer topology change does not rewrite every declaration that lives in it.- pub struct CascadeLayerID(pub);-}--impl CascadeLayerID {- /// The implicit outer layer that unlayered rules belong to.- pub const UNLAYERED: Self = Self(0);-}--define_id! {- /// Identity of an `@scope` scope. Distinct from a tree scope: one is a CSS construct, the other- /// is a DOM one.- pub struct StyleScopeID(pub);-}--impl StyleScopeID {- /// Not inside any `@scope`.- pub const NONE: Self = Self(0);-}--/// What kind of rule a program node is. The kinds exist so that a program delta can be routed to-/// the consumers that care: editing a keyframes rule begins at animations referencing its name,-/// not at every element in the scope.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]-pub enum RuleKind {- Style,- #[cfg(test)]- Media,- CounterStyle,- FontFeatureValues,- Keyframes,- Property,- Function,-}--impl RuleKind {- /// Whether the rule contributes declarations through selector matching.- #[must_use]- pub fn matches_elements(self) -> bool {- self == Self::Style- }-}--/// The immutable semantic contents of one rule version.-///-/// The sheet order token is deliberately absent: rules reference their sheet, and the sheet holds-/// the token. Moving a sheet therefore updates one token instead of rewriting every rule in it.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]-pub struct RuleVersion {- pub rule: RuleID,- pub kind: RuleKind,- /// The name a rule declares, for the rules that reach their consumers by name rather than by- /// matching anything: the animation a `@keyframes` describes, the custom property an `@property`- /// registers. Which index the name is looked up in is decided by the rule's kind.- pub declared_name: Option<StyleAtomID>,- pub selector_program: Option<SelectorProgramID>,- pub declaration_block: Option<DeclarationBlockID>,- pub activation_predicate: Option<ActivationPredicateID>,- pub layer: CascadeLayerID,- pub scope: StyleScopeID,-}--impl RuleVersion {- #[must_use]- pub fn new(rule: RuleID, kind: RuleKind) -> Self {- Self {- rule,- kind,- declared_name: None,- selector_program: None,- declaration_block: None,- activation_predicate: None,- layer: CascadeLayerID::UNLAYERED,- scope: StyleScopeID::NONE,- }- }-}+use std::sync::Arc;-/// One sheet's attachment to one style scope. A compiled program attaches to several scopes+/// One sheet's attachment to one style scope. A sheet attaches to several scopes/// without duplicating its selectors or declarations; only the scope-specific materializations/// stay separate.#[derive(Clone, Copy, Debug, PartialEq, Eq)]@@ -194,14 +66,14 @@ pub struct Attachment {}#[derive(Clone)]-struct Sheet {origin: CascadeOrigin,- /// Advances whenever this sheet's immutable selector or static-cascade dispatch changes.- dispatch_version: u64,/// Top-level rules, in source order.- rules: Vec<RuleID>,- rule_order: OrderMaintenance,+ rules: Arc<Vec<RuleID>>,+ rule_order: Arc<OrderMaintenance>,+ /// Whether `rules` and `rule_order` are the ones the process shares, which documents whose+ /// sheets hold their rules alike share. An edit copies them first.+ rules_shared: bool,attachments: Vec<Attachment>,/// A disabled sheet keeps its program, identities, and order tokens; only its activation/// changes, which is why `disabled` is a predicate update rather than a detach.@@ -210,13 +82,102 @@ struct Sheet {/// contributes nothing, and a rule inside it can reach no element.conditions_hold: bool,live: bool,+ /// The arenas the selector lists of the sheet's rules are in.+ selectors: SheetSelectors,+ /// The sheet of the process's user agent rules this one stands for, which holds its rules.+ user_agent: Option<SheetID>,+}++/// The arenas the selector lists of one sheet's rules are in: the sheet's parse, and each CSSOM+/// edit's, laid out one after another in one space, so that a rule version names its list by one+/// number. An arena never takes the place of another, so a number names one list for as long as+/// the sheet lives.+#[derive(Clone, Default)]+struct SheetSelectors {+ /// Each arena, by where it starts in the space, in increasing order of starts.+ arenas: Vec<(u32, crate::css::selector::SelectorListRef)>,+ /// Where each arena starts, by its serial.+ starts: HashMap<crate::css::selector_arena::SelectorArenaSerial, u32>,+ /// Where the next arena starts.+ next: u32,+ /// How many arenas the sheet kept when it last let go of those no rule named.+ kept: usize,+}++impl SheetSelectors {+ /// Where `list` starts in the space, which takes its arena where it has not yet.+ fn start_of(&mut self, list: &crate::css::selector::SelectorListRef) -> SheetListStart {+ let Some(offset) = list.start_offset() else {+ return SheetListStart::NONE;+ };+ let base = match self.starts.get(&list.serial()) {+ Some(&base) => base,+ None => {+ let base = self.next;+ self.next = base+ .checked_add(list.arena_len())+ .filter(|&next| next < SheetListStart::NONE.0)+ .expect("sheet selector space exhausted");+ self.arenas.push((base, list.clone()));+ self.starts.insert(list.serial(), base);+ base+ }+ };+ SheetListStart(base + offset)+ }++ /// The list starting at `start`.+ fn list(&self, start: SheetListStart) -> Option<crate::css::selector::SelectorListRef> {+ if start == SheetListStart::NONE {+ return None;+ }+ let index = self.arenas.partition_point(|&(base, _)| base <= start.0);+ let (base, arena) = &self.arenas[index.checked_sub(1).expect("a list starts in an arena of its sheet")];+ Some(arena.list_at_offset(start.0 - base))+ }++ /// Whether the sheet took enough arenas since it last let go of some that it is worth looking+ /// for those no rule names.+ fn wants_letting_go(&self) -> bool {+ self.arenas.len() > 2 * self.kept + 4+ }++ /// Keep only the arenas some list of `named` starts in.+ fn keep_named(&mut self, named: &mut [SheetListStart]) {+ named.sort_unstable_by_key(|start| start.0);+ let mut named = named.iter().map(|start| start.0).peekable();+ let ends: Vec<u32> = self+ .arenas+ .iter()+ .skip(1)+ .map(|&(base, _)| base)+ .chain(std::iter::once(self.next))+ .collect();+ let mut index = 0;+ self.arenas.retain(|&(base, _)| {+ let end = ends[index];+ index += 1;+ while named.next_if(|&start| start < base).is_some() {}+ named.peek().is_some_and(|&start| start < end)+ });+ self.starts = self+ .arenas+ .iter()+ .map(|(base, arena)| (arena.serial(), *base))+ .collect();+ self.kept = self.arenas.len();+ }++ fn heap_size(&self) -> usize {+ crate::heap_size::vec_bytes(&self.arenas) + crate::heap_size::map_bytes(&self.starts)+ }}#[derive(Clone)]struct Rule {sheet: SheetID,/// Whether the conditions of the groups this rule sits inside currently hold. A rule behind an- /// `@media` that does not match keeps its identity, its position and its compiled selector; it+ /// `@media` that does not match keeps its identity, its position and its selectors; it/// simply decides nothing, which is the same shape a disabled sheet has.conditions_hold: bool,/// Whether this rule sits in a cascade layer. Layer order decides between declarations that are@@ -224,14 +185,16 @@ struct Rule {in_a_layer: bool,parent: Option<RuleID>,children_slot: Option<NonZeroU32>,- version_slot: u32,nested_order: OrderToken,live: bool,gated_by_container_query: bool,- declarations: Arc<SharedRuleDeclarations>,- semantic_declaration: SemanticDeclarationID,+ /// The rule's declaration block, which holds what the cascade reads of it.+ declarations: Option<SharedDeclarationBlock>,}+// NB: Every rule of every sheet a document attaches has one.+const _: () = assert!(size_of::<Rule>() == 32);+impl Rule {fn sharing_key(&self) -> impl Eq + Hash + '_ {let Self {@@ -240,12 +203,10 @@ impl Rule {in_a_layer,parent,children_slot,- version_slot,nested_order,live,gated_by_container_query,declarations,- semantic_declaration,} = self;(sheet,@@ -253,12 +214,10 @@ impl Rule {in_a_layer,parent,children_slot,- version_slot,nested_order,live,gated_by_container_query,- Arc::as_ptr(declarations),- semantic_declaration,+ declarations.as_ref().map(SharedDeclarationBlock::as_ptr),)}}@@ -277,81 +236,167 @@ impl Hash for Rule {}}-#[derive(Clone, Default, PartialEq)]-struct RuleDeclarationData {- declared_properties: Vec<DeclaredProperty>,- /// The value each declaration was written with, parallel to `declared_properties`, when the- /// rule arrived with them. A consumer computing a value needs the written spelling, which the- /// canonical identity may have rewritten. Empty when the rule arrived without them.- written_values: Vec<RetainedStyleValueData>,- written_value_checks: Vec<super::publication::WrittenValueChecks>,- /// Whether a declared property may move layout geometry, including custom properties.+type WrittenValueChecks = super::pipeline::compute::WrittenValueChecks;++/// What the cascade reads of a declaration block beside its entries and values, in one+/// allocation the block holds: whether any declaration may move layout geometry, then the checks+/// of each longhand's written value, parallel to the block's values. It depends on the block's+/// content alone, so every engine publishing the block shares it.+pub(crate) struct BlockCascadeData {+ length: u32,may_affect_layout_geometry: bool,- /// The custom properties the rule declares, in declaration order, and the values they were- /// written with, parallel to them: a custom property resolves from its written spelling.- custom_declarations: Vec<CustomDeclaration>,- custom_written_values: Vec<RetainedStyleValueData>,}-impl RuleDeclarationData {}+const _: () = assert!(size_of::<BlockCascadeData>() == 8);+const _: () = assert!(align_of::<WrittenValueChecks>() <= align_of::<BlockCascadeData>());+const _: () = assert!(size_of::<BlockCascadeData>().is_multiple_of(align_of::<WrittenValueChecks>()));++impl BlockCascadeData {+ fn layout(length: usize) -> std::alloc::Layout {+ let too_many = "block declares too many properties";+ let bytes = length+ .checked_mul(size_of::<WrittenValueChecks>())+ .and_then(|bytes| bytes.checked_add(size_of::<Self>()))+ .expect(too_many);+ std::alloc::Layout::from_size_align(bytes, align_of::<Self>()).expect(too_many)+ }++ /// What the cascade reads of `block`.+ pub(in crate::css::style) fn new(block: &DeclarationBlockHeader) -> std::ptr::NonNull<Self> {+ let properties = block.properties();+ let length = properties.values().len();+ let may_affect_layout_geometry = !block.custom_properties().is_empty()+ || properties+ .entries()+ .iter()+ .any(|entry| crate::css::property_metadata::property_may_affect_layout_geometry(entry.property()));+ let layout = Self::layout(length);+ // SAFETY: The layout is nonzero, and the header and each check are written once.+ unsafe {+ let base = std::alloc::alloc(layout);+ if base.is_null() {+ std::alloc::handle_alloc_error(layout);+ }+ base.cast::<Self>().write(Self {+ length: u32::try_from(length).expect("block declares too many properties"),+ may_affect_layout_geometry,+ });+ let checks = base.add(size_of::<Self>()).cast::<WrittenValueChecks>();+ let written = RetainedStyleValueData::slice_from_shared(properties.values());+ for (index, (entry, value)) in properties.entries().iter().zip(written).enumerate() {+ checks+ .add(index)+ .write(WrittenValueChecks::prepare(entry.property(), value));+ }+ std::ptr::NonNull::new_unchecked(base.cast())+ }+ }-struct SharedRuleDeclarations {- data: RuleDeclarationData,-}+ /// The checks of each longhand's written value.+ fn checks(&self) -> &[WrittenValueChecks] {+ // SAFETY: The allocation holds `length` checks after the header.+ unsafe {+ ak::slice_from_raw_parts(+ std::ptr::from_ref(self)+ .cast::<u8>()+ .add(size_of::<Self>())+ .cast::<WrittenValueChecks>(),+ self.length as usize,+ )+ }+ }-impl std::ops::Deref for Rule {- type Target = RuleDeclarationData;+ fn heap_bytes(&self) -> usize {+ Self::layout(self.length as usize).size()+ }- fn deref(&self) -> &Self::Target {- &self.declarations.data+ /// Frees the data `data` points at.+ ///+ /// # Safety+ /// `data` must come from `new` and be freed once.+ pub(crate) unsafe fn free(data: std::ptr::NonNull<Self>) {+ // SAFETY: The data is live until here, and holds nothing that needs dropping.+ unsafe {+ let layout = Self::layout(data.as_ref().length as usize);+ std::alloc::dealloc(data.as_ptr().cast(), layout);+ }}}-fn share_rule_declarations(- data: RuleDeclarationData,- pool: &mut WeakPool<SharedRuleDeclarations>,-) -> Arc<SharedRuleDeclarations> {- // Canonical IDs are document-local, so equal numeric declarations alone are insufficient:- // compare the authored values as well before sharing their immutable storage.- let mut hasher = super::fast_hash::fast_hasher();- data.declared_properties.hash(&mut hasher);- data.custom_declarations.hash(&mut hasher);- for values in [&data.written_values, &data.custom_written_values] {- values.len().hash(&mut hasher);- for value in values {- let hash = crate::css::style_value::style_value_content_hash(value.optional_data());- hash.hash(&mut hasher);- }+/// What a rule declares: its declaration block, whose engine-independent cascade data the block+/// holds, and the custom properties among its declarations, named in the engine's atoms.+#[derive(Clone, Default)]+pub(in crate::css::style) struct RuleDeclarations {+ block: Option<SharedDeclarationBlock>,+ custom_declarations: Box<[CustomDeclaration]>,+}++impl RuleDeclarations {+ /// The declarations of `block`, whose custom properties the engine names `custom_names`, and+ /// whether this made the block's cascade data.+ pub(in crate::css::style) fn of_block(block: SharedDeclarationBlock, custom_names: &[StyleAtomID]) -> (Self, bool) {+ let made = block.make_cascade_data(BlockCascadeData::new);+ let custom_declarations = block+ .custom_properties()+ .iter()+ .zip(custom_names)+ .map(|(property, &name)| {+ CustomDeclaration::new(name, property.declaration.important, property.declaration.operator)+ })+ .collect();+ let declarations = Self {+ block: Some(block),+ custom_declarations,+ };+ (declarations, made)}- let hash = hasher.finish();- if let Some(found) = pool.find(hash, |candidate| candidate.data == data) {- return found;++ /// The longhands the rule declares, in declaration order.+ pub(in crate::css::style) fn declared_properties(&self) -> &[DeclarationEntry] {+ self.block.as_ref().map_or(&[], |block| block.properties().entries())}- let declarations = Arc::new(SharedRuleDeclarations { data });- pool.insert(hash, &declarations);- declarations-}+ /// The custom properties the rule declares, in declaration order.+ pub(in crate::css::style) fn custom_declarations(&self) -> &[CustomDeclaration] {+ &self.custom_declarations+ }-fn rule_declaration_pool() -> MutexGuard<'static, WeakPool<SharedRuleDeclarations>> {- // Every engine interns through the same pool, from whichever thread runs it. Declarations- // never reach back into the pool when they are dropped, so the lock is only held while- // interning.- static RULE_DECLARATIONS: OnceLock<Mutex<WeakPool<SharedRuleDeclarations>>> = OnceLock::new();- RULE_DECLARATIONS.get_or_init(Mutex::default).lock().unwrap()-}+ fn written_values(&self) -> &[RetainedStyleValueData] {+ self.block.as_ref().map_or(&[], |block| {+ RetainedStyleValueData::slice_from_shared(block.properties().values())+ })+ }-#[derive(Clone)]+ fn custom_written_values(&self) -> &[RetainedStyleValueData] {+ self.block.as_ref().map_or(&[], |block| {+ RetainedStyleValueData::slice_from_shared(block.custom_properties().values())+ })+ }+}-struct SemanticDeclarationEntry {- id: SemanticDeclarationID,- representative: RuleID,+impl PartialEq for RuleDeclarations {+ fn eq(&self, other: &Self) -> bool {+ let same_block = match (&self.block, &other.block) {+ (Some(block), Some(other)) => std::ptr::eq(block.as_ptr(), other.as_ptr()),+ (None, None) => true,+ _ => false,+ };+ self.custom_declarations == other.custom_declarations+ && (same_block+ || (self.declared_properties() == other.declared_properties()+ && self.written_values() == other.written_values()+ && self.custom_written_values() == other.custom_written_values()))+ }}/// The document's stylesheet program: identities, versions, order, and attachment.#[derive(Clone)]-pub struct StyleSheetProgram {- empty_declarations: Arc<SharedRuleDeclarations>,+pub struct RuleStore {+ /// What the host published of each rule beside its program: its declarations, the conditions of+ /// the container rules around it, and the identity of the rule object it came from.+ pub(in crate::css::style) native: native::NativeRuleRegistry,+ /// The custom properties each rule declaring any declares, named in the engine's atoms.+ custom_declarations: HashMap<RuleID, Box<[CustomDeclaration]>>,sheets: Vec<Sheet>,rules: RuleRecordTable,rule_children: Vec<Vec<RuleID>>,@@ -362,8 +407,6 @@ pub struct StyleSheetProgram {/// is gated without reading the rule's record.rules_gated_by_container_query: usize,rule_versions: RuleVersionTable,- semantic_declarations: HashMap<u64, Vec<SemanticDeclarationEntry>>,- next_semantic_declaration_id: u32,/// Sheet order within each tree context. Sheets in different tree contexts are ordered by the/// encapsulation component of cascade priority, not by these tokens.@@ -378,30 +421,137 @@ pub struct StyleSheetProgram {layer_ranks: Column<Option<HashMap<CascadeLayerID, u32>>>,scopes_using_document_sheets: BitColumn,- version: ProgramVersion,- routing_liveness_version: u64,+ /// The `@scope` levels the scoped style rules are inside, by the scope their versions name,+ /// from one on.+ scope_chains: Vec<Arc<super::super::bridge::BoundScopeChain>>,+ /// The process's user agent rules the document's user agent sheets stand for, which the+ /// document reads rather than recording them.+ user_agent: Option<UserAgentBinding>,}-impl StyleSheetProgram {- pub(super) fn collect_atoms(&self, atoms: &mut HashSet<StyleAtomID>) -> u64 {+impl RuleStore {+ /// The scope a rule version inside the `@scope` levels `chain` names.+ pub(in crate::css::style) fn scope_of_chain(+ &mut self,+ chain: &super::super::bridge::BoundScopeChain,+ ) -> StyleScopeID {+ if chain.levels.is_empty() {+ return StyleScopeID::NONE;+ }+ self.scope_chains.push(Arc::new(chain.clone()));+ StyleScopeID(u32::try_from(self.scope_chains.len()).expect("style scope space exhausted"))+ }++ /// The `@scope` levels `scope` names, or none for a rule inside no `@scope`.+ pub(in crate::css::style) fn scope_chain(+ &self,+ scope: StyleScopeID,+ ) -> Option<&Arc<super::super::bridge::BoundScopeChain>> {+ (scope != StyleScopeID::NONE).then(|| &self.scope_chains[scope.0 as usize - 1])+ }++ /// The bytes of what the cascade reads of the declarations of the store's rules: each block's+ /// cascade data once, with the values its declarations were written with counted aside, and+ /// the rules' custom declarations.+ pub(in crate::css::style) fn declarations_heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {+ use crate::heap_size::HeapSize;+ let blocks = self+ .rules+ .iter()+ .filter_map(|rule| rule.declarations.as_ref())+ .map(|block| {+ let Some(data) = block.cascade_data() else {+ return 0;+ };+ if !sizer.first_sight(std::ptr::from_ref(data)) {+ return 0;+ }+ data.heap_bytes()+ + RetainedStyleValueData::slice_from_shared(block.properties().values()).heap_size(sizer)+ + RetainedStyleValueData::slice_from_shared(block.custom_properties().values()).heap_size(sizer)+ })+ .sum::<usize>();+ blocks+ + crate::heap_size::map_bytes(&self.custom_declarations)+ + self+ .custom_declarations+ .values()+ .map(|declarations| size_of_val(&**declarations))+ .sum::<usize>()+ }++ /// The bytes of the store's sheets and rules. The native rule registry and the rules'+ /// declarations are not counted.+ pub(in crate::css::style) fn heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {+ use crate::heap_size::{map_bytes, vec_bytes};+ let sheets = vec_bytes(&self.sheets)+ + self+ .sheets+ .iter()+ .map(|sheet| {+ // NB: Documents whose sheets hold their rules alike share them, which count once.+ let rules = match sizer.arc_shallow(&sheet.rules) {+ 0 => 0,+ header => header + vec_bytes(&sheet.rules),+ };+ let rule_order = match sizer.arc_shallow(&sheet.rule_order) {+ 0 => 0,+ header => header + sheet.rule_order.heap_size(),+ };+ rules + rule_order + vec_bytes(&sheet.attachments) + sheet.selectors.heap_size()+ })+ .sum::<usize>();+ let order = self.sheet_order.heap_size()+ + self+ .sheet_order+ .iter()+ .flatten()+ .map(OrderMaintenance::heap_size)+ .sum::<usize>();+ let sheets_by_scope =+ self.sheets_by_scope.heap_size() + self.sheets_by_scope.iter().map(vec_bytes).sum::<usize>();+ let layer_ranks =+ self.layer_ranks.heap_size() + self.layer_ranks.iter().flatten().map(map_bytes).sum::<usize>();+ sheets+ + self.rules.heap_size(sizer, |_, _| 0)+ + vec_bytes(&self.rule_children)+ + self.rule_children.iter().map(vec_bytes).sum::<usize>()+ + self.rule_versions.heap_size(sizer)+ + order+ + sheets_by_scope+ + layer_ranks+ + self.scopes_using_document_sheets.heap_size()+ + self.user_agent.as_ref().map_or(0, UserAgentBinding::heap_size)+ }++ pub(in crate::css::style) fn collect_atoms(&self, atoms: &mut HashSet<StyleAtomID>) -> u64 {let mut visited = 0_u64;- for rule in self.rules.iter() {+ for (id, rule) in self.rules.iter().enumerate() {if !rule.live {continue;}visited += 1;- for declaration in &rule.custom_declarations {+ for declaration in self.custom_declarations_of(RuleID(id as u32)) {visited += 1;atoms.insert(declaration.name);}- let version = self.rule_versions[rule.version_slot as usize];- if let Some(name) = version.declared_name {+ let version = &self.rule_versions[id];+ if let Some(name) = version.declared_name() {atoms.insert(name);}if version.layer != CascadeLayerID::UNLAYERED {atoms.insert(StyleAtomID(version.layer.0));}}+ // NB: What the host and the summaries read of a rule's selectors names the atoms of their+ // arena, which a sweep has to keep the document's names of.+ for sheet in self.sheets.iter().filter(|sheet| sheet.live) {+ for (_, arena) in &sheet.selectors.arenas {+ let leased = arena.leased_atoms();+ visited += u64::try_from(leased.len()).expect("atom count exceeds u64");+ atoms.extend(leased.iter().copied());+ }+ }for ranks in self.layer_ranks.iter().flatten() {visited += u64::try_from(ranks.len()).expect("layer rank count exceeds u64");atoms.extend(@@ -417,77 +567,43 @@ impl StyleSheetProgram {#[must_use]pub fn new() -> Self {Self {- empty_declarations: share_rule_declarations(RuleDeclarationData::default(), &mut rule_declaration_pool()),+ native: Default::default(),+ custom_declarations: HashMap::default(),sheets: Vec::new(),rules: RuleRecordTable::default(),rule_children: Vec::new(),rules_declaring_custom_properties: 0,rules_gated_by_container_query: 0,rule_versions: RuleVersionTable::default(),- semantic_declarations: HashMap::default(),- next_semantic_declaration_id: 1,sheet_order: Column::default(),sheets_by_scope: Column::default(),layer_ranks: Column::default(),scopes_using_document_sheets: BitColumn::default(),- version: ProgramVersion(1),- routing_liveness_version: 1,+ scope_chains: Vec::new(),+ user_agent: None,}}- #[must_use]- pub fn version(&self) -> ProgramVersion {- self.version- }-- #[must_use]- pub fn routing_liveness_version(&self) -> u64 {- self.routing_liveness_version- }-- fn bump_version(&mut self) {- self.version = ProgramVersion(self.version.0 + 1);- }-- fn bump_routing_liveness_version(&mut self) {- self.routing_liveness_version = self- .routing_liveness_version- .checked_add(1)- .expect("routing liveness version overflow");- }-- fn bump_sheet_dispatch_version(&mut self, sheet: SheetID) {- let version = &mut self.sheets[sheet.0 as usize].dispatch_version;- *version = version.checked_add(1).expect("sheet dispatch version overflow");- }-- fn bump_rule_sheet_dispatch_version(&mut self, rule: RuleID) {- self.bump_sheet_dispatch_version(self.rules[rule.0 as usize].sheet);- }-// -- Sheets ------------------------------------------------------------------------------- pub fn add_sheet(&mut self, _object: StyleSheetObjectID, origin: CascadeOrigin) -> SheetID {+ pub fn add_sheet(&mut self, origin: CascadeOrigin) -> SheetID {let id = SheetID(u32::try_from(self.sheets.len()).expect("sheet identity space exhausted"));self.sheets.push(Sheet {origin,- dispatch_version: 0,- rules: Vec::new(),- rule_order: OrderMaintenance::new(),+ rules: Arc::default(),+ rule_order: Arc::default(),+ rules_shared: false,attachments: Vec::new(),enabled: true,conditions_hold: true,live: true,+ selectors: SheetSelectors::default(),+ user_agent: None,});id}- #[must_use]- pub fn sheet_dispatch_version(&self, sheet: SheetID) -> u64 {- self.sheets[sheet.0 as usize].dispatch_version- }-#[cfg(test)]fn sheet_order_mut(&mut self, tree_scope: TreeScopeID) -> &mut OrderMaintenance {let index = tree_scope.0 as usize;@@ -495,90 +611,6 @@ impl StyleSheetProgram {self.sheet_order[index].get_or_insert_with(OrderMaintenance::new)}- /// Attach a sheet to a style scope at the end of that scope's sheet order.- #[cfg(test)]- pub fn attach_sheet(&mut self, sheet: SheetID, tree_scope: TreeScopeID) -> Attachment {- let order_axis = self.sheet_order_mut(tree_scope);-- let order = order_axis.insert_last();-- let attachment = Attachment { tree_scope, order };- let attachments = &mut self.sheets[sheet.0 as usize].attachments;- attachments.push(attachment);-- let scope_index = tree_scope.0 as usize;- self.sheets_by_scope.ensure(scope_index);- self.sheets_by_scope[scope_index].push(sheet);-- self.bump_routing_liveness_version();- self.bump_version();- attachment- }-- /// Attach a sheet immediately before another sheet's attachment in the same scope. Loading- /// order does not determine cascade order: a linked or imported sheet receives its position- /// from document and rule order before or while it loads, and attachment reuses that position.- #[cfg(test)]- pub fn attach_sheet_before(&mut self, sheet: SheetID, before: Attachment) -> Attachment {- let order_axis = self.sheet_order_mut(before.tree_scope);-- let order = order_axis.insert_before(before.order);-- let attachment = Attachment {- tree_scope: before.tree_scope,- order,- };- let attachments = &mut self.sheets[sheet.0 as usize].attachments;- attachments.push(attachment);-- let scope_index = before.tree_scope.0 as usize;- self.sheets_by_scope.ensure(scope_index);- let position = self.sheets_by_scope[scope_index]- .iter()- .position(|&candidate| {- self.attachment_in_scope(candidate, before.tree_scope)- .is_some_and(|attachment| attachment.order == before.order)- })- .expect("an insertion target must remain attached");- self.sheets_by_scope[scope_index].insert(position, sheet);-- self.bump_routing_liveness_version();- self.bump_version();- attachment- }-- #[cfg(test)]- pub fn detach_sheet(&mut self, sheet: SheetID, tree_scope: TreeScopeID) {- let attachments = &mut self.sheets[sheet.0 as usize].attachments;- let Some(position) = attachments- .iter()- .position(|attachment| attachment.tree_scope == tree_scope)- else {- return;- };- let attachment = attachments.remove(position);- if let Some(order) = self.sheet_order.get_mut(tree_scope.0 as usize).and_then(Option::as_mut) {- order.remove(attachment.order);- }- if let Some(sheets) = self.sheets_by_scope.get_mut(tree_scope.0 as usize)- && let Some(position) = sheets.iter().position(|&candidate| candidate == sheet)- {- sheets.remove(position);- }- self.bump_routing_liveness_version();- self.bump_version();- }-- /// Move a sheet within its scope. Only the sheet's own order token is written; the program- /// nodes of its rules are untouched, because they reference the sheet rather than copying its- /// position.- #[cfg(test)]- pub fn move_sheet_before(&mut self, sheet: SheetID, before: Attachment) {- let tree_scope = before.tree_scope;- self.detach_sheet(sheet, tree_scope);- self.attach_sheet_before(sheet, before);- }-/// Enabling or disabling a sheet updates its activation, not its attachment: identities, order/// tokens, and compiled programs all survive.pub fn set_sheet_enabled(&mut self, sheet: SheetID, enabled: bool) {@@ -586,14 +618,6 @@ impl StyleSheetProgram {return;}self.sheets[sheet.0 as usize].enabled = enabled;- self.bump_routing_liveness_version();- self.bump_version();- }-- #[must_use]- #[cfg(test)]- pub fn sheet_is_enabled(&self, sheet: SheetID) -> bool {- self.sheets[sheet.0 as usize].enabled}/// Record whether a sheet's own conditions hold. This is activation, not attachment: the sheet@@ -603,8 +627,6 @@ impl StyleSheetProgram {return;}self.sheets[sheet.0 as usize].conditions_hold = conditions_hold;- self.bump_routing_liveness_version();- self.bump_version();}#[must_use]@@ -628,10 +650,10 @@ impl StyleSheetProgram {#[inline]#[must_use]pub fn rule_can_decide(&self, rule: RuleID) -> bool {- if !self.rules[rule.0 as usize].live || !self.rules[rule.0 as usize].conditions_hold {+ if !self.rule_is_live(rule) || !self.rule_conditions_hold(rule) {return false;}- let sheet = self.rules[rule.0 as usize].sheet;+ let sheet = self.rule_sheet(rule);self.sheet_contributes(sheet) && !self.sheets[sheet.0 as usize].attachments.is_empty()}@@ -639,17 +661,23 @@ impl StyleSheetProgram {/// conditions this is activation, not existence: the rule keeps its identity and its place./// Returns whether the answer moved.pub fn set_rule_conditions_hold(&mut self, rule: RuleID, conditions_hold: bool) -> bool {+ if rule.in_user_agent_rules().is_some() {+ return self+ .user_agent_binding_mut()+ .set_rule_conditions_hold(rule, conditions_hold);+ }if self.rules[rule.0 as usize].conditions_hold == conditions_hold {return false;}self.rules[rule.0 as usize].conditions_hold = conditions_hold;- self.bump_routing_liveness_version();- self.bump_version();true}#[must_use]pub fn rule_conditions_hold(&self, rule: RuleID) -> bool {+ if rule.in_user_agent_rules().is_some() {+ return self.user_agent_binding().rule_conditions_hold(rule);+ }self.rules[rule.0 as usize].conditions_hold}@@ -658,22 +686,11 @@ impl StyleSheetProgram {return;}self.rules[rule.0 as usize].in_a_layer = in_a_layer;- self.bump_rule_sheet_dispatch_version(rule);}#[must_use]pub fn rule_is_in_a_layer(&self, rule: RuleID) -> bool {- self.rules[rule.0 as usize].in_a_layer- }-- /// Every live rule in this scope that sits in a cascade layer.- #[must_use]- pub fn rules_in_a_layer_in_scope(&self, scope: TreeScopeID) -> Vec<RuleID> {- self.sheets_in_scope(scope)- .iter()- .flat_map(|&sheet| self.rules_in_sheet(sheet))- .filter(|rule| self.rules[rule.0 as usize].in_a_layer)- .collect()+ self.record(rule).in_a_layer}#[must_use]@@ -681,11 +698,6 @@ impl StyleSheetProgram {self.sheets[sheet.0 as usize].origin}- #[must_use]- pub fn sheet_attachments(&self, sheet: SheetID) -> &[Attachment] {- &self.sheets[sheet.0 as usize].attachments- }-/// The style scopes a sheet is attached to. A sheet adopted by several shadow roots decides in/// each of them and in none of the others.#[must_use]@@ -708,18 +720,63 @@ impl StyleSheetProgram {.map_or(&[], Vec::as_slice)}+ /// The tree scopes with sheets attached, the document first.+ pub fn scopes_with_sheets(&self) -> impl Iterator<Item = TreeScopeID> + '_ {+ self.sheets_by_scope+ .iter()+ .enumerate()+ .filter(|(_, sheets)| !sheets.is_empty())+ .map(|(index, _)| TreeScopeID(u32::try_from(index).expect("tree scope identity space exhausted")))+ }+pub(crate) fn set_sheets_in_scope(&mut self, tree_scope: TreeScopeID, sheets: Vec<SheetID>) {let index = tree_scope.0 as usize;self.sheet_order.ensure(index);self.sheets_by_scope.ensure(index);let previous_sheets = std::mem::replace(&mut self.sheets_by_scope[index], sheets);- let mut attachment_presence: Vec<_> = previous_sheets++ // The sheets that stay keep their positions where they keep their order, so that a sheet+ // arriving or leaving moves the rank of no other: only a reordering ranks them anew.+ let previous: HashSet<SheetID> = previous_sheets.iter().copied().collect();+ let current: HashSet<SheetID> = self.sheets_by_scope[index].iter().copied().collect();+ let kept_before = previous_sheets.iter().filter(|sheet| current.contains(sheet));+ let kept_after = self.sheets_by_scope[index].iter()- .chain(&self.sheets_by_scope[index])- .map(|&sheet| (sheet, self.sheet_is_attached_somewhere(sheet)))- .collect();- attachment_presence.sort_unstable_by_key(|&(sheet, _)| sheet);- attachment_presence.dedup_by_key(|entry| entry.0);+ .filter(|sheet| previous.contains(sheet));+ if self.sheet_order[index].is_some() && kept_before.eq(kept_after) {+ let order = self.sheet_order[index].as_mut().expect("the scope has an order");+ for sheet in previous_sheets.iter().filter(|sheet| !current.contains(sheet)) {+ let attachments = &mut self.sheets[sheet.0 as usize].attachments;+ if let Some(position) = attachments+ .iter()+ .position(|attachment| attachment.tree_scope == tree_scope)+ {+ order.remove(attachments.remove(position).order);+ }+ }+ let mut next: Option<OrderToken> = None;+ for position in (0..self.sheets_by_scope[index].len()).rev() {+ let sheet = self.sheets_by_scope[index][position];+ let attachments = &mut self.sheets[sheet.0 as usize].attachments;+ if previous.contains(&sheet) {+ next = attachments+ .iter()+ .find(|attachment| attachment.tree_scope == tree_scope)+ .map(|attachment| attachment.order);+ continue;+ }+ let token = match next {+ Some(before) => order.insert_before(before),+ None => order.insert_last(),+ };+ attachments.push(Attachment {+ tree_scope,+ order: token,+ });+ next = Some(token);+ }+ return;+ }for sheet in previous_sheets {self.sheets[sheet.0 as usize]@@ -738,55 +795,23 @@ impl StyleSheetProgram {}self.sheet_order[index] = Some(order);-- if attachment_presence- .into_iter()- .any(|(sheet, was_attached)| was_attached != self.sheet_is_attached_somewhere(sheet))- {- self.bump_routing_liveness_version();- }- self.bump_version();}// -- Rules -------------------------------------------------------------------------------- /// Append a rule to a sheet or to a grouping rule.- #[cfg(test)]- pub fn append_rule(&mut self, sheet: SheetID, parent: Option<RuleID>, kind: RuleKind) -> RuleID {- let order_axis = &mut self.sheets[sheet.0 as usize].rule_order;-- let order = order_axis.insert_last();-- self.create_rule(sheet, parent, kind, order, None, true)- }-pub(crate) fn reserve_rule(&mut self, sheet: SheetID, parent: Option<RuleID>, kind: RuleKind) -> RuleID {- let order_axis = &mut self.sheets[sheet.0 as usize].rule_order;+ let order_axis = self.rule_order_mut(sheet);let order = order_axis.insert_last();self.create_rule(sheet, parent, kind, order, None, false)}- /// Insert a rule immediately before an existing sibling. Existing rules are neither renumbered- /// nor rematched: the new rule takes an order token between its neighbours.- #[cfg(test)]- pub fn insert_rule_before(&mut self, before: RuleID, kind: RuleKind) -> RuleID {- let sheet = self.rules[before.0 as usize].sheet;- let parent = self.rules[before.0 as usize].parent;- let sibling_order = self.rules[before.0 as usize].nested_order;- let order_axis = &mut self.sheets[sheet.0 as usize].rule_order;-- let order = order_axis.insert_before(sibling_order);-- self.create_rule(sheet, parent, kind, order, Some(before), true)- }-pub(crate) fn reserve_rule_before(&mut self, before: RuleID, kind: RuleKind) -> RuleID {let sheet = self.rules[before.0 as usize].sheet;let parent = self.rules[before.0 as usize].parent;let sibling_order = self.rules[before.0 as usize].nested_order;- let order_axis = &mut self.sheets[sheet.0 as usize].rule_order;+ let order_axis = self.rule_order_mut(sheet);let order = order_axis.insert_before(sibling_order);@@ -803,7 +828,9 @@ impl StyleSheetProgram {live: bool,) -> RuleID {let id = RuleID(u32::try_from(self.rules.len()).expect("rule identity space exhausted"));- let version_slot = self.allocate_rule_version(RuleVersion::new(id, kind));+ // NB: Every rule has one version, at its own number in the version table.+ self.rule_versions.push(RuleVersion::new(kind));+ debug_assert_eq!(self.rule_versions.len(), self.rules.len() + 1);self.rules.push(Rule {sheet,@@ -811,12 +838,10 @@ impl StyleSheetProgram {in_a_layer: false,parent,children_slot: None,- version_slot,nested_order: order,live,gated_by_container_query: false,- declarations: Arc::clone(&self.empty_declarations),- semantic_declaration: SemanticDeclarationID::default(),+ declarations: None,});let siblings = match parent {@@ -824,28 +849,39 @@ impl StyleSheetProgram {let slot = self.ensure_rule_children_slot(parent);&mut self.rule_children[slot]}- None => &mut self.sheets[sheet.0 as usize].rules,+ None => self.top_level_rules_mut(sheet),};match before.and_then(|before| siblings.iter().position(|sibling| *sibling == before)) {Some(position) => siblings.insert(position, id),None => siblings.push(id),}- if live {- self.bump_sheet_dispatch_version(sheet);- self.bump_routing_liveness_version();- self.bump_version();- }id}#[must_use]pub fn rule_sheet(&self, rule: RuleID) -> SheetID {- self.rules[rule.0 as usize].sheet+ match rule.in_user_agent_rules() {+ Some(rule) => self.user_agent_binding().sheet_of(rule),+ None => self.rules[rule.0 as usize].sheet,+ }+ }++ /// The record of `rule`, which the process holds where it is a user agent rule.+ #[inline]+ fn record(&self, rule: RuleID) -> &Rule {+ match rule.in_user_agent_rules() {+ Some(rule) => &self.user_agent_binding().store().rules[rule.0 as usize],+ None => &self.rules[rule.0 as usize],+ }}#[must_use]- pub(super) fn rule_children(&self, rule: RuleID) -> &[RuleID] {+ pub(in crate::css::style) fn rule_children(&self, rule: RuleID) -> &[RuleID] {+ debug_assert!(+ rule.in_user_agent_rules().is_none(),+ "a user agent rule's children are the process's"+ );self.rules[rule.0 as usize].children_slot.map_or(&[], |slot| self.rule_children[(slot.get() - 1) as usize].as_slice())@@ -872,37 +908,77 @@ impl StyleSheetProgram {#[must_use]pub fn rule_is_live(&self, rule: RuleID) -> bool {- self.rules[rule.0 as usize].live+ self.record(rule).live}+ #[inline]#[must_use]- pub fn sheet_is_attached_somewhere(&self, sheet: SheetID) -> bool {- !self.sheets[sheet.0 as usize].attachments.is_empty()+ pub fn rule_version(&self, rule: RuleID) -> &RuleVersion {+ match rule.in_user_agent_rules() {+ Some(rule) => &self.user_agent_binding().store().rule_versions[rule.0 as usize],+ None => &self.rule_versions[rule.0 as usize],+ }}- pub fn sheets_with_attachment_state(&self) -> impl Iterator<Item = (SheetID, bool)> + '_ {- self.sheets.iter().enumerate().map(|(index, sheet)| {- (- SheetID(u32::try_from(index).expect("sheet identity space exhausted")),- !sheet.attachments.is_empty(),- )- })+ /// The selectors of the version `version` of a rule of `sheet`.+ #[must_use]+ pub(in crate::css::style) fn selectors_of(+ &self,+ sheet: SheetID,+ version: &RuleVersion,+ ) -> Option<crate::css::selector::SelectorListRef> {+ let held = &self.sheets[sheet.0 as usize];+ match held.user_agent {+ Some(sheet) => self.user_agent_binding().store().selectors_of(sheet, version),+ None => held.selectors.list(version.selectors),+ }}- pub fn live_selector_programs(&self) -> impl Iterator<Item = (RuleID, SelectorProgramID)> + '_ {- self.rules.iter().enumerate().filter_map(|(index, rule)| {- let version = self.rule_versions[rule.version_slot as usize];- (rule.live).then_some((- RuleID(u32::try_from(index).expect("rule identity space exhausted")),- version.selector_program?,- ))- })+ /// The selectors of `rule`.+ #[must_use]+ pub(in crate::css::style) fn rule_selectors(&self, rule: RuleID) -> Option<crate::css::selector::SelectorListRef> {+ self.selectors_of(self.rule_sheet(rule), self.rule_version(rule))}- #[inline]+ /// Where `list` starts among the selectors of `sheet`, which a version of one of its rules+ /// names it by.+ pub(in crate::css::style) fn start_of_selectors(+ &mut self,+ sheet: SheetID,+ list: &crate::css::selector::SelectorListRef,+ ) -> SheetListStart {+ self.sheets[sheet.0 as usize].selectors.start_of(list)+ }++ /// Whether a sheet took enough selector arenas since it last let go of some that letting go of+ /// those no rule names is worth it.#[must_use]- pub fn rule_version(&self, rule: RuleID) -> RuleVersion {- self.rule_versions[self.rules[rule.0 as usize].version_slot as usize]+ pub(in crate::css::style) fn wants_letting_go_of_selectors(&self) -> bool {+ self.sheets.iter().any(|sheet| sheet.selectors.wants_letting_go())+ }++ /// Let go of the selector arenas of each sheet that no version of its rules names, where the+ /// sheet took many since it last did. Only the committed versions are asked, so this is for+ /// once no transaction stages any.+ pub(in crate::css::style) fn let_go_of_unnamed_selectors(&mut self) {+ let mut named: HashMap<SheetID, Vec<SheetListStart>> = HashMap::default();+ for (id, rule) in self.rules.iter().enumerate() {+ if !self.sheets[rule.sheet.0 as usize].selectors.wants_letting_go() {+ continue;+ }+ let start = self.rule_versions[id].selectors;+ if start != SheetListStart::NONE {+ named.entry(rule.sheet).or_default().push(start);+ }+ }+ for (index, sheet) in self.sheets.iter_mut().enumerate() {+ if sheet.selectors.wants_letting_go() {+ let id = SheetID(u32::try_from(index).expect("sheet identity space exhausted"));+ sheet+ .selectors+ .keep_named(named.get_mut(&id).map_or(&mut [], |named| &mut named[..]));+ }+ }}/// Replace one rule's semantic contents after the transaction carrying its previous value has@@ -910,28 +986,16 @@ impl StyleSheetProgram {/// did not change are preserved, so a consumer can tell a declaration edit from a selector edit/// by comparing components.pub fn replace_rule_version(&mut self, rule: RuleID, contents: RuleVersion) {- assert_eq!(contents.rule, rule, "a rule version must name its own rule");- let slot = self.rules[rule.0 as usize].version_slot;- let selector_changed = self.rule_versions[slot as usize].selector_program != contents.selector_program;- self.rule_versions.set(slot as usize, contents);- self.bump_rule_sheet_dispatch_version(rule);- if selector_changed {- self.bump_routing_liveness_version();- }- self.bump_version();+ self.rule_versions.set(rule.0 as usize, contents);}pub(crate) fn replace_reserved_rule_version(&mut self, rule: RuleID, contents: RuleVersion) {- assert_eq!(contents.rule, rule, "a rule version must name its own rule");- let slot = self.rules[rule.0 as usize].version_slot;- self.rule_versions.set(slot as usize, contents);- self.bump_rule_sheet_dispatch_version(rule);+ self.rule_versions.set(rule.0 as usize, contents);}pub(crate) fn set_rule_liveness(&mut self, changes: &[(RuleID, bool)]) {- let mut changed = false;for &(rule, _) in changes.iter().filter(|(_, live)| *live) {- changed |= self.set_rule_live(rule, true);+ self.set_rule_live(rule, true);}let departing: HashSet<RuleID> = changes@@ -945,19 +1009,7 @@ impl StyleSheetProgram {{continue;}- let (_, subtree_changed) = self.detach_rule_subtree(root);- changed |= subtree_changed;- }- if changed {- let sheets: HashSet<SheetID> = changes- .iter()- .map(|(rule, _)| self.rules[rule.0 as usize].sheet)- .collect();- for sheet in sheets {- self.bump_sheet_dispatch_version(sheet);- }- self.bump_routing_liveness_version();- self.bump_version();+ self.detach_rule_subtree(root);}}@@ -966,7 +1018,7 @@ impl StyleSheetProgram {return false;}let entry = &mut self.rules[rule.0 as usize];- if !entry.custom_declarations.is_empty() {+ if self.custom_declarations.contains_key(&rule) {if live {self.rules_declaring_custom_properties += 1;} else {@@ -984,20 +1036,7 @@ impl StyleSheetProgram {true}- /// Remove a rule and the subtree rooted at it. Deleting a group rule detaches its whole- /// subtree; the identities are retired together in one operation rather than one rule at a- /// time.- #[cfg(test)]- pub fn remove_rule(&mut self, rule: RuleID) -> Vec<RuleID> {- let sheet = self.rules[rule.0 as usize].sheet;- let (removed, _) = self.detach_rule_subtree(rule);- self.bump_sheet_dispatch_version(sheet);- self.bump_routing_liveness_version();- self.bump_version();- removed- }-- fn detach_rule_subtree(&mut self, rule: RuleID) -> (Vec<RuleID>, bool) {+ fn detach_rule_subtree(&mut self, rule: RuleID) -> Vec<RuleID> {let sheet = self.rules[rule.0 as usize].sheet;let parent = self.rules[rule.0 as usize].parent;let siblings = match parent {@@ -1007,22 +1046,29 @@ impl StyleSheetProgram {.expect("a parent has a child list");&mut self.rule_children[(slot.get() - 1) as usize]}- None => &mut self.sheets[sheet.0 as usize].rules,+ None => self.top_level_rules_mut(sheet),};if let Some(position) = siblings.iter().position(|sibling| *sibling == rule) {siblings.remove(position);}let removed = self.rule_subtree(rule);- let mut changed = false;for &id in &removed {- changed |= self.set_rule_live(id, false);+ self.set_rule_live(id, false);+ // A rule that left its sheet never decides again, so its selectors are let go with it+ // rather than kept alive, and their names, for nothing.+ let slot = id.0 as usize;+ if self.rule_versions[slot].selectors != SheetListStart::NONE {+ let mut version = self.rule_versions[slot].clone();+ version.selectors = SheetListStart::NONE;+ self.rule_versions.set(slot, version);+ }let order = self.rules[id.0 as usize].nested_order;- let order_axis = &mut self.sheets[sheet.0 as usize].rule_order;+ let order_axis = self.rule_order_mut(sheet);order_axis.remove(order);}- (removed, changed)+ removed}fn collect_subtree(&self, rule: RuleID, out: &mut Vec<RuleID>) {@@ -1034,6 +1080,10 @@ impl StyleSheetProgram {#[must_use]pub(crate) fn rule_subtree(&self, rule: RuleID) -> Vec<RuleID> {+ if let Some(rule) = rule.in_user_agent_rules() {+ let rules = self.user_agent_binding().store().rule_subtree(rule);+ return rules.into_iter().map(RuleID::of_user_agent).collect();+ }let mut rules = Vec::new();self.collect_subtree(rule, &mut rules);rules@@ -1041,13 +1091,17 @@ impl StyleSheetProgram {#[must_use]pub(crate) fn all_top_level_rules_in_sheet(&self, sheet: SheetID) -> &[RuleID] {- &self.sheets[sheet.0 as usize].rules+ self.sheets[sheet.0 as usize].rules.as_slice()}#[must_use]pub(crate) fn all_rules_in_sheet(&self, sheet: SheetID) -> Vec<RuleID> {+ if let Some(sheet) = self.sheets[sheet.0 as usize].user_agent {+ let rules = self.user_agent_binding().store().all_rules_in_sheet(sheet);+ return rules.into_iter().map(RuleID::of_user_agent).collect();+ }let mut rules = Vec::new();- for &top_level in &self.sheets[sheet.0 as usize].rules {+ for &top_level in self.sheets[sheet.0 as usize].rules.iter() {self.collect_subtree(top_level, &mut rules);}rules.sort_by_key(|rule| {@@ -1061,6 +1115,10 @@ impl StyleSheetProgram {/// Every live style rule of a sheet, in cascade order within that sheet.#[must_use]pub fn rules_in_sheet(&self, sheet: SheetID) -> Vec<RuleID> {+ if let Some(sheet) = self.sheets[sheet.0 as usize].user_agent {+ let rules = self.user_agent_binding().store().rules_in_sheet(sheet);+ return rules.into_iter().map(RuleID::of_user_agent).collect();+ }let top_level_rules = &self.sheets[sheet.0 as usize].rules;if top_level_rules.iter().all(|rule| self.rule_children(*rule).is_empty()) {return top_level_rules@@ -1071,7 +1129,7 @@ impl StyleSheetProgram {}let mut rules: Vec<RuleID> = Vec::new();- for &top_level in top_level_rules {+ for &top_level in top_level_rules.iter() {self.collect_live_subtree(top_level, &mut rules);}rules.sort_by_key(|rule| {@@ -1116,16 +1174,6 @@ impl StyleSheetProgram {.map_or(ranks.is_empty(), |current| current == ranks)}- /// Put the named layers of `scope` in declaration order, ahead of its implicit outer layer.- ///- /// The parser publishes qualified name identities rather than ranks. This table is the one- /// place that derives ranks, so shadow scopes can order the same spelling independently.- #[cfg(test)]- pub fn set_layer_order(&mut self, scope: TreeScopeID, layers: &[CascadeLayerID]) -> bool {- let ranks = Self::layer_ranks_in_order(layers);- self.set_layer_ranks(scope, ranks)- }-pub(crate) fn set_layer_ranks(&mut self, scope: TreeScopeID, ranks: HashMap<CascadeLayerID, u32>) -> bool {let index = scope.0 as usize;self.layer_ranks.ensure(index);@@ -1138,25 +1186,9 @@ impl StyleSheetProgram {}self.layer_ranks[index] = Some(ranks);- if initialized {- self.bump_version();- }true}- #[must_use]- pub fn layer_order_key(&self, scope: TreeScopeID) -> Vec<(CascadeLayerID, u32)> {- let mut key: Vec<_> = self- .layer_ranks- .get(scope.0 as usize)- .and_then(Option::as_ref)- .into_iter()- .flat_map(|ranks| ranks.iter().map(|(&layer, &rank)| (layer, rank)))- .collect();- key.sort_unstable_by_key(|(layer, _)| layer.0);- key- }-#[must_use]pub fn layer_order_is_initialized(&self, scope: TreeScopeID) -> bool {self.layer_ranks.get(scope.0 as usize).is_some_and(Option::is_some)@@ -1211,207 +1243,121 @@ impl StyleSheetProgram {self.rules_gated_by_container_query -= 1;}}- self.bump_rule_sheet_dispatch_version(rule);}#[must_use]pub fn rule_is_gated_by_container_query(&self, rule: RuleID) -> bool {- self.rules_gated_by_container_query != 0 && self.rules[rule.0 as usize].gated_by_container_query- }-- /// Record which longhand properties a rule declares, and which of them it marks important.- ///- /// The cascade needs this to know which properties a rule can win: only a property some added,- /// removed, modified or reprioritized rule declares is a candidate for a winner change.- pub fn set_rule_declared_properties(- &mut self,- rule: RuleID,- declared: Vec<DeclaredProperty>,- written_values: Vec<RetainedStyleValueData>,- custom_declarations: Vec<CustomDeclaration>,- custom_written_values: Vec<RetainedStyleValueData>,- ) {- debug_assert!(written_values.is_empty() || written_values.len() == declared.len());- debug_assert!(custom_written_values.is_empty() || custom_written_values.len() == custom_declarations.len());- if self.rules[rule.0 as usize].semantic_declaration != SemanticDeclarationID::default() {- self.invalidate_semantic_declarations();+ self.rules_gated_by_container_query != 0 && self.record(rule).gated_by_container_query+ }++ /// Record the declarations a rule declares.+ pub(in crate::css::style) fn set_rule_declarations(&mut self, rule: RuleID, declarations: RuleDeclarations) {+ let RuleDeclarations {+ block,+ custom_declarations,+ } = declarations;+ let live = self.rules[rule.0 as usize].live;+ self.rules[rule.0 as usize].declarations = block;+ let declared_custom_properties_before = live && self.custom_declarations.contains_key(&rule);+ if custom_declarations.is_empty() {+ self.custom_declarations.remove(&rule);+ } else {+ self.custom_declarations.insert(rule, custom_declarations);}- let entry = &mut self.rules[rule.0 as usize];- let declared_custom_properties_before = entry.live && !entry.custom_declarations.is_empty();- let written_value_checks = declared- .iter()- .zip(&written_values)- .map(|(declared, value)| super::publication::WrittenValueChecks::prepare(declared.property, value))- .collect();- let may_affect_layout_geometry = !custom_declarations.is_empty()- || declared- .iter()- .any(|declared| crate::css::property_metadata::property_may_affect_layout_geometry(declared.property));- let moves_layout_geometry = entry.declarations.data.may_affect_layout_geometry != may_affect_layout_geometry;- entry.declarations = share_rule_declarations(- RuleDeclarationData {- declared_properties: declared,- written_values,- written_value_checks,- may_affect_layout_geometry,- custom_declarations,- custom_written_values,- },- &mut rule_declaration_pool(),- );match (declared_custom_properties_before,- entry.live && !entry.custom_declarations.is_empty(),+ live && self.custom_declarations.contains_key(&rule),) {(false, true) => self.rules_declaring_custom_properties += 1,(true, false) => self.rules_declaring_custom_properties -= 1,_ => {}}- // The routing liveness view carries which live routes' rules may move layout geometry. A rule that cannot- // decide has no live routes, and moves the routing liveness when it comes to.- if moves_layout_geometry && self.rule_can_decide(rule) {- self.bump_routing_liveness_version();- }- self.bump_rule_sheet_dispatch_version(rule);}- fn invalidate_semantic_declarations(&mut self) {- if self.semantic_declarations.is_empty() {- return;- }- self.semantic_declarations.clear();-- for index in 0..self.rules.len() {- if self.rules[index].semantic_declaration != SemanticDeclarationID::default() {- self.rules[index].semantic_declaration = SemanticDeclarationID::default();- }+ /// What a rule declares.+ #[must_use]+ pub(in crate::css::style) fn rule_declarations_of(&self, rule: RuleID) -> RuleDeclarations {+ RuleDeclarations {+ block: self.record(rule).declarations.clone(),+ custom_declarations: self.custom_declarations_of(rule).into(),}}- /// Lazily name equal complete declaration inventories alike. Keeping representatives only for- /// rules that cross the FFI boundary avoids charging ordinary stylesheet parsing for a C++- /// style-sharing optimization. IDs are never reused, so invalidation cannot alias a cached ID.- pub(super) fn ensure_semantic_declaration(&mut self, rule: RuleID) -> SemanticDeclarationID {- let rule_index = rule.0 as usize;- if self.rules[rule_index].semantic_declaration != SemanticDeclarationID::default() {- return self.rules[rule_index].semantic_declaration;- }- // Image value identities omit the declaration's resource context. Keep the native- // declaration identity in sharing keys for these blocks instead of merging them.- if self.rules[rule_index].written_values.iter().any(|value| {- crate::css::style_compute::value_is_computationally_independent(value.data()).is_none()- || crate::css::style_compute::external_value_dependencies(value.data())- .may_need_style_sheet_resource_context- }) {- return SemanticDeclarationID::default();- }- let hash = super::intern_table::content_hash(&self.rules[rule.0 as usize].declared_properties);-- let bucket = self.semantic_declarations.entry(hash).or_default();- let existing = bucket.iter().find_map(|entry| {- let representative = entry.representative;- (self.rules[representative.0 as usize].declared_properties == self.rules[rule_index].declared_properties)- .then_some(entry.id)- });- let id = match existing {- Some(id) => id,- None => {- let id = SemanticDeclarationID(self.next_semantic_declaration_id);- self.next_semantic_declaration_id = self- .next_semantic_declaration_id- .checked_add(1)- .expect("semantic declaration identity space exhausted");- bucket.push(SemanticDeclarationEntry {- id,- representative: rule,- });- id- }- };-- let entry = &mut self.rules[rule.0 as usize];- entry.semantic_declaration = id;- id+ fn block_of(&self, rule: RuleID) -> Option<&SharedDeclarationBlock> {+ self.record(rule).declarations.as_ref()}+ /// The longhands a rule declares, in declaration order.#[must_use]- pub fn declared_properties_of(&self, rule: RuleID) -> &[DeclaredProperty] {- &self.rules[rule.0 as usize].declared_properties+ pub fn declared_properties_of(&self, rule: RuleID) -> &[DeclarationEntry] {+ self.block_of(rule).map_or(&[], |block| block.properties().entries())}/// The custom properties a rule declares, in declaration order.#[must_use]pub fn custom_declarations_of(&self, rule: RuleID) -> &[CustomDeclaration] {- &self.rules[rule.0 as usize].custom_declarations+ if let Some(rule) = rule.in_user_agent_rules() {+ return self.user_agent_binding().store().custom_declarations_of(rule);+ }+ self.custom_declarations+ .get(&rule)+ .map_or(&[], |declarations| declarations)}/// Whether any rule declares a custom property.#[must_use]pub fn any_rule_declares_custom_properties(&self) -> bool {self.rules_declaring_custom_properties != 0+ || self+ .user_agent+ .as_ref()+ .is_some_and(|binding| binding.store().rules_declaring_custom_properties != 0)}/// The values a rule's custom declarations were written with, parallel to them, or nothing/// when the rule arrived without them.#[must_use]pub fn custom_written_values_of(&self, rule: RuleID) -> &[RetainedStyleValueData] {- &self.rules[rule.0 as usize].custom_written_values+ self.block_of(rule).map_or(&[], |block| {+ RetainedStyleValueData::slice_from_shared(block.custom_properties().values())+ })}#[must_use]pub fn written_values_of(&self, rule: RuleID) -> &[RetainedStyleValueData] {- &self.rules[rule.0 as usize].written_values+ self.block_of(rule).map_or(&[], |block| {+ RetainedStyleValueData::slice_from_shared(block.properties().values())+ })}- /// The value the rule's winning declaration for one property was written with: the last of- /// its declarations naming that property, importance and identity. `None` when the rule- /// arrived without its written values.- #[must_use]- pub fn written_winner_value(- &self,- rule: RuleID,- property: u16,- important: bool,- value: SpecifiedValueID,- ) -> Option<&RetainedStyleValueData> {- self.written_winner_declaration(rule, property, important, value)- .map(|(_, value)| value)+ fn cascade_data_of(&self, rule: RuleID) -> Option<&BlockCascadeData> {+ self.block_of(rule).map(|block| {+ block+ .cascade_data()+ .expect("a rule's published block holds its cascade data")+ })}/// Whether a match of this rule may move geometry.- pub(super) fn rule_may_affect_layout_geometry(&self, rule: RuleID) -> bool {- self.rules[rule.0 as usize].may_affect_layout_geometry- }-- pub(super) fn written_value_checks(&self, rule: RuleID, index: usize) -> super::publication::WrittenValueChecks {- self.rules[rule.0 as usize].declarations.data.written_value_checks[index]+ pub(in crate::css::style) fn rule_may_affect_layout_geometry(&self, rule: RuleID) -> bool {+ self.cascade_data_of(rule)+ .is_some_and(|data| data.may_affect_layout_geometry)}- /// The winning declaration's position in its rule and the value it was written with. The- /// position orders declarations the cascade ranks equally, such as a logical property and its- /// physical associate in one rule.- pub fn written_winner_declaration(+ pub(in crate::css::style) fn written_value_checks(&self,rule: RuleID,- property: u16,- important: bool,- value: SpecifiedValueID,- ) -> Option<(usize, &RetainedStyleValueData)> {- let entry = &self.rules[rule.0 as usize];- if entry.written_values.len() != entry.declared_properties.len() {- return None;- }- let index = entry.declared_properties.iter().rposition(|declared| {- declared.property == property && declared.important == important && declared.value == value- })?;- Some((index, &entry.written_values[index]))+ index: usize,+ ) -> super::pipeline::compute::WrittenValueChecks {+ self.cascade_data_of(rule)+ .expect("a rule declaring a property holds its block")+ .checks()[index]}- #[must_use]/// Whether the rule's declarations are all in the winner columns. A rule declaring custom/// properties is not: they never reach the columns.pub fn declarations_are_complete_for(&self, rule: RuleID) -> bool {- self.rules[rule.0 as usize].custom_declarations.is_empty()+ self.custom_declarations_of(rule).is_empty()}/// Record that a tree scope's rules include the document's author sheets as well as its own,@@ -1425,24 +1371,6 @@ impl StyleSheetProgram {self.scopes_using_document_sheets.contains(tree_scope.0 as usize)}- #[must_use]- pub fn sheet_rules_apply_in_scope(&self, sheet: SheetID, tree_scope: TreeScopeID) -> bool {- self.sheet_is_attached_in_scope(sheet, tree_scope)- || (tree_scope != TreeScopeID::DOCUMENT- && self.sheet_is_attached_in_scope(sheet, TreeScopeID::DOCUMENT)- && (matches!(self.sheet_origin(sheet), CascadeOrigin::UserAgent | CascadeOrigin::User)- || self.scope_uses_document_sheets(tree_scope)))- }-- fn sheet_is_attached_in_scope(&self, sheet: SheetID, tree_scope: TreeScopeID) -> bool {- let attachments = self.sheet_attachments(sheet);- let sheets = self.sheets_in_scope(tree_scope);- match attachments.len() <= sheets.len() {- true => attachments.iter().any(|attachment| attachment.tree_scope == tree_scope),- false => sheets.contains(&sheet),- }- }-/// The attachment of a sheet in one tree scope, if it is attached there.#[must_use]pub fn attachment_in_scope(&self, sheet: SheetID, tree_scope: TreeScopeID) -> Option<Attachment> {@@ -1463,9 +1391,19 @@ impl StyleSheetProgram {.rank(attachment.order)}+ /// How many times the rule order of a sheet was relabeled, which moves the ranks of its rules+ /// without moving their order.+ #[must_use]+ pub(in crate::css::style) fn rule_order_relabels(&self, sheet: SheetID) -> u64 {+ self.sheets[sheet.0 as usize].rule_order.relabels()+ }+/// The comparable rank of a rule within its sheet.#[must_use]pub fn rule_rank(&self, rule: RuleID) -> u64 {+ if let Some(rule) = rule.in_user_agent_rules() {+ return self.user_agent_binding().store().rule_rank(rule);+ }let sheet = self.rules[rule.0 as usize].sheet;self.sheets[sheet.0 as usize].rule_order@@ -1474,63 +1412,198 @@ impl StyleSheetProgram {// -- Accounting --------------------------------------------------------------------------- pub(super) fn share_rule_storage(&mut self) {- self.rule_versions.share();- self.rules.share();+ pub(in crate::css::style) fn share_rule_storage(&mut self, process_indexes: Option<&super::ProcessRuleIndexes>) {+ if let Some(process_indexes) = process_indexes {+ self.rule_versions.share(&process_indexes.rule_version_pages);+ self.rules.share(&process_indexes.rule_record_pages);+ self.native.targets.share(&process_indexes.target_pages);+ for sheet in self.sheets.iter_mut().filter(|sheet| !sheet.rules_shared) {+ process_indexes.share_sheet_rules(&mut sheet.rules, &mut sheet.rule_order);+ sheet.rules_shared = true;+ }+ }}- fn allocate_rule_version(&mut self, contents: RuleVersion) -> u32 {- let slot = u32::try_from(self.rule_versions.len()).expect("rule version space exhausted");-- self.rule_versions.push(contents);+ /// The top-level rules of `sheet`, to edit, which no other document's sheet holds then.+ fn top_level_rules_mut(&mut self, sheet: SheetID) -> &mut Vec<RuleID> {+ let sheet = &mut self.sheets[sheet.0 as usize];+ sheet.rules_shared = false;+ Arc::make_mut(&mut sheet.rules)+ }- slot+ /// The rule order of `sheet`, to edit, which no other document's sheet holds then.+ fn rule_order_mut(&mut self, sheet: SheetID) -> &mut OrderMaintenance {+ let sheet = &mut self.sheets[sheet.0 as usize];+ sheet.rules_shared = false;+ Arc::make_mut(&mut sheet.rule_order)}}-impl Default for StyleSheetProgram {+impl Default for RuleStore {fn default() -> Self {Self::new()}}+#[cfg(test)]+impl RuleStore {+ /// Attach a sheet to a style scope at the end of that scope's sheet order.+ pub fn attach_sheet(&mut self, sheet: SheetID, tree_scope: TreeScopeID) -> Attachment {+ let order_axis = self.sheet_order_mut(tree_scope);++ let order = order_axis.insert_last();++ let attachment = Attachment { tree_scope, order };+ let attachments = &mut self.sheets[sheet.0 as usize].attachments;+ attachments.push(attachment);++ let scope_index = tree_scope.0 as usize;+ self.sheets_by_scope.ensure(scope_index);+ self.sheets_by_scope[scope_index].push(sheet);+ attachment+ }++ /// Attach a sheet immediately before another sheet's attachment in the same scope. Loading+ /// order does not determine cascade order: a linked or imported sheet receives its position+ /// from document and rule order before or while it loads, and attachment reuses that position.+ pub fn attach_sheet_before(&mut self, sheet: SheetID, before: Attachment) -> Attachment {+ let order_axis = self.sheet_order_mut(before.tree_scope);++ let order = order_axis.insert_before(before.order);++ let attachment = Attachment {+ tree_scope: before.tree_scope,+ order,+ };+ let attachments = &mut self.sheets[sheet.0 as usize].attachments;+ attachments.push(attachment);++ let scope_index = before.tree_scope.0 as usize;+ self.sheets_by_scope.ensure(scope_index);+ let position = self.sheets_by_scope[scope_index]+ .iter()+ .position(|&candidate| {+ self.attachment_in_scope(candidate, before.tree_scope)+ .is_some_and(|attachment| attachment.order == before.order)+ })+ .expect("an insertion target must remain attached");+ self.sheets_by_scope[scope_index].insert(position, sheet);+ attachment+ }++ pub fn detach_sheet(&mut self, sheet: SheetID, tree_scope: TreeScopeID) {+ let attachments = &mut self.sheets[sheet.0 as usize].attachments;+ let Some(position) = attachments+ .iter()+ .position(|attachment| attachment.tree_scope == tree_scope)+ else {+ return;+ };+ let attachment = attachments.remove(position);+ if let Some(order) = self.sheet_order.get_mut(tree_scope.0 as usize).and_then(Option::as_mut) {+ order.remove(attachment.order);+ }+ if let Some(sheets) = self.sheets_by_scope.get_mut(tree_scope.0 as usize)+ && let Some(position) = sheets.iter().position(|&candidate| candidate == sheet)+ {+ sheets.remove(position);+ }+ }++ /// Move a sheet within its scope. Only the sheet's own order token is written; the program+ /// nodes of its rules are untouched, because they reference the sheet rather than copying its+ /// position.+ pub fn move_sheet_before(&mut self, sheet: SheetID, before: Attachment) {+ let tree_scope = before.tree_scope;+ self.detach_sheet(sheet, tree_scope);+ self.attach_sheet_before(sheet, before);+ }++ pub fn sheet_is_enabled(&self, sheet: SheetID) -> bool {+ self.sheets[sheet.0 as usize].enabled+ }++ /// Append a rule to a sheet or to a grouping rule.+ pub fn append_rule(&mut self, sheet: SheetID, parent: Option<RuleID>, kind: RuleKind) -> RuleID {+ let order_axis = self.rule_order_mut(sheet);++ let order = order_axis.insert_last();++ self.create_rule(sheet, parent, kind, order, None, true)+ }++ /// Insert a rule immediately before an existing sibling. Existing rules are neither renumbered+ /// nor rematched: the new rule takes an order token between its neighbors.+ pub fn insert_rule_before(&mut self, before: RuleID, kind: RuleKind) -> RuleID {+ let sheet = self.rules[before.0 as usize].sheet;+ let parent = self.rules[before.0 as usize].parent;+ let sibling_order = self.rules[before.0 as usize].nested_order;+ let order_axis = self.rule_order_mut(sheet);++ let order = order_axis.insert_before(sibling_order);++ self.create_rule(sheet, parent, kind, order, Some(before), true)+ }++ /// How many rules the store itself holds.+ pub(in crate::css::style) fn rule_count(&self) -> usize {+ self.rules.len()+ }++ /// Remove a rule and the subtree rooted at it. Deleting a group rule detaches its whole+ /// subtree; the identities are retired together in one operation rather than one rule at a+ /// time.+ pub fn remove_rule(&mut self, rule: RuleID) -> Vec<RuleID> {+ let removed = self.detach_rule_subtree(rule);+ removed+ }++ /// Put the named layers of `scope` in declaration order, ahead of its implicit outer layer.+ ///+ /// The parser publishes qualified name identities rather than ranks. This table is the one+ /// place that derives ranks, so shadow scopes can order the same spelling independently.+ pub fn set_layer_order(&mut self, scope: TreeScopeID, layers: &[CascadeLayerID]) -> bool {+ let ranks = Self::layer_ranks_in_order(layers);+ self.set_layer_ranks(scope, ranks)+ }+}+#[cfg(test)]mod tests {use super::*;+ use crate::css::style::cascade::CascadeOperator;++ /// The selectors `text` writes.+ fn list(text: &str) -> crate::css::selector::SelectorListRef {+ let parsed = crate::css::selector_parser::parse_selector_list(+ &text.encode_utf16().collect::<Vec<u16>>()[..],+ &[],+ crate::css::selector_parser::SelectorType::Standalone,+ crate::css::selector_parser::SelectorParsingMode::Standard,+ )+ .expect("a test writes valid selectors");+ crate::css::selector::SelectorListRef::pack(&parsed.selectors)+ }#[test]- fn shared_declarations_compare_authored_values_and_isolate_edits() {+ fn rules_read_the_written_values_of_their_blocks() {let (mut first, first_sheet) = program_with_sheet();let (mut second, second_sheet) = program_with_sheet();let first_rule = first.append_rule(first_sheet, None, RuleKind::Style);let second_rule = second.append_rule(second_sheet, None, RuleKind::Style);- let set = |program: &mut StyleSheetProgram, rule, keyword| {- program.set_rule_declared_properties(- rule,- vec![DeclaredProperty {- property: 1,- important: false,- operator: CascadeOperator::Initial,- value: SpecifiedValueID(1),- }],- vec![RetainedStyleValueData::from_owned(- crate::css::style_value::StyleValueData::Keyword { keyword },- )],- Vec::new(),- Vec::new(),- );+ let block = |keyword| {+ crate::css::style::pipeline::test_support::declaration_block(&[(+ crate::css::property_metadata::property_id::COLOR,+ false,+ crate::css::style_value::StyleValueData::Keyword { keyword },+ )])};- set(&mut first, first_rule, 1);- set(&mut second, second_rule, 1);- assert!(Arc::ptr_eq(- &first.rules[first_rule.0 as usize].declarations,- &second.rules[second_rule.0 as usize].declarations- ));- set(&mut second, second_rule, 2);- assert!(!Arc::ptr_eq(- &first.rules[first_rule.0 as usize].declarations,- &second.rules[second_rule.0 as usize].declarations- ));+ let shared = block(1);+ first.set_rule_declarations(first_rule, RuleDeclarations::of_block(shared.clone(), &[]).0);+ second.set_rule_declarations(second_rule, RuleDeclarations::of_block(shared, &[]).0);+ assert!(first.rule_declarations_of(first_rule) == second.rule_declarations_of(second_rule));+ second.set_rule_declarations(second_rule, RuleDeclarations::of_block(block(2), &[]).0);+ assert!(first.rule_declarations_of(first_rule) != second.rule_declarations_of(second_rule));assert!(matches!(first.written_values_of(first_rule)[0].data(),crate::css::style_value::StyleValueData::Keyword { keyword: 1 }@@ -1542,9 +1615,9 @@ mod tests {));}- fn program_with_sheet() -> (StyleSheetProgram, SheetID) {- let mut program = StyleSheetProgram::new();- let sheet = program.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);+ fn program_with_sheet() -> (RuleStore, SheetID) {+ let mut program = RuleStore::new();+ let sheet = program.add_sheet(CascadeOrigin::Author);program.attach_sheet(sheet, TreeScopeID::DOCUMENT);(program, sheet)}@@ -1554,141 +1627,103 @@ mod tests {let (mut program, sheet) = program_with_sheet();let group = program.append_rule(sheet, None, RuleKind::Media);let rule = program.append_rule(sheet, Some(group), RuleKind::Style);- let declarations = || {- vec![CustomDeclaration {- name: StyleAtomID(1),- important: false,- operator: CascadeOperator::Initial,- value: SpecifiedValueID(1),- }]+ let declarations = || RuleDeclarations {+ block: None,+ custom_declarations: Box::new([CustomDeclaration::new(StyleAtomID(1), false, CascadeOperator::Initial)]),};- program.set_rule_declared_properties(rule, vec![], vec![], declarations(), vec![]);+ program.set_rule_declarations(rule, declarations());assert!(program.any_rule_declares_custom_properties());program.remove_rule(group);assert!(!program.any_rule_declares_custom_properties());let reserved = program.reserve_rule(sheet, None, RuleKind::Style);- program.set_rule_declared_properties(reserved, vec![], vec![], declarations(), vec![]);+ program.set_rule_declarations(reserved, declarations());assert!(!program.any_rule_declares_custom_properties());program.set_rule_liveness(&[(reserved, true), (reserved, true)]);assert!(program.any_rule_declares_custom_properties());program.set_rule_liveness(&[(reserved, false)]);assert!(!program.any_rule_declares_custom_properties());- program.set_rule_declared_properties(reserved, vec![], vec![], vec![], vec![]);+ program.set_rule_declarations(reserved, RuleDeclarations::default());assert!(!program.any_rule_declares_custom_properties());}#[test]- fn a_declaration_edit_keeps_the_rule_and_its_selector_program() {+ fn a_declaration_edit_keeps_the_rule_and_its_selectors() {let (mut program, sheet) = program_with_sheet();let rule = program.append_rule(sheet, None, RuleKind::Style);- let mut contents = program.rule_version(rule);- contents.selector_program = Some(SelectorProgramID(9));- contents.declaration_block = Some(DeclarationBlockID(1));- program.replace_rule_version(rule, contents);- let first = program.rule_version(rule);+ let mut contents = program.rule_version(rule).clone();+ contents.selectors = program.start_of_selectors(sheet, &list(".c"));+ contents.declaration_block = Some(DeclarationBlockID::new(1));+ program.replace_rule_version(rule, contents.clone());+ let first = program.rule_version(rule).clone();- contents.declaration_block = Some(DeclarationBlockID(2));+ contents.declaration_block = Some(DeclarationBlockID::new(2));program.replace_rule_version(rule, contents);- let second = program.rule_version(rule);+ let second = program.rule_version(rule).clone();assert_ne!(first, second, "a declaration edit creates a new rule version");- assert_eq!(- first.selector_program, second.selector_program,- "and leaves the selector program identity alone"- );- assert_eq!(program.rule_version(rule), second);+ assert_eq!(first.selectors, second.selectors, "and leaves the selectors alone");+ assert_eq!(*program.rule_version(rule), second);}#[test]- fn a_selector_edit_changes_only_the_selector_program() {+ fn a_selector_edit_changes_only_the_selectors() {let (mut program, sheet) = program_with_sheet();let rule = program.append_rule(sheet, None, RuleKind::Style);- let mut contents = program.rule_version(rule);- contents.selector_program = Some(SelectorProgramID(1));- contents.declaration_block = Some(DeclarationBlockID(5));- program.replace_rule_version(rule, contents);+ let mut contents = program.rule_version(rule).clone();+ contents.selectors = program.start_of_selectors(sheet, &list(".c"));+ contents.declaration_block = Some(DeclarationBlockID::new(5));+ program.replace_rule_version(rule, contents.clone());- contents.selector_program = Some(SelectorProgramID(2));+ contents.selectors = program.start_of_selectors(sheet, &list(".c"));program.replace_rule_version(rule, contents);assert_eq!(program.rule_version(rule).declaration_block,- Some(DeclarationBlockID(5))+ Some(DeclarationBlockID::new(5)));}#[test]- fn routing_liveness_ignores_declarations_but_tracks_selector_and_activation_changes() {+ fn repeated_rule_version_replacement_keeps_storage_flat() {let (mut program, sheet) = program_with_sheet();let rule = program.append_rule(sheet, None, RuleKind::Style);- let mut contents = program.rule_version(rule);- contents.selector_program = Some(SelectorProgramID(1));- program.replace_rule_version(rule, contents);- let selector_version = program.routing_liveness_version();-- contents.declaration_block = Some(DeclarationBlockID(1));- program.replace_rule_version(rule, contents);- assert_eq!(program.routing_liveness_version(), selector_version);-- contents.selector_program = Some(SelectorProgramID(2));- program.replace_rule_version(rule, contents);- let replacement_version = program.routing_liveness_version();- assert!(replacement_version > selector_version);-- assert!(program.set_rule_conditions_hold(rule, false));- assert!(program.routing_liveness_version() > replacement_version);- }-- #[test]- fn equal_declarations_share_a_collision_checked_identity() {- let (mut program, sheet) = program_with_sheet();- let first = program.append_rule(sheet, None, RuleKind::Style);- let second = program.append_rule(sheet, None, RuleKind::Style);- let third = program.append_rule(sheet, None, RuleKind::Style);- let never_interned = program.append_rule(sheet, None, RuleKind::Style);- let declared = |value| DeclaredProperty {- property: 1,- important: false,- operator: CascadeOperator::Declared,- value: SpecifiedValueID(value),- };- program.set_rule_declared_properties(first, vec![declared(10)], Vec::new(), Vec::new(), Vec::new());- program.set_rule_declared_properties(second, vec![declared(10)], Vec::new(), Vec::new(), Vec::new());- program.set_rule_declared_properties(third, vec![declared(20)], Vec::new(), Vec::new(), Vec::new());-- let first_identity = program.ensure_semantic_declaration(first);- let second_identity = program.ensure_semantic_declaration(second);- let third_identity = program.ensure_semantic_declaration(third);- assert_ne!(first_identity, SemanticDeclarationID::default());- assert_eq!(first_identity, second_identity);- assert_ne!(first_identity, third_identity);-- program.set_rule_declared_properties(never_interned, vec![declared(30)], Vec::new(), Vec::new(), Vec::new());- assert_eq!(program.ensure_semantic_declaration(first), first_identity);-- program.set_rule_declared_properties(second, vec![declared(20)], Vec::new(), Vec::new(), Vec::new());- assert_eq!(- program.ensure_semantic_declaration(second),- program.ensure_semantic_declaration(third)- );- assert_ne!(program.ensure_semantic_declaration(first), first_identity);+ let selector_lists = [list(".a"), list(".b")];+ for index in 0..128_u32 {+ let mut contents = program.rule_version(rule).clone();+ contents.selectors = program.start_of_selectors(sheet, &selector_lists[index as usize % 2]);+ contents.declaration_block = Some(DeclarationBlockID::new(index % 2 + 1));+ program.replace_rule_version(rule, contents);+ }}#[test]- fn repeated_rule_version_replacement_keeps_program_storage_flat() {+ fn a_sheet_lets_go_of_the_selector_arenas_no_rule_names() {let (mut program, sheet) = program_with_sheet();let rule = program.append_rule(sheet, None, RuleKind::Style);-- for index in 0..128_u32 {- let mut contents = program.rule_version(rule);- contents.selector_program = Some(SelectorProgramID(index % 2));- contents.declaration_block = Some(DeclarationBlockID(index % 2));+ let lists: Vec<_> = (0..16).map(|index| list(&format!(".c{index}"))).collect();+ let mut starts = Vec::new();+ for selectors in &lists {+ let mut contents = program.rule_version(rule).clone();+ contents.selectors = program.start_of_selectors(sheet, selectors);+ starts.push(contents.selectors);program.replace_rule_version(rule, contents);}+ starts.dedup();+ assert_eq!(+ starts.len(),+ lists.len(),+ "each arena the sheet takes starts its lists anew"+ );+ assert!(program.wants_letting_go_of_selectors());+ program.let_go_of_unnamed_selectors();+ assert!(!program.wants_letting_go_of_selectors());+ assert_eq!(program.sheets[sheet.0 as usize].selectors.arenas.len(), 1);+ let selectors = program.rule_selectors(rule).expect("the rule keeps its selectors");+ assert!(selectors.view().identity() == lists.last().unwrap().view().identity());}#[test]@@ -1696,14 +1731,14 @@ mod tests {let (mut program, sheet) = program_with_sheet();let first = program.append_rule(sheet, None, RuleKind::Style);let last = program.append_rule(sheet, None, RuleKind::Style);- let first_version = program.rule_version(first);- let last_version = program.rule_version(last);+ let first_version = program.rule_version(first).clone();+ let last_version = program.rule_version(last).clone();let middle = program.insert_rule_before(last, RuleKind::Style);assert_eq!(program.rules_in_sheet(sheet), vec![first, middle, last]);- assert_eq!(program.rule_version(first), first_version);- assert_eq!(program.rule_version(last), last_version);+ assert_eq!(*program.rule_version(first), first_version);+ assert_eq!(*program.rule_version(last), last_version);}#[test]@@ -1726,77 +1761,40 @@ mod tests {#[test]fn moving_a_sheet_writes_one_token_and_leaves_its_rules_alone() {- let mut program = StyleSheetProgram::new();- let first = program.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- let second = program.add_sheet(StyleSheetObjectID(2), CascadeOrigin::Author);+ let mut program = RuleStore::new();+ let first = program.add_sheet(CascadeOrigin::Author);+ let second = program.add_sheet(CascadeOrigin::Author);program.attach_sheet(first, TreeScopeID::DOCUMENT);let second_attachment = program.attach_sheet(second, TreeScopeID::DOCUMENT);let rule = program.append_rule(first, None, RuleKind::Style);- let version = program.rule_version(rule);+ let version = program.rule_version(rule).clone();assert_eq!(program.sheets_in_scope(TreeScopeID::DOCUMENT), vec![first, second]);program.move_sheet_before(first, second_attachment);assert_eq!(program.sheets_in_scope(TreeScopeID::DOCUMENT), vec![first, second]);- assert_eq!(program.rule_version(rule), version, "rules reference the sheet's token");- }-- #[test]- fn replacing_scope_sheets_tracks_global_attachment_liveness() {- let mut program = StyleSheetProgram::new();- let first = program.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- let second = program.add_sheet(StyleSheetObjectID(2), CascadeOrigin::Author);- program.append_rule(first, None, RuleKind::Style);- program.append_rule(second, None, RuleKind::Style);- let unattached_version = program.routing_liveness_version();-- program.set_sheets_in_scope(TreeScopeID::DOCUMENT, vec![first, second]);- let attached_version = program.routing_liveness_version();- assert!(attached_version > unattached_version);-- program.set_sheets_in_scope(TreeScopeID::DOCUMENT, vec![second, first]);- assert_eq!(program.routing_liveness_version(), attached_version);-- program.set_sheets_in_scope(TreeScopeID::DOCUMENT, Vec::new());- assert!(program.routing_liveness_version() > attached_version);- }-- #[test]- fn one_program_attaches_to_several_scopes() {- let mut program = StyleSheetProgram::new();- let sheet = program.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- program.attach_sheet(sheet, TreeScopeID::DOCUMENT);- program.attach_sheet(sheet, TreeScopeID(1));- let rule = program.append_rule(sheet, None, RuleKind::Style);-- assert_eq!(program.sheet_attachments(sheet).len(), 2);- assert_eq!(program.sheets_in_scope(TreeScopeID(1)), vec![sheet]);assert_eq!(- program.rules_in_sheet(sheet),- vec![rule],- "the rules are not duplicated"+ *program.rule_version(rule),+ version,+ "rules reference the sheet's token");-- program.detach_sheet(sheet, TreeScopeID(1));- assert!(program.sheets_in_scope(TreeScopeID(1)).is_empty());- assert_eq!(program.sheets_in_scope(TreeScopeID::DOCUMENT), vec![sheet]);}#[test]fn disabling_a_sheet_keeps_its_program_and_position() {let (mut program, sheet) = program_with_sheet();let rule = program.append_rule(sheet, None, RuleKind::Style);- let version = program.rule_version(rule);+ let version = program.rule_version(rule).clone();program.set_sheet_enabled(sheet, false);assert!(!program.sheet_is_enabled(sheet));assert_eq!(program.sheets_in_scope(TreeScopeID::DOCUMENT), vec![sheet]);- assert_eq!(program.rule_version(rule), version);+ assert_eq!(*program.rule_version(rule), version);}#[test]fn layer_topology_changes_ranks_without_touching_rules() {- let mut program = StyleSheetProgram::new();+ let mut program = RuleStore::new();let base = CascadeLayerID(1);let theme = CascadeLayerID(2);let shadow = TreeScopeID(1);@@ -1855,16 +1853,4 @@ mod tests {program.set_rule_gated_by_container_query(child, false);assert_eq!(program.rules_gated_by_container_query, 0);}-- #[test]- fn every_structural_edit_advances_the_program_version() {- let (mut program, sheet) = program_with_sheet();- let before = program.version();- let rule = program.append_rule(sheet, None, RuleKind::Style);- assert!(program.version() > before);-- let before = program.version();- program.remove_rule(rule);- assert!(program.version() > before);- }}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/identities.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/identities.rsnew file mode 100644index 00000000000..6d749d9abea--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/identities.rs@@ -0,0 +1,222 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The identities of the stylesheet program's sheets and rules, and what each rule version says.++pub use crate::css::cascaded_properties::CascadeOrigin;++use crate::css::declaration_block::DeclarationEntry;+use crate::css::style::cascade::CascadeOperator;+use crate::css::style::index::StyleAtomID;+use std::hash::{Hash, Hasher};++define_id! {+ /// Semantic identity of a sheet, stable across edits to its contents.+ pub struct SheetID(pub);+}+define_id! {+ /// Semantic identity of a rule, stable across edits to its declarations or selector.+ pub struct RuleID(pub);+}++impl RuleID {+ /// The bit telling a rule of the process's user agent rules from a rule of the document.+ const USER_AGENT: u32 = 1 << 31;++ /// The rule of the document that `rule`, a rule of the process's user agent rules, is to it.+ pub(in crate::css::style) fn of_user_agent(rule: RuleID) -> Self {+ assert!(rule.0 < Self::USER_AGENT, "user agent rule space exhausted");+ Self(rule.0 | Self::USER_AGENT)+ }++ /// The rule of the process's user agent rules this one is, if it is one.+ #[inline]+ pub(in crate::css::style) fn in_user_agent_rules(self) -> Option<RuleID> {+ (self.0 & Self::USER_AGENT != 0).then_some(Self(self.0 & !Self::USER_AGENT))+ }+}++/// One custom property a declaration block declares. The cascade tracks no winner per custom+/// property name: an element's custom-property environment cascades these by name when it is+/// computed, so a block carries them beside its longhand declarations.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub struct CustomDeclaration {+ pub name: StyleAtomID,+ pub(crate) entry: DeclarationEntry,+}++const _: () = assert!(size_of::<CustomDeclaration>() == 8);++impl CustomDeclaration {+ pub(crate) fn new(name: StyleAtomID, important: bool, operator: CascadeOperator) -> Self {+ Self {+ name,+ entry: DeclarationEntry::new(crate::css::property_metadata::property_id::CUSTOM, important, operator),+ }+ }++ pub(crate) fn important(self) -> bool {+ self.entry.important()+ }++ pub(crate) fn operator(self) -> CascadeOperator {+ self.entry.operator()+ }+}++/// Immutable identity of a declaration block, whether it came from a rule or a style node. No+/// block's is zero, so an absent block costs nothing next to one.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]+pub struct DeclarationBlockID(std::num::NonZeroU32);++impl DeclarationBlockID {+ /// The identity numbered `raw`, which is not zero.+ #[must_use]+ pub fn new(raw: u32) -> Self {+ Self(std::num::NonZeroU32::new(raw).expect("a declaration block identity is not zero"))+ }++ #[must_use]+ pub fn raw(self) -> u32 {+ self.0.get()+ }+}++/// Where the selector list of a rule starts among the selectors of its sheet, which the sheet's+/// rule store resolves, or [`Self::NONE`].+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub struct SheetListStart(pub(super) u32);++impl SheetListStart {+ /// No list: the rule has no selectors, or an empty list.+ pub const NONE: Self = Self(u32::MAX);+}++define_id! {+ /// Identity of a cascade layer: the interned qualified layer name. Rules reference the identity+ /// rather than a copied numeric rank, so each tree scope can order the same name independently+ /// and a layer topology change does not rewrite every declaration that lives in it.+ pub struct CascadeLayerID(pub);+}++impl CascadeLayerID {+ /// The implicit outer layer that unlayered rules belong to.+ pub const UNLAYERED: Self = Self(0);+}++define_id! {+ /// Identity of an `@scope` scope. Distinct from a tree scope: one is a CSS construct, the other+ /// is a DOM one.+ pub struct StyleScopeID(pub);+}++impl StyleScopeID {+ /// Not inside any `@scope`.+ pub const NONE: Self = Self(0);+}++/// What kind of rule a program node is. The kinds exist so that a program delta can be routed to+/// the consumers that care: editing a keyframes rule begins at animations referencing its name,+/// not at every element in the scope.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub enum RuleKind {+ Style,+ #[cfg(test)]+ Media,+ CounterStyle,+ FontFeatureValues,+ Keyframes,+ Property,+ Function,+}++impl RuleKind {+ /// Whether the rule contributes declarations through selector matching.+ #[must_use]+ pub fn matches_elements(self) -> bool {+ self == Self::Style+ }+}++/// The immutable semantic contents of one rule version.+///+/// The sheet order token is deliberately absent: rules reference their sheet, and the sheet holds+/// the token. Moving a sheet therefore updates one token instead of rewriting every rule in it.+///+/// A version holds its selector list by where it starts among the selectors of its sheet, which no+/// other list of the sheet ever starts at: a version whose selectors did not change keeps them.+#[derive(Clone)]+pub struct RuleVersion {+ pub kind: RuleKind,+ /// The name a rule declares, for the rules that reach their consumers by name rather than by+ /// matching anything: the animation a `@keyframes` describes, the custom property an `@property`+ /// registers, or `NONE`. Which index the name is looked up in is decided by the rule's kind.+ declared_name: StyleAtomID,+ pub selectors: SheetListStart,+ pub declaration_block: Option<DeclarationBlockID>,+ pub layer: CascadeLayerID,+ pub scope: StyleScopeID,+}++// NB: Every rule of every sheet a document attaches has one, at the rule's own number, which it+// therefore does not name.+const _: () = assert!(size_of::<RuleVersion>() == 24);++impl RuleVersion {+ fn identity(&self) -> impl Eq + Hash + std::fmt::Debug + '_ {+ let Self {+ kind,+ declared_name,+ selectors,+ declaration_block,+ layer,+ scope,+ } = self;+ (kind, declared_name, selectors, declaration_block, layer, scope)+ }++ #[must_use]+ pub const fn new(kind: RuleKind) -> Self {+ Self {+ kind,+ declared_name: StyleAtomID::NONE,+ selectors: SheetListStart::NONE,+ declaration_block: None,+ layer: CascadeLayerID::UNLAYERED,+ scope: StyleScopeID::NONE,+ }+ }++ /// The name the rule declares, where it declares one.+ #[must_use]+ pub fn declared_name(&self) -> Option<StyleAtomID> {+ (!self.declared_name.is_none()).then_some(self.declared_name)+ }++ pub fn set_declared_name(&mut self, name: StyleAtomID) {+ self.declared_name = name;+ }+}++impl PartialEq for RuleVersion {+ fn eq(&self, other: &Self) -> bool {+ self.identity() == other.identity()+ }+}++impl Eq for RuleVersion {}++impl Hash for RuleVersion {+ fn hash<H: Hasher>(&self, state: &mut H) {+ self.identity().hash(state);+ }+}++impl std::fmt::Debug for RuleVersion {+ fn fmt(&self, formatter: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {+ self.identity().fmt(formatter)+ }+}diff --git a/Libraries/LibWeb/Rust/src/css/style/native_rules.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/native.rssimilarity index 81%rename from Libraries/LibWeb/Rust/src/css/style/native_rules.rsrename to Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/native.rsindex 1eec33ed63c..bbf541c10bc 100644--- a/Libraries/LibWeb/Rust/src/css/style/native_rules.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/native.rs@@ -4,9 +4,9 @@* SPDX-License-Identifier: BSD-2-Clause*/-use super::{RetainedState, RuleID};+use super::RuleID;use crate::css::container_conditions::ContainerConditionsData;-use crate::css::declaration_block::DeclarationBlockData;+use crate::css::style::RetainedState;use std::hash::{Hash, Hasher};use std::num::NonZeroU64;use std::sync::Arc;@@ -15,23 +15,27 @@ mod identities;mod targets;use identities::NativeRuleIdentities;use targets::NativeRuleTargets;+pub(in crate::css::style) use targets::{NativeRuleTargetRef, TargetPages};#[derive(Clone)]-pub(super) struct NativeRuleTarget {+pub(in crate::css::style) struct NativeRuleTarget {pub identity: NonZeroU64,- pub declarations: Option<Arc<DeclarationBlockData>>,pub source_identity: u64,conditions: Option<Box<NativeRuleConditions>>,}+// NB: Every rule the host compiled has one. Its declarations are the block its rule holds.+const _: () = assert!(size_of::<NativeRuleTarget>() == 24);+#[derive(Clone)]struct NativeRuleConditions {- layer_name: Box<[u16]>,+ /// The qualified name of the layer, which every rule of the layer shares.+ layer_name: Arc<[u16]>,containers: Box<[Arc<ContainerConditionsData>]>,}#[derive(Clone, Default)]-pub(super) struct NativeRuleRegistry {+pub(in crate::css::style) struct NativeRuleRegistry {pub targets: NativeRuleTargets,pub identities: NativeRuleIdentities,}@@ -40,13 +44,11 @@ impl PartialEq for NativeRuleTarget {fn eq(&self, other: &Self) -> bool {let Self {identity,- declarations,source_identity,conditions: _,} = self;*identity == other.identity&& *source_identity == other.source_identity- && declarations.as_ref().map(Arc::as_ptr) == other.declarations.as_ref().map(Arc::as_ptr)&& self.layer_name() == other.layer_name()&& self.containers().len() == other.containers().len()&& self@@ -63,12 +65,10 @@ impl Hash for NativeRuleTarget {fn hash<H: Hasher>(&self, hasher: &mut H) {let Self {identity,- declarations,source_identity,conditions: _,} = self;identity.hash(hasher);- declarations.as_ref().map(Arc::as_ptr).hash(hasher);source_identity.hash(hasher);self.layer_name().hash(hasher);for container in self.containers() {@@ -109,11 +109,15 @@ impl RetainedState {/// The identity of the native sheet a rule was compiled from: an imported sheet's own, not the/// importing sheet's.pub(crate) fn rule_source_identity(&self, id: RuleID) -> Option<u64> {- self.native_rules.targets.get(&id).map(|target| target.source_identity)+ self.rules.native_target(id).map(|target| target.source_identity)}pub(crate) fn native_rule_id(&self, identity: u64) -> Option<RuleID> {- self.native_rules.identities.get(&identity)+ self.rules+ .native+ .identities+ .get(&identity)+ .or_else(|| self.rules.user_agent_rule_of_identity(identity))}/// Register immutable cascade inputs independently of document-local rule owners, with the container conditions@@ -122,29 +126,23 @@ impl RetainedState {&mut self,id: RuleID,identity: u64,- declarations: Option<Arc<DeclarationBlockData>>,source_identity: u64,- layer_name: &[u16],+ layer_name: Arc<[u16]>,containers: Box<[Arc<ContainerConditionsData>]>,) {// Whole-sheet replacement can reuse the semantic ID with a new native rule. Retire the// old reverse lookup before installing the replacement; detached CSSOM rules keep their// native identity but no longer name a rule in this engine.- self.native_rules.remove(id);+ self.rules.native.remove(id);let target = NativeRuleTarget {identity: NonZeroU64::new(identity).expect("native rule identities are nonzero"),- declarations,source_identity,- conditions: (!layer_name.is_empty() || !containers.is_empty()).then(|| {- Box::new(NativeRuleConditions {- layer_name: layer_name.into(),- containers,- })- }),+ conditions: (!layer_name.is_empty() || !containers.is_empty())+ .then(|| Box::new(NativeRuleConditions { layer_name, containers })),};- self.native_rules.identities.insert(identity, id);- self.native_rules.targets.insert(id, target);- self.native_rules.reconcile_memory();+ self.rules.native.identities.insert(identity, id);+ self.rules.native.targets.insert(id, target);+ self.rules.native.reconcile_memory();}}@@ -155,7 +153,7 @@ mod tests {use crate::css::parser::value_parser::ParseContext;use crate::css::rule::{rust_rule_identity, rust_rule_list_clear};use crate::css::style::StyleEngine;- use crate::css::style::program::{CascadeOrigin, RuleKind, StyleSheetObjectID};+ use crate::css::style::pipeline::rule_store::{CascadeOrigin, RuleKind};use crate::css::style_sheet::NativeStyleSheet;use std::rc::Rc;@@ -181,7 +179,7 @@ mod tests {let mut engines = [StyleEngine::new(), StyleEngine::new()];let mut ids = Vec::new();for (index, engine) in engines.iter_mut().enumerate() {- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);+ let sheet = engine.add_sheet(CascadeOrigin::Author);for _ in 0..index {engine.add_non_matching_rule(sheet, None, RuleKind::Function);}@@ -189,15 +187,14 @@ mod tests {engine.register_native_rule(id,identity,- rule.cascade_declarations(),source.identity(),- &[],+ std::sync::Arc::default(),Box::default(),);assert_eq!(engine.native_rule_id(identity), Some(id));ids.push(id);assert_eq!(- engine.native_rules.targets.get(&id).unwrap().source_identity,+ engine.rules.native.targets.get(&id).unwrap().source_identity,source_identity);}@@ -209,16 +206,16 @@ mod tests {let replacement = self::source();assert_ne!(replacement.identity(), source_identity);assert_eq!(- engines[1].native_rules.targets.get(&ids[1]).unwrap().source_identity,+ engines[1].rules.native.targets.get(&ids[1]).unwrap().source_identity,source_identity);engines[0].remove_style_rule(ids[0]);- assert!(engines[0].native_rules.identities.is_empty());+ assert!(engines[0].rules.native.identities.is_empty());assert!(rule_weak.upgrade().is_none());assert!(source_weak.upgrade().is_none());- assert_eq!(engines[1].native_rules.identities.get(&identity), Some(ids[1]));+ assert_eq!(engines[1].rules.native.identities.get(&identity), Some(ids[1]));engines[1].remove_style_rule(ids[1]);- assert!(engines[1].native_rules.identities.is_empty());+ assert!(engines[1].rules.native.identities.is_empty());assert!(rule_weak.upgrade().is_none());assert!(source_weak.upgrade().is_none());}@@ -231,14 +228,13 @@ mod tests {let children = rule.child_rules().unwrap();let child = children.rule_at(0);let mut engine = StyleEngine::new();- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);+ let sheet = engine.add_sheet(CascadeOrigin::Author);let id = engine.add_non_matching_rule(sheet, None, RuleKind::Function);engine.register_native_rule(id,rust_rule_identity(rule),- rule.cascade_declarations(),source.identity(),- &[],+ std::sync::Arc::default(),Box::default(),);let mut notifications = Vec::<u32>::new();@@ -275,34 +271,33 @@ mod tests {let old_rule = &old_source.rules().rule_at(0);let new_rule = &new_source.rules().rule_at(0);let mut engine = StyleEngine::new();- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);+ let sheet = engine.add_sheet(CascadeOrigin::Author);let id = engine.add_non_matching_rule(sheet, None, RuleKind::Function);engine.register_native_rule(id,rust_rule_identity(old_rule),- old_rule.cascade_declarations(),old_source.identity(),- &[],+ std::sync::Arc::default(),Box::default(),);engine.register_native_rule(id,rust_rule_identity(new_rule),- new_rule.cascade_declarations(),new_source.identity(),- &[],+ std::sync::Arc::default(),Box::default(),);assert!(!engine- .native_rules+ .rules+ .native.identities.contains_key(&rust_rule_identity(old_rule)));assert_eq!(- engine.native_rules.identities.get(&rust_rule_identity(new_rule)),+ engine.rules.native.identities.get(&rust_rule_identity(new_rule)),Some(id));- assert_eq!(engine.native_rules.targets.len(), 1);+ assert_eq!(engine.rules.native.targets.len(), 1);}}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/native/identities.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/native/identities.rsnew file mode 100644index 00000000000..ac45d6b9715--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/native/identities.rs@@ -0,0 +1,196 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++use crate::css::style::pipeline::rule_store::RuleID;+use std::collections::BTreeMap;++/// Native identities that follow one another by a constant step, naming rules that follow one another.+#[derive(Clone, Copy)]+struct IdentityRun {+ first_rule: u32,+ count: u32,+ /// How far each identity is from the one before.+ step: u32,+}++impl IdentityRun {+ /// Where `identity` is in the run starting at `first`, if it is there.+ fn place_of(self, first: u64, identity: u64) -> Option<u32> {+ let distance = identity - first;+ let step = u64::from(self.step);+ (distance.is_multiple_of(step) && distance / step < u64::from(self.count)).then(|| (distance / step) as u32)+ }++ fn last_identity(self, first: u64) -> u64 {+ first + u64::from(self.count - 1) * u64::from(self.step)+ }+}++/// The rule each native identity names. A parsed sheet numbers its rules in one range, and a document publishes them+/// in that order, so a sheet's rules take one run however many they are: what a document holds per rule of a sheet+/// other documents share is nothing, as the rest of a rule's records are shared pages.+#[derive(Clone, Default)]+pub(in crate::css::style) struct NativeRuleIdentities {+ /// The runs, by their first identity.+ runs: BTreeMap<u64, IdentityRun>,+}++impl NativeRuleIdentities {+ fn run_of(&self, identity: u64) -> Option<(u64, IdentityRun, u32)> {+ let (&first, &run) = self.runs.range(..=identity).next_back()?;+ Some((first, run, run.place_of(first, identity)?))+ }++ pub(in crate::css::style) fn get(&self, identity: &u64) -> Option<RuleID> {+ let (_, run, place) = self.run_of(*identity)?;+ Some(RuleID(run.first_rule + place))+ }++ /// Have no run span `identity`, which no run holds: the identities of a run past it make a run of their own.+ fn split_at(&mut self, identity: u64) {+ let Some((&first, run)) = self.runs.range_mut(..identity).next_back() else {+ return;+ };+ if run.last_identity(first) < identity {+ return;+ }+ let before = (identity - first).div_ceil(u64::from(run.step)) as u32;+ let after = IdentityRun {+ first_rule: run.first_rule + before,+ count: run.count - before,+ step: run.step,+ };+ run.count = before;+ self.runs+ .insert(first + u64::from(before) * u64::from(after.step), after);+ }++ pub(super) fn insert(&mut self, identity: u64, id: RuleID) {+ self.remove(&identity);+ self.split_at(identity);+ if let Some((&first, run)) = self.runs.range_mut(..identity).next_back() {+ let last_rule = run.first_rule + run.count - 1;+ let last = run.last_identity(first);+ let extends = last < identity+ && last_rule.checked_add(1) == Some(id.0)+ && u32::try_from(identity - last).is_ok_and(|step| run.count == 1 || step == run.step);+ if extends {+ run.step = u32::try_from(identity - last).expect("the step fits");+ run.count += 1;+ return;+ }+ }+ self.runs.insert(+ identity,+ IdentityRun {+ first_rule: id.0,+ count: 1,+ step: 1,+ },+ );+ }++ pub(super) fn remove(&mut self, identity: &u64) -> Option<RuleID> {+ let (first, run, place) = self.run_of(*identity)?;+ self.runs.remove(&first);+ if place > 0 {+ self.runs.insert(first, IdentityRun { count: place, ..run });+ }+ let after = run.count - place - 1;+ if after > 0 {+ self.runs.insert(+ identity + u64::from(run.step),+ IdentityRun {+ first_rule: run.first_rule + place + 1,+ count: after,+ step: run.step,+ },+ );+ }+ Some(RuleID(run.first_rule + place))+ }++ #[cfg(test)]+ pub(super) fn is_empty(&self) -> bool {+ self.runs.is_empty()+ }++ #[cfg(test)]+ pub(super) fn contains_key(&self, identity: &u64) -> bool {+ self.get(identity).is_some()+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_sheet_published_in_order_takes_one_run() {+ let mut identities = NativeRuleIdentities::default();+ for index in 0..1000 {+ identities.insert(5000 + index * 2, RuleID(7 + index as u32));+ }+ assert_eq!(identities.runs.len(), 1);+ assert_eq!(identities.get(&5000), Some(RuleID(7)));+ assert_eq!(identities.get(&5002), Some(RuleID(8)));+ assert_eq!(identities.get(&5001), None);+ assert_eq!(identities.get(&(5000 + 999 * 2)), Some(RuleID(1006)));+ assert_eq!(identities.get(&(5000 + 1000 * 2)), None);+ assert_eq!(identities.get(&4998), None);+ }++ #[test]+ fn removing_splits_a_run_and_overwriting_moves_an_identity() {+ let mut identities = NativeRuleIdentities::default();+ for index in 0..10 {+ identities.insert(100 + index, RuleID(index as u32));+ }+ assert_eq!(identities.remove(&104), Some(RuleID(4)));+ assert_eq!(identities.remove(&104), None);+ assert_eq!(identities.runs.len(), 2);+ assert_eq!(identities.get(&103), Some(RuleID(3)));+ assert_eq!(identities.get(&105), Some(RuleID(5)));+ identities.insert(102, RuleID(50));+ assert_eq!(identities.get(&102), Some(RuleID(50)));+ assert_eq!(identities.get(&101), Some(RuleID(1)));+ assert_eq!(identities.get(&103), Some(RuleID(3)));+ for identity in [100, 101, 102, 103, 105, 106, 107, 108, 109] {+ assert!(identities.remove(&identity).is_some());+ }+ assert!(identities.is_empty());+ }++ #[test]+ fn an_identity_between_those_of_a_run_splits_it() {+ let mut identities = NativeRuleIdentities::default();+ for index in 0..5 {+ identities.insert(100 + index * 2, RuleID(index as u32));+ }+ identities.insert(103, RuleID(50));+ assert_eq!(identities.get(&103), Some(RuleID(50)));+ for index in 0..5 {+ assert_eq!(identities.get(&(100 + index * 2)), Some(RuleID(index as u32)));+ }+ assert_eq!(identities.get(&101), None);+ assert_eq!(identities.get(&105), None);+ }++ #[test]+ fn sparse_identities_and_the_largest_one_are_found() {+ let mut identities = NativeRuleIdentities::default();+ for (identity, rule) in [(1, 0), (127, 1), (128, 2), (u64::MAX, 3)] {+ identities.insert(identity, RuleID(rule));+ }+ assert_eq!(identities.get(&u64::MAX), Some(RuleID(3)));+ assert_eq!(identities.get(&2), None);+ assert_eq!(identities.remove(&2), None);+ for identity in [1, 127, 128, u64::MAX] {+ assert!(identities.remove(&identity).is_some());+ }+ assert!(identities.is_empty());+ }+}diff --git a/Libraries/LibWeb/Rust/src/css/style/native_rules/targets.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/native/targets.rssimilarity index 86%rename from Libraries/LibWeb/Rust/src/css/style/native_rules/targets.rsrename to Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/native/targets.rsindex 3e334b36285..207a6ad256c 100644--- a/Libraries/LibWeb/Rust/src/css/style/native_rules/targets.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/native/targets.rs@@ -6,19 +6,18 @@use super::NativeRuleTarget;use crate::css::container_conditions::ContainerConditionsData;-use crate::css::declaration_block::DeclarationBlockData;use crate::css::style::fast_hash::fast_hasher;-use crate::css::style::program::RuleID;+use crate::css::style::pipeline::rule_store::RuleID;use crate::css::style::weak_pool::WeakPool;use std::hash::{Hash, Hasher};use std::num::NonZeroU64;-use std::sync::{Arc, Mutex, MutexGuard, OnceLock};+use std::sync::{Arc, Mutex};const TARGETS_PER_PAGE: usize = 128;#[derive(Clone)]-struct TargetPage {+pub(in crate::css::style) struct TargetPage {values: [Option<NativeRuleTarget>; TARGETS_PER_PAGE],live_count: u16,shared_hash: Option<u64>,@@ -85,10 +84,6 @@ pub(in crate::css::style) struct NativeRuleTargetRef<'a> {}impl<'a> NativeRuleTargetRef<'a> {- pub(in crate::css::style) fn declarations(&self) -> Option<&'a Arc<DeclarationBlockData>> {- self.data.declarations.as_ref()- }-pub(in crate::css::style) fn layer_name(&self) -> &'a [u16] {self.data.layer_name()}@@ -98,12 +93,8 @@ impl<'a> NativeRuleTargetRef<'a> {}}-fn target_pages() -> MutexGuard<'static, WeakPool<TargetPage>> {- // Every engine interns through the same pool, from whichever thread runs it. Pages never reach- // back into the pool when they are dropped, so the lock is only held while interning.- static TARGET_PAGES: OnceLock<Mutex<WeakPool<TargetPage>>> = OnceLock::new();- TARGET_PAGES.get_or_init(Mutex::default).lock().unwrap()-}+/// The pool equal pages of native rule targets are shared through.+pub(in crate::css::style) type TargetPages = Mutex<WeakPool<TargetPage>>;/// Dense semantic rule identities address immutable pages directly. Store native identities/// relative to each page's document-local bases so copies of one parsed stylesheet can share@@ -119,10 +110,10 @@ impl NativeRuleTargets {fn page_mut(&mut self, index: usize) -> &mut TargetPage {self.needs_sharing = true;let page = self.pages[index / TARGETS_PER_PAGE].as_mut().unwrap();+ // NB: A page the pool knows is copied, as one another table holds is: the pool keeps no+ // page alive, and the copy is published again where the table is next shared.if Arc::get_mut(&mut page.data).is_none() {- target_pages().make_private(page.data.shared_hash, &mut page.data, |data| {- TargetPage::new(data.values.clone())- });+ page.data = Arc::new(TargetPage::new(page.data.values.clone()));}let data = Arc::get_mut(&mut page.data).expect("a private page has one owner");if page.identity_base != 0 || page.source_base != 0 {@@ -149,12 +140,6 @@ impl NativeRuleTargets {})}- pub(in crate::css::style) fn get_mut(&mut self, id: &RuleID) -> Option<&mut NativeRuleTarget> {- self.get(id)?;- let index = id.0 as usize;- self.page_mut(index).values[index % TARGETS_PER_PAGE].as_mut()- }-pub(super) fn insert(&mut self, id: RuleID, target: NativeRuleTarget) {let index = id.0 as usize;let page_index = index / TARGETS_PER_PAGE;@@ -192,11 +177,11 @@ impl NativeRuleTargets {.sum()}- pub(in crate::css::style) fn share(&mut self) {+ pub(in crate::css::style) fn share(&mut self, pool: &TargetPages) {if !self.needs_sharing {return;}- let mut pool = target_pages();+ let mut pool = pool.lock().unwrap();for page in self.pages.iter_mut().flatten() {if page.data.shared_hash.is_some() {continue;@@ -224,7 +209,6 @@ mod tests {fn target(identity: u64) -> NativeRuleTarget {NativeRuleTarget {identity: NonZeroU64::new(identity).unwrap(),- declarations: None,source_identity: 1,conditions: None,}@@ -232,6 +216,7 @@ mod tests {#[test]fn relative_pages_preserve_native_identities_across_sharing_and_mutation() {+ let pool = TargetPages::default();let mut first = NativeRuleTargets::default();let mut second = NativeRuleTargets::default();for (base, table) in [(0, &mut first), (1000, &mut second)] {@@ -243,8 +228,8 @@ mod tests {}first.insert(RuleID(TARGETS_PER_PAGE as u32), target(200));second.insert(RuleID(TARGETS_PER_PAGE as u32), target(201));- first.share();- second.share();+ first.share(&pool);+ second.share(&pool);assert!(Arc::ptr_eq(&first.pages[0].as_ref().unwrap().data,&second.pages[0].as_ref().unwrap().data@@ -270,12 +255,14 @@ mod tests {let mut replacement = target(1008);replacement.source_identity = 1001;second.insert(RuleID(7), replacement);- second.share();+ second.share(&pool);assert!(Arc::ptr_eq(&first.pages[0].as_ref().unwrap().data,&second.pages[0].as_ref().unwrap().data));- second.get_mut(&RuleID(7)).unwrap().identity = NonZeroU64::new(300).unwrap();+ let mut edited = target(300);+ edited.source_identity = 1001;+ second.insert(RuleID(7), edited);assert_eq!(first.get(&RuleID(7)).unwrap().identity.get(), 8);assert_eq!(second.get(&RuleID(7)).unwrap().identity.get(), 300);for index in 0..=TARGETS_PER_PAGE {@@ -286,7 +273,7 @@ mod tests {let mut largest = target(u64::MAX);largest.source_identity = u64::MAX;second.insert(RuleID(0), largest);- second.share();+ second.share(&pool);assert_eq!(second.get(&RuleID(0)).unwrap().identity.get(), u64::MAX);assert_eq!(second.get(&RuleID(0)).unwrap().source_identity, u64::MAX);let removed = second.remove(&RuleID(0)).unwrap();diff --git a/Libraries/LibWeb/Rust/src/css/style/program/rule_records.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/rule_records.rssimilarity index 72%rename from Libraries/LibWeb/Rust/src/css/style/program/rule_records.rsrename to Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/rule_records.rsindex 357949bce09..ac5e38cd6a2 100644--- a/Libraries/LibWeb/Rust/src/css/style/program/rule_records.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/rule_records.rs@@ -9,11 +9,11 @@ use crate::css::style::fast_hash::fast_hasher;use crate::css::style::weak_pool::WeakPool;use std::hash::{Hash, Hasher};use std::ops::{Index, IndexMut};-use std::sync::{Arc, Mutex, MutexGuard, OnceLock};+use std::sync::{Arc, Mutex};const RULE_RECORDS_PER_PAGE: usize = 128;-struct RuleRecordPage {+pub(in crate::css::style) struct RuleRecordPage {values: [Option<Rule>; RULE_RECORDS_PER_PAGE],shared_hash: Option<u64>,}@@ -27,12 +27,8 @@ impl RuleRecordPage {}}-fn rule_record_pages() -> MutexGuard<'static, WeakPool<RuleRecordPage>> {- // Every engine interns through the same pool, from whichever thread runs it. Pages never reach- // back into the pool when they are dropped, so the lock is only held while interning.- static RULE_RECORD_PAGES: OnceLock<Mutex<WeakPool<RuleRecordPage>>> = OnceLock::new();- RULE_RECORD_PAGES.get_or_init(Mutex::default).lock().unwrap()-}+/// The pool equal pages of rule records are shared through.+pub(in crate::css::style) type RuleRecordPages = Mutex<WeakPool<RuleRecordPage>>;/// Equal rule records share immutable pages through the process's pool. Child lists remain/// outside the records; mutations detach only their page, including updates to its child-list slot.@@ -44,6 +40,28 @@ pub(super) struct RuleRecordTable {}impl RuleRecordTable {+ /// The bytes of the table's pages, each counted once, with what `rule_heap` says each rule+ /// holds.+ pub(super) fn heap_size(+ &self,+ sizer: &mut crate::heap_size::HeapSizer,+ mut rule_heap: impl FnMut(&Rule, &mut crate::heap_size::HeapSizer) -> usize,+ ) -> usize {+ let mut bytes = crate::heap_size::vec_bytes(&self.pages);+ for page in &self.pages {+ if sizer.first_sight(Arc::as_ptr(page)) {+ bytes += crate::heap_size::ARC_HEADER_BYTES + size_of::<RuleRecordPage>();+ bytes += page+ .values+ .iter()+ .flatten()+ .map(|rule| rule_heap(rule, sizer))+ .sum::<usize>();+ }+ }+ bytes+ }+pub(super) fn len(&self) -> usize {self.len}@@ -63,8 +81,10 @@ impl RuleRecordTable {assert!(index < self.len);self.needs_sharing = true;let page = &mut self.pages[index / RULE_RECORDS_PER_PAGE];+ // NB: A page the pool knows is copied, as one another table holds is: the pool keeps no+ // page alive, and the copy is published again where the table is next shared.if Arc::get_mut(page).is_none() {- rule_record_pages().make_private(page.shared_hash, page, |page| RuleRecordPage::new(page.values.clone()));+ *page = Arc::new(RuleRecordPage::new(page.values.clone()));}let page = Arc::get_mut(page).expect("a private page has one owner");page.shared_hash = None;@@ -83,11 +103,11 @@ impl RuleRecordTable {.map(|rule| rule.as_ref().expect("a live rule slot has a record"))}- pub(super) fn share(&mut self) {+ pub(super) fn share(&mut self, pool: &RuleRecordPages) {if !self.needs_sharing {return;}- let mut pool = rule_record_pages();+ let mut pool = pool.lock().unwrap();for page in &mut self.pages {if page.shared_hash.is_some() {continue;@@ -133,17 +153,19 @@ impl IndexMut<usize> for RuleRecordTable {#[cfg(test)]mod tests {use super::*;- use crate::css::style::program::{CascadeOrigin, RuleID, RuleKind, StyleSheetObjectID, StyleSheetProgram};+ use crate::css::style::pipeline::rule_store::RuleStore;+ use crate::css::style::pipeline::rule_store::{CascadeOrigin, RuleID, RuleKind};#[test]fn shared_rule_records_detach_flags_and_keep_child_lists_document_local() {+ let pools = crate::css::style::pipeline::ProcessRuleIndexes::default();let make_program = || {- let mut program = StyleSheetProgram::new();- let sheet = program.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);+ let mut program = RuleStore::new();+ let sheet = program.add_sheet(CascadeOrigin::Author);for _ in 0..RULE_RECORDS_PER_PAGE * 2 + 1 {program.append_rule(sheet, None, RuleKind::Style);}- program.share_rule_storage();+ program.share_rule_storage(Some(&pools));program};let first = make_program();@@ -158,7 +180,7 @@ mod tests {assert!(!second.rule_conditions_hold(changed));assert!(Arc::ptr_eq(&first.rules.pages[0], &second.rules.pages[0]));assert!(!Arc::ptr_eq(&first.rules.pages[1], &second.rules.pages[1]));- second.share_rule_storage();+ second.share_rule_storage(Some(&pools));let parent = RuleID(0);let child = second.append_rule(second.rule_sheet(parent), Some(parent), RuleKind::Style);@@ -174,14 +196,15 @@ mod tests {#[test]fn a_clone_shares_the_unpublished_pages_it_holds_with_the_original() {- let mut program = StyleSheetProgram::new();- let sheet = program.add_sheet(StyleSheetObjectID(0x5ee7), CascadeOrigin::Author);+ let pools = crate::css::style::pipeline::ProcessRuleIndexes::default();+ let mut program = RuleStore::new();+ let sheet = program.add_sheet(CascadeOrigin::Author);for _ in 0..RULE_RECORDS_PER_PAGE + 1 {program.append_rule(sheet, None, RuleKind::Style);}let mut clone = program.clone();- clone.share_rule_storage();- program.share_rule_storage();+ clone.share_rule_storage(Some(&pools));+ program.share_rule_storage(Some(&pools));for (left, right) in program.rules.pages.iter().zip(&clone.rules.pages) {assert!(Arc::ptr_eq(left, right));}diff --git a/Libraries/LibWeb/Rust/src/css/style/program/rule_versions.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/rule_versions.rssimilarity index 69%rename from Libraries/LibWeb/Rust/src/css/style/program/rule_versions.rsrename to Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/rule_versions.rsindex 5a6b442ac7d..6c413158e01 100644--- a/Libraries/LibWeb/Rust/src/css/style/program/rule_versions.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/rule_versions.rs@@ -4,26 +4,17 @@* SPDX-License-Identifier: BSD-2-Clause*/-use super::{CascadeLayerID, RuleID, RuleKind, RuleVersion, StyleScopeID};use crate::css::style::fast_hash::fast_hasher;+use crate::css::style::pipeline::rule_store::{RuleKind, RuleVersion};use crate::css::style::weak_pool::WeakPool;use std::hash::{Hash, Hasher};use std::ops::Index;-use std::sync::{Arc, Mutex, MutexGuard, OnceLock};+use std::sync::{Arc, Mutex};const RULE_VERSIONS_PER_PAGE: usize = 128;-const EMPTY_VERSION: RuleVersion = RuleVersion {- rule: RuleID(0),- kind: RuleKind::Style,- declared_name: None,- selector_program: None,- declaration_block: None,- activation_predicate: None,- layer: CascadeLayerID::UNLAYERED,- scope: StyleScopeID::NONE,-};--struct RuleVersionPage {+const EMPTY_VERSION: RuleVersion = RuleVersion::new(RuleKind::Style);++pub(in crate::css::style) struct RuleVersionPage {values: [RuleVersion; RULE_VERSIONS_PER_PAGE],shared_hash: Option<u64>,}@@ -37,15 +28,11 @@ impl RuleVersionPage {}}-fn rule_version_pages() -> MutexGuard<'static, WeakPool<RuleVersionPage>> {- // Every engine interns through the same pool, from whichever thread runs it. Pages never reach- // back into the pool when they are dropped, so the lock is only held while interning.- static RULE_VERSION_PAGES: OnceLock<Mutex<WeakPool<RuleVersionPage>>> = OnceLock::new();- RULE_VERSION_PAGES.get_or_init(Mutex::default).lock().unwrap()-}+/// The pool equal pages of rule versions are shared through.+pub(in crate::css::style) type RuleVersionPages = Mutex<WeakPool<RuleVersionPage>>;-/// Rule versions contain only numeric identities. Equal pages are interned through the process's-/// pool rather than copied.+/// Rule versions contain only identities: numbers, and selector programs compared by address. Equal+/// pages are interned through the process's pool rather than copied.#[derive(Clone, Default)]pub(super) struct RuleVersionTable {pages: Vec<Arc<RuleVersionPage>>,@@ -54,6 +41,11 @@ pub(super) struct RuleVersionTable {}impl RuleVersionTable {+ /// The bytes of the table's pages, each counted once.+ pub(super) fn heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {+ crate::heap_size::vec_bytes(&self.pages) + self.pages.iter().map(|page| sizer.arc_shallow(page)).sum::<usize>()+ }+pub(super) fn len(&self) -> usize {self.len}@@ -75,8 +67,10 @@ impl RuleVersionTable {return;}let page = &mut self.pages[index / RULE_VERSIONS_PER_PAGE];+ // NB: A page the pool knows is copied, as one another table holds is: the pool keeps no+ // page alive, and the copy is published again where the table is next shared.if Arc::get_mut(page).is_none() {- rule_version_pages().make_private(page.shared_hash, page, |page| RuleVersionPage::new(page.values));+ *page = Arc::new(RuleVersionPage::new(page.values.clone()));}let page = Arc::get_mut(page).expect("a private page has one owner");page.shared_hash = None;@@ -84,11 +78,11 @@ impl RuleVersionTable {self.needs_sharing = true;}- pub(super) fn share(&mut self) {+ pub(super) fn share(&mut self, pool: &RuleVersionPages) {if !self.needs_sharing {return;}- let mut pool = rule_version_pages();+ let mut pool = pool.lock().unwrap();for page in &mut self.pages {if page.shared_hash.is_some() {continue;@@ -103,7 +97,7 @@ impl RuleVersionTable {// A clone of the table, as a fork of the style engine, holds the unpublished page too, and publishes a// copy of its own.if Arc::get_mut(page).is_none() {- *page = Arc::new(RuleVersionPage::new(page.values));+ *page = Arc::new(RuleVersionPage::new(page.values.clone()));}Arc::get_mut(page).expect("a private page has one owner").shared_hash = Some(hash);pool.insert(hash, page);@@ -127,12 +121,13 @@ mod tests {#[test]fn equal_pages_share_and_edits_detach_only_the_changed_page() {+ let pool = RuleVersionPages::default();let make_table = || {let mut table = RuleVersionTable::default();- for index in 0..RULE_VERSIONS_PER_PAGE * 2 + 1 {- table.push(RuleVersion::new(RuleID(index as u32), RuleKind::Style));+ for _ in 0..RULE_VERSIONS_PER_PAGE * 2 + 1 {+ table.push(RuleVersion::new(RuleKind::Style));}- table.share();+ table.share(&pool);table};let first = make_table();@@ -141,15 +136,15 @@ mod tests {assert!(Arc::ptr_eq(left, right));}let index = RULE_VERSIONS_PER_PAGE + 7;- let mut changed = second[index];+ let mut changed = second[index].clone();changed.kind = RuleKind::Media;second.set(index, changed);assert_eq!(first[index].kind, RuleKind::Style);assert_eq!(second[index].kind, RuleKind::Media);assert!(Arc::ptr_eq(&first.pages[0], &second.pages[0]));assert!(!Arc::ptr_eq(&first.pages[1], &second.pages[1]));- second.share();- second.push(RuleVersion::new(RuleID(second.len() as u32), RuleKind::Style));+ second.share(&pool);+ second.push(RuleVersion::new(RuleKind::Style));assert_eq!(first.len(), RULE_VERSIONS_PER_PAGE * 2 + 1);assert_eq!(second.len(), first.len() + 1);drop(second);@@ -161,13 +156,17 @@ mod tests {#[test]fn a_clone_shares_the_unpublished_pages_it_holds_with_the_original() {+ let pool = RuleVersionPages::default();let mut table = RuleVersionTable::default();for index in 0..RULE_VERSIONS_PER_PAGE + 1 {- table.push(RuleVersion::new(RuleID(0x5ee7_0000 + index as u32), RuleKind::Style));+ // NB: Names no other test gives, so that no page another test published is equal.+ let mut version = RuleVersion::new(RuleKind::Keyframes);+ version.set_declared_name(crate::css::style::StyleAtomID(0x5ee7_0000 + index as u32));+ table.push(version);}let mut clone = table.clone();- clone.share();- table.share();+ clone.share(&pool);+ table.share(&pool);for (left, right) in table.pages.iter().zip(&clone.pages) {assert!(Arc::ptr_eq(left, right));}diff --git a/Libraries/LibWeb/Rust/src/css/style/sheet_occurrences.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/sheet_occurrences.rssimilarity index 78%rename from Libraries/LibWeb/Rust/src/css/style/sheet_occurrences.rsrename to Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/sheet_occurrences.rsindex 43d28a53d1a..2559773ecde 100644--- a/Libraries/LibWeb/Rust/src/css/style/sheet_occurrences.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/sheet_occurrences.rs@@ -4,7 +4,7 @@* SPDX-License-Identifier: BSD-2-Clause*/-use super::*;+use super::super::super::*;#[derive(Clone)]@@ -15,13 +15,13 @@ struct SheetOccurrence {}#[derive(Clone, Default)]-pub(super) struct ScopeSheetOccurrences {+pub(in crate::css::style) struct ScopeSheetOccurrences {occurrences: Vec<SheetOccurrence>,published: Vec<SheetID>,}impl StyleEngine {- pub(super) fn attach_sheet_occurrence(+ pub(in crate::css::style) fn attach_sheet_occurrence(&mut self,sheet: SheetID,scope: TreeScopeID,@@ -46,7 +46,7 @@ impl StyleEngine {self.publish_sheet_occurrences(scope);}- pub(super) fn detach_sheet_occurrence(&mut self, scope: TreeScopeID, identity: u64) {+ pub(in crate::css::style) fn detach_sheet_occurrence(&mut self, scope: TreeScopeID, identity: u64) {let Some(state) = self.host.sheet_occurrences.get_mut(&scope) else {return;};@@ -54,7 +54,12 @@ impl StyleEngine {self.publish_sheet_occurrences(scope);}- pub(super) fn set_sheet_occurrence_conditions(&mut self, scope: TreeScopeID, identity: u64, conditions_hold: bool) {+ pub(in crate::css::style) fn set_sheet_occurrence_conditions(+ &mut self,+ scope: TreeScopeID,+ identity: u64,+ conditions_hold: bool,+ ) {let Some(entry) = self.host.sheet_occurrences@@ -96,11 +101,6 @@ impl StyleEngine {}let old_set: HashSet<_> = old.iter().copied().collect();- let active_set: HashSet<_> = active.iter().copied().collect();- let order_changed = old- .iter()- .filter(|sheet| active_set.contains(sheet))- .ne(active.iter().filter(|sheet| old_set.contains(sheet)));// Preserve legacy attachments, including the document's user and user-agent sheets.let mut sheets: Vec<_> = self.current_sheets_in_scope(scope)@@ -109,20 +109,7 @@ impl StyleEngine {.filter(|sheet| !old_set.contains(sheet)).collect();sheets.extend_from_slice(&active);- for &sheet in active.iter().filter(|sheet| !old_set.contains(sheet)) {- self.restore_routing_for_reattached_sheet(sheet);- }self.stage_sheets_in_scope(scope, sheets);- for &sheet in old.iter().filter(|sheet| !active_set.contains(sheet)) {- self.record_attachment(sheet, scope, true, false);- self.retained.routing_needs_detachment_sweep = true;- }- for &sheet in active.iter().filter(|sheet| !old_set.contains(sheet)) {- self.record_attachment(sheet, scope, false, true);- }- if order_changed {- self.record_sheet_order_change(scope);- }}}@@ -133,8 +120,8 @@ mod tests {#[test]fn duplicate_occurrences_preserve_positions_while_inactive() {let mut engine = StyleEngine::new();- let shared = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- let other = engine.add_sheet(StyleSheetObjectID(2), CascadeOrigin::Author);+ let shared = engine.add_sheet(CascadeOrigin::Author);+ let other = engine.add_sheet(CascadeOrigin::Author);let scope = TreeScopeID::DOCUMENT;engine.attach_sheet_occurrence(shared, scope, 1, 0, true);engine.attach_sheet_occurrence(other, scope, 2, 0, true);@@ -160,7 +147,7 @@ mod tests {#[test]fn occurrence_conditions_are_local_to_their_scope_and_storage_is_released() {let mut engine = StyleEngine::new();- let shared = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);+ let shared = engine.add_sheet(CascadeOrigin::Author);let first = TreeScopeID(1);let second = TreeScopeID(2);engine.attach_sheet_occurrence(shared, first, 1, 0, true);@@ -168,7 +155,7 @@ mod tests {engine.set_sheet_occurrence_conditions(first, 1, false);assert!(engine.current_sheets_in_scope(first).is_empty());assert_eq!(engine.current_sheets_in_scope(second), &[shared]);- assert!(engine.program.sheet_conditions_hold(shared));+ assert!(engine.rules.sheet_conditions_hold(shared));engine.detach_sheet_occurrence(first, 1);engine.detach_sheet_occurrence(second, 2);assert!(engine.host.sheet_occurrences.is_empty());diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/staging.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/staging.rsnew file mode 100644index 00000000000..a9a48dd3b39--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/staging.rs@@ -0,0 +1,856 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The rule edits a transaction stages, which the rule store takes at the transaction barrier.++use super::super::super::*;+use super::RuleDeclarations;+use crate::css::declaration_block::SharedDeclarationBlock;++#[derive(Clone)]+struct StagedFieldRow<V> {+ before: V,+ after: V,+ dirty: bool,+}++/// Sparse staging for one program field. The first write freezes `before`, later writes replace+/// `after`, and `take_dirty()` applies only the last write while retaining both sides for+/// `ProgramStaging::delta()`.+#[derive(Clone)]+struct StagedField<K, V> {+ rows: HashMap<K, StagedFieldRow<V>>,+ touched: Vec<K>,+ dirty_count: usize,+}++impl<K, V> Default for StagedField<K, V> {+ fn default() -> Self {+ Self {+ rows: HashMap::default(),+ touched: Vec::new(),+ dirty_count: 0,+ }+ }+}++impl<K: Copy + Eq + Hash + Ord, V: Clone> StagedField<K, V> {+ fn current(&self, key: K, committed: impl FnOnce() -> V) -> V {+ self.side(key, TransactionFactSide::After, committed)+ }++ fn after(&self, key: K) -> Option<&V> {+ self.rows.get(&key).map(|row| &row.after)+ }++ fn side(&self, key: K, side: TransactionFactSide, resident: impl FnOnce() -> V) -> V {+ let row = self.rows.get(&key);+ match (side, row) {+ (TransactionFactSide::Before, Some(row)) => row.before.clone(),+ (TransactionFactSide::After, Some(row)) => row.after.clone(),+ _ => resident(),+ }+ }++ fn stage(&mut self, key: K, before: impl FnOnce() -> V, after: V) {+ match self.rows.entry(key) {+ std::collections::hash_map::Entry::Occupied(mut entry) => {+ let row = entry.get_mut();+ row.after = after;+ if !row.dirty {+ row.dirty = true;+ self.dirty_count += 1;+ }+ }+ std::collections::hash_map::Entry::Vacant(entry) => {+ entry.insert(StagedFieldRow {+ before: before(),+ after,+ dirty: true,+ });+ self.touched.push(key);+ self.dirty_count += 1;+ }+ }+ }++ fn take_dirty(&mut self) -> Vec<(K, V)> {+ if self.is_empty() {+ return Vec::new();+ }+ let mut dirty = Vec::with_capacity(self.dirty_count);+ for &key in &self.touched {+ let row = self.rows.get_mut(&key).unwrap();+ if row.dirty {+ dirty.push((key, row.after.clone()));+ row.dirty = false;+ }+ }+ self.dirty_count = 0;+ dirty.sort_unstable_by_key(|(key, _)| *key);+ dirty+ }++ fn is_empty(&self) -> bool {+ self.dirty_count == 0+ }++ pub(in crate::css::style) fn clear(&mut self) {+ self.rows.clear();+ self.touched.clear();+ // Keep small edit buffers warm, but do not retain stylesheet-loading capacity for the+ // lifetime of every document. These rows are only needed until transaction release.+ if self.rows.capacity() * size_of::<(K, StagedFieldRow<V>)>() > 4096 {+ self.rows = HashMap::default();+ }+ if self.touched.capacity() * size_of::<K>() > 4096 {+ self.touched = Vec::new();+ }+ self.dirty_count = 0;+ }++ fn pairs(&self) -> impl Iterator<Item = (K, &V, &V)> {+ self.touched.iter().map(|&key| {+ let row = self.rows.get(&key).unwrap();+ (key, &row.before, &row.after)+ })+ }+}++/// Program transaction staging. Every field preserves its first before value and last-writer+/// after value until release; `delta()` may read those pairs after the final values are applied.+#[derive(Clone, Default)]+pub(in crate::css::style) struct ProgramStaging {+ rule_conditions: StagedField<RuleID, bool>,+ sheet_conditions: StagedField<SheetID, bool>,+ sheet_enabled: StagedField<SheetID, bool>,+ rule_declarations: StagedField<RuleID, RuleDeclarations>,+ rule_versions: StagedField<RuleID, RuleVersion>,+ rule_in_a_layer: StagedField<RuleID, bool>,+ rule_gated_by_container_query: StagedField<RuleID, bool>,+ rule_liveness: StagedField<RuleID, bool>,+ layer_orders: StagedField<TreeScopeID, HashMap<CascadeLayerID, u32>>,+ scopes_using_document_sheets: StagedField<TreeScopeID, bool>,+ sheets_in_scope: StagedField<TreeScopeID, Vec<SheetID>>,+ sheet_rule_replacements: Column<Option<SheetRuleReplacement>>,+ /// Whether a registration made through `CSS.registerProperty()` waits for the next+ /// transaction, which says what moved of the registrations as it takes the registry in.+ registration_pending: bool,+ /// The names whose registration the registry the next transaction reads holds otherwise than+ /// the one the last transaction read.+ moved_registrations: Vec<ak::Utf16FlyString>,+}++impl ProgramStaging {+ pub(in crate::css::style) fn is_dirty(&self) -> bool {+ !self.rule_conditions.is_empty()+ || !self.sheet_conditions.is_empty()+ || !self.sheet_enabled.is_empty()+ || !self.rule_declarations.is_empty()+ || !self.rule_versions.is_empty()+ || !self.rule_in_a_layer.is_empty()+ || !self.rule_gated_by_container_query.is_empty()+ || !self.rule_liveness.is_empty()+ || !self.layer_orders.is_empty()+ || !self.scopes_using_document_sheets.is_empty()+ || !self.sheets_in_scope.is_empty()+ || self.sheet_rule_replacements.iter().any(Option::is_some)+ || self.registration_pending+ || !self.moved_registrations.is_empty()+ }++ /// Note a registration made through `CSS.registerProperty()`, which the registry the next+ /// transaction reads holds.+ pub(in crate::css::style) fn note_registration_change(&mut self) {+ self.registration_pending = true;+ }++ /// Note what moved between the registry the last transaction read, `previous`, and the one+ /// the next reads, `registry`.+ pub(in crate::css::style) fn note_registry_moved(+ &mut self,+ previous: &crate::css::custom_properties::CustomPropertyRegistry,+ registry: &crate::css::custom_properties::CustomPropertyRegistry,+ ) {+ for name in registry.names_registered_otherwise_than(previous) {+ if !self.moved_registrations.contains(&name) {+ self.moved_registrations.push(name);+ }+ }+ }++ pub(in crate::css::style) fn clear(&mut self) {+ self.rule_conditions.clear();+ self.sheet_conditions.clear();+ self.sheet_enabled.clear();+ self.rule_declarations.clear();+ self.rule_versions.clear();+ self.rule_in_a_layer.clear();+ self.rule_gated_by_container_query.clear();+ self.rule_liveness.clear();+ self.layer_orders.clear();+ self.scopes_using_document_sheets.clear();+ self.sheets_in_scope.clear();+ for index in 0..self.sheet_rule_replacements.len() {+ self.sheet_rule_replacements[index] = None;+ }+ }+}++#[derive(Clone)]+pub(in crate::css::style) struct ReplacedStyleRule {+ pub(in crate::css::style) rule: RuleID,+ pub(in crate::css::style) version: RuleVersion,+ pub(in crate::css::style) declared: Vec<DeclarationEntry>,+ pub(in crate::css::style) declarations_are_complete: bool,+ pub(in crate::css::style) gated_by_container_query: bool,+}++/// What a transaction changed of the rules, read off the program as it stood before the transaction+/// and as the transaction leaves it.+#[derive(Default)]+pub(crate) struct RuleChanges {+ /// The rules whose contents, conditions, layering or existence moved. A rule of a sheet that was+ /// attached nowhere before the transaction is left out: what it decides arrives with the sheet.+ pub(crate) rules: Vec<RuleID>,+ /// The sheets that were attached to or detached from a scope, or whose activation moved.+ pub(crate) sheets: Vec<SheetID>,+ /// The scopes whose sheet order or layer order moved, which reorders declarations that already+ /// matched without changing which elements they match.+ pub(crate) reordered_scopes: Vec<TreeScopeID>,+ /// The scopes whose layer order moved, which moves the layer ranks of their rules, whether or+ /// not it reorders any of them.+ pub(crate) layered_scopes: Vec<TreeScopeID>,+ /// The custom property names whose registration moved, through an `@property` rule or+ /// `CSS.registerProperty()`.+ pub(crate) registrations: Vec<ak::Utf16FlyString>,+}++impl RuleChanges {+ pub(crate) fn is_empty(&self) -> bool {+ self.rules.is_empty()+ && self.sheets.is_empty()+ && self.reordered_scopes.is_empty()+ && self.layered_scopes.is_empty()+ && self.registrations.is_empty()+ }+}++#[derive(Clone)]+pub(in crate::css::style) struct SheetRuleReplacement {+ pub(in crate::css::style) sheet: SheetID,+ pub(in crate::css::style) rules: Vec<ReplacedStyleRule>,+ pub(in crate::css::style) reused: usize,+ pub(in crate::css::style) reuse_disabled: bool,+}++impl StyleEngine {+ /// 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.rules.scope_uses_document_sheets(tree_scope)+ });+ if previous {+ return;+ }+ self.host.program_staging.scopes_using_document_sheets.stage(+ tree_scope,+ || self.retained.rules.scope_uses_document_sheets(tree_scope),+ true,+ );+ }++ /// Put the qualified layer names in the order one tree scope declares them in.+ pub fn set_layer_order(&mut self, scope: TreeScopeID, layers: &[CascadeLayerID]) {+ let ranks = RuleStore::layer_ranks_in_order(layers);+ let pending_order = self.host.program_staging.layer_orders.after(scope);+ if pending_order.map_or_else(+ || self.retained.rules.layer_ranks_match(scope, &ranks),+ |pending| pending == &ranks,+ ) {+ return;+ }+ self.host+ .program_staging+ .layer_orders+ .stage(scope, || self.retained.rules.layer_ranks(scope), ranks);+ }++ /// The dense layer rank consumed by the C++ property cascade and non-style rule lookup.+ #[must_use]+ pub fn layer_index(&self, scope: TreeScopeID, layer: CascadeLayerID) -> u32 {+ self.host.program_staging.layer_orders.after(scope).map_or_else(+ || self.retained.rules.layer_index(scope, layer),+ |ranks| {+ ranks+ .get(&layer)+ .copied()+ .unwrap_or_else(|| u32::try_from(ranks.len()).expect("cascade layer count exhausted"))+ },+ )+ }++ /// The declaration block `rule` holds, as this transaction staged it.+ pub(in crate::css::style) fn current_rule_block(&self, rule: RuleID) -> Option<SharedDeclarationBlock> {+ match self.host.program_staging.rule_declarations.after(rule) {+ Some(staged) => staged.block.clone(),+ None => self.retained.rules.block_of(rule).cloned(),+ }+ }++ pub(in crate::css::style) fn stage_rule_declarations(&mut self, rule: RuleID, declarations: RuleDeclarations) {+ // NB: As for its version, a rule this transaction reserved takes its declarations in place.+ if self.staged_rule_is_arriving(rule) && self.host.program_staging.rule_declarations.after(rule).is_none() {+ self.retained.rules.set_rule_declarations(rule, declarations);+ return;+ }+ self.host.program_staging.rule_declarations.stage(+ rule,+ || self.retained.rules.rule_declarations_of(rule),+ declarations,+ );+ }++ pub(in crate::css::style) fn current_declared_properties_of(&self, rule: RuleID) -> &[DeclarationEntry] {+ self.host+ .program_staging+ .rule_declarations+ .after(rule)+ .map(|pending| pending.declared_properties())+ .unwrap_or_else(|| self.retained.rules.declared_properties_of(rule))+ }++ pub(in crate::css::style) fn current_declarations_are_complete_for(&self, rule: RuleID) -> bool {+ self.host+ .program_staging+ .rule_declarations+ .after(rule)+ .map(|pending| pending.custom_declarations().is_empty())+ .unwrap_or_else(|| self.retained.rules.declarations_are_complete_for(rule))+ }++ pub fn set_rule_conditions_hold(&mut self, rule: RuleID, conditions_hold: bool) {+ let previous = self+ .host+ .program_staging+ .rule_conditions+ .current(rule, || self.retained.rules.rule_conditions_hold(rule));+ if previous == conditions_hold {+ return;+ }+ self.host.program_staging.rule_conditions.stage(+ rule,+ || self.retained.rules.rule_conditions_hold(rule),+ conditions_hold,+ );+ }++ /// Record whether a sheet's conditions hold, as evaluating its media queries decides.+ pub fn set_sheet_conditions_hold(&mut self, sheet: SheetID, conditions_hold: bool) {+ let previous = self+ .host+ .program_staging+ .sheet_conditions+ .current(sheet, || self.retained.rules.sheet_conditions_hold(sheet));+ if previous == conditions_hold {+ return;+ }+ self.host.program_staging.sheet_conditions.stage(+ sheet,+ || self.retained.rules.sheet_conditions_hold(sheet),+ conditions_hold,+ );+ }++ #[cfg(test)]+ pub(in crate::css::style) fn set_sheet_enabled(&mut self, sheet: SheetID, enabled: bool) {+ let previous = self+ .host+ .program_staging+ .sheet_enabled+ .current(sheet, || self.retained.rules.sheet_is_enabled(sheet));+ if previous == enabled {+ return;+ }+ self.host+ .program_staging+ .sheet_enabled+ .stage(sheet, || self.retained.rules.sheet_is_enabled(sheet), enabled);+ }++ /// Begin rebuilding a sheet while retaining compatible style-rule identities by cascade+ /// position. The parsed CSSOM objects are new, but an unchanged semantic rule does not become a+ /// departure followed by an arrival merely because the whole sheet was reparsed.+ pub fn begin_sheet_rules_replacement(&mut self, sheet: SheetID) {+ assert!(+ self.host.sheet_rule_replacement.is_none(),+ "stylesheet replacements do not nest"+ );+ if let Some(slot) = self+ .host+ .program_staging+ .sheet_rule_replacements+ .get_mut(sheet.0 as usize)+ && let Some(mut replacement) = slot.take()+ {+ replacement.reused = 0;+ replacement.reuse_disabled = false;+ self.host.sheet_rule_replacement = Some(replacement);+ return;+ }+ let rules = self.current_rules_in_sheet(sheet);+ if rules+ .iter()+ .any(|&rule| self.current_rule_version(rule).kind != RuleKind::Style)+ {+ self.clear_sheet_rules(sheet);+ return;+ }+ let rules: Vec<ReplacedStyleRule> = rules+ .into_iter()+ .map(|rule| ReplacedStyleRule {+ rule,+ version: self.current_rule_version(rule),+ declared: self.current_declared_properties_of(rule).to_vec(),+ declarations_are_complete: self.current_declarations_are_complete_for(rule),+ gated_by_container_query: self.current_rule_is_gated_by_container_query(rule),+ })+ .collect();+ self.host.sheet_rule_replacement = Some(SheetRuleReplacement {+ sheet,+ rules,+ reused: 0,+ reuse_disabled: false,+ });+ }++ /// Finish a synchronous sheet rebuild, retiring unmatched old rules and publishing declaration+ /// changes on identities that were reused.+ pub fn finish_sheet_rules_replacement(&mut self, sheet: SheetID, declaration_block: u32) {+ let Some(replacement) = self.host.sheet_rule_replacement.take() else {+ return;+ };+ assert_eq!(replacement.sheet, sheet);+ for old in &replacement.rules[..replacement.reused] {+ let declarations_changed = !old.declarations_are_complete+ || !self.current_declarations_are_complete_for(old.rule)+ || self.current_declared_properties_of(old.rule) != old.declared+ || self.current_rule_is_gated_by_container_query(old.rule) != old.gated_by_container_query;+ if declarations_changed {+ let mut version = self.current_rule_version(old.rule);+ version.declaration_block = Some(DeclarationBlockID::new(declaration_block));+ self.replace_rule_version(old.rule, version);+ }+ }+ if replacement.reused < replacement.rules.len() {+ let index = sheet.0 as usize;+ self.host+ .program_staging+ .sheet_rule_replacements+ .insert(index, Some(replacement));+ }+ }++ pub(in crate::css::style) fn finalize_staged_sheet_rule_replacements(&mut self) {+ for index in 0..self.host.program_staging.sheet_rule_replacements.len() {+ let Some(replacement) = self.host.program_staging.sheet_rule_replacements[index].take() else {+ continue;+ };+ for old in &replacement.rules[replacement.reused..] {+ self.remove_rule(old.rule);+ }+ }+ }++ pub(in crate::css::style) fn reuse_replaced_style_rule(&mut self, sheet: SheetID) -> Option<RuleID> {+ let replacement = self.host.sheet_rule_replacement.as_mut()?;+ if replacement.sheet != sheet || replacement.reuse_disabled {+ return None;+ }+ let old = replacement.rules.get(replacement.reused)?;+ if old.version.kind != RuleKind::Style {+ replacement.reuse_disabled = true;+ return None;+ }+ let rule = old.rule;+ let declaration_block = old.version.declaration_block;+ replacement.reused += 1;++ self.set_rule_conditions_hold(rule, true);+ self.stage_rule_declarations(rule, RuleDeclarations::default());+ self.stage_rule_in_a_layer(rule, false);+ self.stage_rule_gated_by_container_query(rule, false);+ let mut version = RuleVersion::new(RuleKind::Style);+ version.declaration_block = declaration_block;+ self.replace_rule_version(rule, version);+ Some(rule)+ }++ pub(in crate::css::style) fn current_rule_version(&self, rule: RuleID) -> RuleVersion {+ self.host+ .program_staging+ .rule_versions+ .current(rule, || self.retained.rules.rule_version(rule).clone())+ }++ pub(in crate::css::style) fn stage_rule_version(&mut self, rule: RuleID, contents: RuleVersion) {+ // NB: A rule this transaction reserved has no committed version anything reads, and its+ // arrival already names it a changed rule. Its version is written in place rather than+ // staged with a before side nothing asks for, which for a sheet arriving whole would+ // hold two versions of every one of its rules until the transaction is released.+ if self.staged_rule_is_arriving(rule) && self.host.program_staging.rule_versions.after(rule).is_none() {+ self.retained.rules.replace_reserved_rule_version(rule, contents);+ return;+ }+ self.host.program_staging.rule_versions.stage(+ rule,+ || self.retained.rules.rule_version(rule).clone(),+ contents,+ );+ }++ pub(in crate::css::style) fn current_rule_is_gated_by_container_query(&self, rule: RuleID) -> bool {+ self.host+ .program_staging+ .rule_gated_by_container_query+ .current(rule, || self.retained.rules.rule_is_gated_by_container_query(rule))+ }++ pub(in crate::css::style) fn stage_rule_gated_by_container_query(&mut self, rule: RuleID, gated: bool) {+ self.host.program_staging.rule_gated_by_container_query.stage(+ rule,+ || self.retained.rules.rule_is_gated_by_container_query(rule),+ gated,+ );+ }++ pub(in crate::css::style) fn stage_rule_in_a_layer(&mut self, rule: RuleID, in_a_layer: bool) {+ self.host.program_staging.rule_in_a_layer.stage(+ rule,+ || self.retained.rules.rule_is_in_a_layer(rule),+ in_a_layer,+ );+ }++ /// What the staged program changes of the committed one, which has yet to take it.+ fn staged_rule_changes(&self) -> RuleChanges {+ fn moved<K: Copy, V: PartialEq>(pairs: impl Iterator<Item = (K, V, V)>) -> impl Iterator<Item = K> {+ pairs.filter_map(|(key, before, after)| (before != after).then_some(key))+ }+ let staging = &self.host.program_staging;+ let program = &self.retained.rules;+ let mut changes = RuleChanges::default();++ let mut rules: Vec<RuleID> = moved(staging.rule_conditions.pairs())+ .chain(moved(staging.rule_declarations.pairs()))+ .chain(moved(staging.rule_versions.pairs()))+ .chain(moved(staging.rule_in_a_layer.pairs()))+ .chain(moved(staging.rule_gated_by_container_query.pairs()))+ .chain(moved(staging.rule_liveness.pairs()))+ .collect();+ rules.sort_unstable();+ rules.dedup();+ rules.retain(|&rule| !program.sheet_scopes(program.rule_sheet(rule)).is_empty());+ changes.rules = rules;++ changes.sheets = moved(staging.sheet_conditions.pairs())+ .chain(moved(staging.sheet_enabled.pairs()))+ .collect();+ for (scope, before, after) in staging.sheets_in_scope.pairs() {+ let kept_before = before.iter().filter(|sheet| after.contains(sheet));+ let kept_after = after.iter().filter(|sheet| before.contains(sheet));+ if kept_before.ne(kept_after) {+ changes.reordered_scopes.push(scope);+ }+ changes.sheets.extend(+ before+ .iter()+ .filter(|sheet| !after.contains(sheet))+ .chain(after.iter().filter(|sheet| !before.contains(sheet))),+ );+ }+ changes.sheets.sort_unstable();+ changes.sheets.dedup();++ changes.layered_scopes = moved(staging.layer_orders.pairs()).collect();+ // NB: A scope's first layer order places no layered rule that was there before it.+ changes+ .reordered_scopes+ .extend(moved(staging.layer_orders.pairs()).filter(|&scope| program.layer_order_is_initialized(scope)));+ changes.reordered_scopes.sort_unstable();+ changes.reordered_scopes.dedup();+ changes+ }++ pub(in crate::css::style) fn commit_staged_program(&mut self) -> RuleChanges {+ let mut changes = self.staged_rule_changes();+ self.host.program_staging.registration_pending = false;+ changes.registrations = std::mem::take(&mut self.host.program_staging.moved_registrations);+ self.retained+ .counters+ .add(Counter::CascadeTopologyDeltas, changes.reordered_scopes.len() as u64);+ let rule_conditions = self.host.program_staging.rule_conditions.take_dirty();+ let sheet_conditions = self.host.program_staging.sheet_conditions.take_dirty();+ let sheet_enabled = self.host.program_staging.sheet_enabled.take_dirty();+ if !rule_conditions.is_empty() || !sheet_conditions.is_empty() || !sheet_enabled.is_empty() {+ for (rule, conditions_hold) in rule_conditions {+ self.retained.rules.set_rule_conditions_hold(rule, conditions_hold);+ }+ for (sheet, conditions_hold) in sheet_conditions {+ self.retained.rules.set_sheet_conditions_hold(sheet, conditions_hold);+ }+ for (sheet, enabled) in sheet_enabled {+ self.retained.rules.set_sheet_enabled(sheet, enabled);+ }+ }++ let declarations = self.host.program_staging.rule_declarations.take_dirty();+ for (rule, declarations) in declarations {+ self.retained.rules.set_rule_declarations(rule, declarations);+ }++ let mut versions = self.host.program_staging.rule_versions.take_dirty();+ if !versions.is_empty() {+ versions.sort_unstable_by_key(|(rule, _)| *rule);+ for (rule, version) in versions {+ if self.staged_rule_is_arriving(rule) {+ self.retained.rules.replace_reserved_rule_version(rule, version);+ } else {+ self.retained.rules.replace_rule_version(rule, version);+ }+ }+ }++ let in_a_layer = self.host.program_staging.rule_in_a_layer.take_dirty();+ let gated_by_container_query = self.host.program_staging.rule_gated_by_container_query.take_dirty();+ for (rule, value) in in_a_layer {+ self.retained.rules.set_rule_in_a_layer(rule, value);+ }+ for (rule, value) in gated_by_container_query {+ self.retained.rules.set_rule_gated_by_container_query(rule, value);+ }++ let mut liveness_changes = self.host.program_staging.rule_liveness.take_dirty();+ if !liveness_changes.is_empty() {+ liveness_changes.sort_unstable_by_key(|(rule, _)| *rule);+ self.retained.rules.set_rule_liveness(&liveness_changes);+ }++ let layer_orders = self.host.program_staging.layer_orders.take_dirty();+ let scopes = self.host.program_staging.scopes_using_document_sheets.take_dirty();+ if !layer_orders.is_empty() || !scopes.is_empty() {+ for (scope, ranks) in layer_orders {+ self.retained.rules.set_layer_ranks(scope, ranks);+ }+ for (scope, uses_document_sheets) in scopes {+ if uses_document_sheets {+ self.retained.rules.set_scope_uses_document_sheets(scope);+ }+ }+ }++ let mut sheet_orders = self.host.program_staging.sheets_in_scope.take_dirty();+ if !sheet_orders.is_empty() {+ sheet_orders.sort_unstable_by_key(|(scope, _)| *scope);+ for (scope, sheets) in sheet_orders {+ self.retained.rules.set_sheets_in_scope(scope, sheets);+ }+ }+ changes+ }++ pub(in crate::css::style) fn current_rule_is_live(&self, rule: RuleID) -> bool {+ self.host+ .program_staging+ .rule_liveness+ .current(rule, || self.retained.rules.rule_is_live(rule))+ }++ fn staged_rule_is_arriving(&self, rule: RuleID) -> bool {+ !self+ .host+ .program_staging+ .rule_liveness+ .side(rule, TransactionFactSide::Before, || {+ self.retained.rules.rule_is_live(rule)+ })+ && self.current_rule_is_live(rule)+ }++ pub(in crate::css::style) fn stage_rule_liveness(&mut self, rule: RuleID, live: bool) {+ self.host+ .program_staging+ .rule_liveness+ .stage(rule, || self.retained.rules.rule_is_live(rule), live);+ }++ pub(in crate::css::style) fn current_sheets_in_scope(&self, tree_scope: TreeScopeID) -> &[SheetID] {+ self.host+ .program_staging+ .sheets_in_scope+ .after(tree_scope)+ .map_or_else(|| self.retained.rules.sheets_in_scope(tree_scope), Vec::as_slice)+ }++ pub(in crate::css::style) fn stage_sheets_in_scope(&mut self, tree_scope: TreeScopeID, sheets: Vec<SheetID>) {+ self.host.program_staging.sheets_in_scope.stage(+ tree_scope,+ || self.retained.rules.sheets_in_scope(tree_scope).to_vec(),+ sheets,+ );+ }+}++impl StyleEngine {+ pub fn set_rule_gated_by_container_query(&mut self, rule: RuleID) {+ self.stage_rule_gated_by_container_query(rule, true);+ }++ /// Record which cascade layer a rule sits in.+ ///+ /// Where a rule sits among the layers is part of what the rule is, and it is what the cascade+ /// compares; whether it is in one at all is what a layer topology change routes by.+ pub fn set_rule_layer(&mut self, rule: RuleID, layer: CascadeLayerID) {+ let mut version = self.current_rule_version(rule);+ if version.layer == layer {+ return;+ }+ version.layer = layer;+ self.replace_rule_version(rule, version);+ }++ pub fn set_rule_in_a_layer(&mut self, rule: RuleID) {+ self.stage_rule_in_a_layer(rule, true);+ }++ pub(in crate::css::style) fn append_rule(+ &mut self,+ sheet: SheetID,+ parent: Option<RuleID>,+ kind: RuleKind,+ ) -> RuleID {+ let rule = self.retained.rules.reserve_rule(sheet, parent, kind);+ self.stage_rule_liveness(rule, true);+ rule+ }++ /// Insert one rule between two neighbors. Existing rules are neither renumbered nor rematched.+ pub(in crate::css::style) fn insert_rule_before(&mut self, before: RuleID, kind: RuleKind) -> RuleID {+ let rule = self.retained.rules.reserve_rule_before(before, kind);+ self.stage_rule_liveness(rule, true);+ rule+ }++ /// Delete a rule, taking its subtree with it. Every removed identity is a rule change, because a+ /// deleted winning declaration has to be repaired wherever it was winning.+ pub(in crate::css::style) fn remove_rule(&mut self, rule: RuleID) -> Vec<RuleID> {+ if !self.current_rule_is_live(rule) {+ return Vec::new();+ }+ let removed: Vec<RuleID> = self+ .rules+ .rule_subtree(rule)+ .into_iter()+ .filter(|&rule| self.current_rule_is_live(rule))+ .collect();+ for &id in &removed {+ self.retained.rules.native.remove(id);+ self.stage_rule_liveness(id, false);+ }+ removed+ }++ /// Replace a rule's contents.+ pub(in crate::css::style) fn replace_rule_version(&mut self, rule: RuleID, contents: RuleVersion) {+ self.stage_rule_version(rule, contents);+ }++ pub(in crate::css::style) fn current_top_level_rules_in_sheet(&self, sheet: SheetID) -> Vec<RuleID> {+ self.retained+ .rules+ .all_top_level_rules_in_sheet(sheet)+ .iter()+ .copied()+ .filter(|&rule| self.current_rule_is_live(rule))+ .collect()+ }++ pub(in crate::css::style) fn current_rules_in_sheet(&self, sheet: SheetID) -> Vec<RuleID> {+ self.retained+ .rules+ .all_rules_in_sheet(sheet)+ .into_iter()+ .filter(|&rule| self.current_rule_is_live(rule))+ .collect()+ }++ /// Answers the identities the end of the transaction released, for the host to mint again.+ pub(in crate::css::style) fn discard_style_update_outputs(&mut self) -> Vec<u32> {+ self.retained.tree.release_retired_identities()+ }++ /// Releases the identities the end of the transaction released, which the job pays the host to mint again.+ pub(in crate::css::style) fn release_style_update_identities(&mut self) {+ let released = self.discard_style_update_outputs();+ self.host.released_style_nodes.extend(released);+ }++ pub(crate) fn take_released_style_nodes(&mut self) -> Vec<u32> {+ std::mem::take(&mut self.host.released_style_nodes)+ }+}++impl StyleEngine {+ /// Drop every rule of a sheet.+ ///+ /// This is for `replace()`, which really does swap the whole rule list. Every other edit to a+ /// sheet moves one rule and is patched one rule at a time, because retiring identities that did+ /// not change turns a one-rule edit into a program change over the whole sheet.+ pub(in crate::css::style) fn clear_sheet_rules(&mut self, sheet: SheetID) {+ for rule in self.current_top_level_rules_in_sheet(sheet) {+ self.remove_rule(rule);+ }+ }++ /// Delete one rule and settle the program around it.+ pub fn remove_style_rule(&mut self, rule: RuleID) {+ self.remove_rule(rule);+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn sparse_program_staging_freezes_before_until_release() {+ let rule = RuleID(7);+ let mut staged = StagedField::default();+ staged.stage(rule, || 10_u32, 20);+ staged.stage(rule, || panic!("the before value is already frozen"), 30);++ assert_eq!(staged.side(rule, TransactionFactSide::Before, || 0), 10);+ assert_eq!(staged.current(rule, || 0), 30);+ assert_eq!(staged.take_dirty(), [(rule, 30)]);+ assert!(staged.is_empty());+ assert_eq!(staged.side(rule, TransactionFactSide::Before, || 0), 10);+ assert_eq!(staged.current(rule, || 35), 30);++ staged.stage(rule, || panic!("the before value is already frozen"), 40);+ assert_eq!(staged.side(rule, TransactionFactSide::Before, || 0), 10);+ assert_eq!(staged.take_dirty(), [(rule, 40)]);+ assert_eq!(staged.current(rule, || 50), 40);++ staged.clear();+ assert_eq!(staged.current(rule, || 50), 50);+ assert!(staged.rows.is_empty());+ assert!(staged.touched.is_empty());+ }+}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/user_agent.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/user_agent.rsnew file mode 100644index 00000000000..14efcc77eed--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/rule_store/user_agent.rs@@ -0,0 +1,276 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The rules of the user agent's sheets, which the process keeps once and every document reads.+//!+//! A document records no user agent rule. Its user agent sheets stand for sheets of the process's+//! [`UserAgentRules`], whose rules it names by [`RuleID::of_user_agent`], and it keeps only which+//! of them its media leave out. Those sheets and left-out rules are the document's+//! [`UserAgentVariant`], the key of the user agent index it decides with.++use super::{RuleID, RuleStore, SheetID};+use crate::css::style::atoms::DocumentAtoms;+use crate::css::style::selector_analysis::SelectorSummary;+use crate::fork::ForkShared;+use smallvec::SmallVec;+use std::sync::Arc;++/// The rules of the user agent's sheets the process published so far. Nothing edits a published+/// rule, and a sheet arriving makes a new table holding the old one's rules at their numbers, so+/// that a document holding an older table reads what it always read.+#[derive(Clone)]+pub(in crate::css::style) struct UserAgentRules {+ store: RuleStore,+ sheets: SmallVec<[UserAgentSheet; 4]>,+}++impl Default for UserAgentRules {+ fn default() -> Self {+ Self {+ store: RuleStore::new(),+ sheets: SmallVec::new(),+ }+ }+}++/// A user agent sheet the process published.+#[derive(Clone)]+struct UserAgentSheet {+ /// The identity of the native sheet the rules were compiled from.+ source_identity: u64,+ sheet: SheetID,+ /// What a document learns of the selectors of the sheet's rules as it attaches the sheet.+ selectors: Arc<SelectorSummary>,+ /// The references that keep the names the sheet's rules declare interned.+ _atoms: ForkShared<DocumentAtoms>,+}++impl UserAgentRules {+ /// The rules, numbered as [`RuleID::in_user_agent_rules`] answers.+ pub(in crate::css::style) fn store(&self) -> &RuleStore {+ &self.store+ }++ /// The table holding what this one holds and `store`, the rule store that went on to hold the+ /// rules of the sheet `sheet`, published from the native sheet `source_identity`.+ pub(in crate::css::style) fn with_sheet(+ &self,+ store: RuleStore,+ sheet: SheetID,+ source_identity: u64,+ selectors: SelectorSummary,+ atoms: ForkShared<DocumentAtoms>,+ ) -> Self {+ let mut sheets = self.sheets.clone();+ sheets.push(UserAgentSheet {+ source_identity,+ sheet,+ selectors: Arc::new(selectors),+ _atoms: atoms,+ });+ Self { store, sheets }+ }++ /// The sheet published from the native sheet `source_identity`.+ pub(in crate::css::style) fn sheet_of_source(&self, source_identity: u64) -> Option<SheetID> {+ self.sheets+ .iter()+ .find(|sheet| sheet.source_identity == source_identity)+ .map(|sheet| sheet.sheet)+ }++ /// What the selectors of the rules of `sheet` say to a document attaching it.+ pub(in crate::css::style) fn selector_summary(&self, sheet: SheetID) -> Arc<SelectorSummary> {+ let sheet = self.sheets.iter().find(|candidate| candidate.sheet == sheet);+ Arc::clone(&sheet.expect("the process published the sheet").selectors)+ }++ /// The bytes of the table, the first time `sizer` reaches each thing it holds.+ pub(in crate::css::style) fn heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {+ self.store.heap_size(sizer) + self.sheets.len() * size_of::<UserAgentSheet>()+ }++ /// The bytes of the declarations of the rules, the first time `sizer` reaches each.+ pub(in crate::css::style) fn declarations_heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {+ self.store.declarations_heap_size(sizer)+ }+}++/// Which of the process's user agent rules decide in a document: every rule of its contributing+/// user agent sheets, in cascade order, but those its media leave out. Documents alike in this+/// decide with one user agent index.+#[derive(Clone, PartialEq, Eq)]+pub(in crate::css::style) struct UserAgentVariant {+ /// The contributing sheets, in cascade order, in the numbers of the process's rules.+ sheets: SmallVec<[SheetID; 4]>,+ /// The rules left out, in the numbers of the process's rules, in increasing order.+ left_out: SmallVec<[RuleID; 8]>,+}++impl UserAgentVariant {+ /// The rules of the sheet published from the native sheet `source_identity` alone, but those+ /// compiled from the native rules `failing`, whose conditions do not hold.+ pub(in crate::css::style) fn of_published_sheet(+ rules: &UserAgentRules,+ source_identity: u64,+ failing: &[u64],+ ) -> Option<Self> {+ let sheet = rules.sheet_of_source(source_identity)?;+ let mut left_out: SmallVec<[RuleID; 8]> = failing+ .iter()+ .filter_map(|&identity| rules.store.native.identities.get(&identity))+ .collect();+ left_out.sort_unstable();+ let mut sheets = SmallVec::new();+ sheets.push(sheet);+ Some(Self { sheets, left_out })+ }++ pub(in crate::css::style) fn sheets(&self) -> &[SheetID] {+ &self.sheets+ }++ /// Whether the media of the documents of the variant leave `rule` out.+ pub(in crate::css::style) fn leaves_out(&self, rule: RuleID) -> bool {+ self.left_out.binary_search(&rule).is_ok()+ }++ pub(in crate::css::style) fn heap_size(&self) -> usize {+ crate::heap_size::small_vec_bytes(&self.sheets) + crate::heap_size::small_vec_bytes(&self.left_out)+ }+}++/// What a document holds of the process's user agent rules.+#[derive(Clone)]+pub(super) struct UserAgentBinding {+ rules: Arc<UserAgentRules>,+ /// The document's sheet each published sheet it attached is, by the published sheet's number.+ sheets: SmallVec<[(SheetID, SheetID); 4]>,+ /// The rules whose conditions do not hold in the document, in increasing order.+ left_out: SmallVec<[RuleID; 8]>,+}++impl UserAgentBinding {+ #[inline]+ pub(super) fn store(&self) -> &RuleStore {+ &self.rules.store+ }++ /// The document's sheet the rule `rule` of the process is in.+ pub(super) fn sheet_of(&self, rule: RuleID) -> SheetID {+ let published = self.store().rule_sheet(rule);+ let found = self.sheets.iter().find(|(sheet, _)| *sheet == published);+ found.expect("a document names the rules of the sheets it holds").1+ }++ /// Whether the conditions of `rule`, as the document names it, hold in the document.+ pub(super) fn rule_conditions_hold(&self, rule: RuleID) -> bool {+ let rule = rule.in_user_agent_rules().expect("a user agent rule");+ self.left_out.binary_search(&rule).is_err()+ }++ /// Note whether the conditions of `rule` hold in the document, answering whether that moved.+ pub(super) fn set_rule_conditions_hold(&mut self, rule: RuleID, conditions_hold: bool) -> bool {+ let rule = rule.in_user_agent_rules().expect("a user agent rule");+ match (self.left_out.binary_search(&rule), conditions_hold) {+ (Ok(place), true) => {+ self.left_out.remove(place);+ true+ }+ (Err(place), false) => {+ self.left_out.insert(place, rule);+ true+ }+ _ => false,+ }+ }++ pub(super) fn heap_size(&self) -> usize {+ crate::heap_size::small_vec_bytes(&self.sheets) + crate::heap_size::small_vec_bytes(&self.left_out)+ }+}++impl RuleStore {+ #[inline]+ pub(super) fn user_agent_binding(&self) -> &UserAgentBinding {+ self.user_agent+ .as_ref()+ .expect("a document names the rules of the sheets it holds")+ }++ pub(super) fn user_agent_binding_mut(&mut self) -> &mut UserAgentBinding {+ self.user_agent+ .as_mut()+ .expect("a document names the rules of the sheets it holds")+ }++ /// Have `sheet`, a sheet of the document that holds no rules, stand for `published`, a sheet of+ /// `rules`, the newest table of the process's user agent rules.+ pub(in crate::css::style) fn bind_user_agent_sheet(+ &mut self,+ sheet: SheetID,+ rules: Arc<UserAgentRules>,+ published: SheetID,+ ) {+ self.sheets[sheet.0 as usize].user_agent = Some(published);+ match &mut self.user_agent {+ Some(binding) => {+ binding.rules = rules;+ binding.sheets.push((published, sheet));+ }+ None => {+ let mut sheets = SmallVec::new();+ sheets.push((published, sheet));+ self.user_agent = Some(UserAgentBinding {+ rules,+ sheets,+ left_out: SmallVec::new(),+ });+ }+ }+ }++ /// The process's user agent rules the document holds.+ pub(in crate::css::style) fn user_agent_rules(&self) -> Option<&Arc<UserAgentRules>> {+ self.user_agent.as_ref().map(|binding| &binding.rules)+ }++ /// Which of the process's user agent rules decide in the document, if any can.+ pub(in crate::css::style) fn user_agent_variant(&self) -> Option<UserAgentVariant> {+ let binding = self.user_agent.as_ref()?;+ let sheets: SmallVec<[SheetID; 4]> = self+ .sheets_in_scope(super::TreeScopeID::DOCUMENT)+ .iter()+ .filter(|&&sheet| self.sheet_contributes(sheet))+ .filter_map(|&sheet| self.sheets[sheet.0 as usize].user_agent)+ .collect();+ (!sheets.is_empty()).then(|| UserAgentVariant {+ sheets,+ left_out: binding.left_out.clone(),+ })+ }++ /// The document's name of the user agent rule compiled from the native rule `identity`.+ pub(in crate::css::style) fn user_agent_rule_of_identity(&self, identity: u64) -> Option<RuleID> {+ let binding = self.user_agent.as_ref()?;+ let rule = binding.store().native.identities.get(&identity)?;+ // NB: The process's table holds sheets the document may not have attached.+ let published = binding.store().rule_sheet(rule);+ binding+ .sheets+ .iter()+ .any(|(sheet, _)| *sheet == published)+ .then(|| RuleID::of_user_agent(rule))+ }++ /// The native rule `rule` was compiled from, as the document names it.+ pub(in crate::css::style) fn native_target(&self, rule: RuleID) -> Option<super::native::NativeRuleTargetRef<'_>> {+ match rule.in_user_agent_rules() {+ Some(rule) => self.user_agent.as_ref()?.store().native.targets.get(&rule),+ None => self.native.targets.get(&rule),+ }+ }+}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/rules.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/rules.rsnew file mode 100644index 00000000000..9e91f442f20--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/rules.rs@@ -0,0 +1,3712 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The rule index: every attached style rule entry of a tree scope, bucketed by the most selective+//! key its subject compound requires, with the ancestor keys its combinator chain requires.+//!+//! An entry keeps its number for as long as the index lives. A change to some rules indexes those+//! rules again alone: the entries of a rule that left or changed die, leaving every bucket, and the+//! entries of a rule that arrived or changed are appended. What the index indexed is kept by the+//! rule store's identities of the rules and sheets, so the rules a change does not name, such as+//! the user agent's, are never indexed again for it.+//!+//! Shadow trees whose ordered sheets and layers are the same decide with the same entries, which+//! they share as a group: a page with many instances of one component indexes its rules once.+//!+//! NB: An update works at the granularity of the rules a change names: an appended sheet's rules+//! join the buckets the index has, and nothing else is indexed again.++use super::super::index::dispatch_bloom_bit;+use super::super::selector_analysis::{EntryFacts, collect_tested_ids, state_dispatch_key, subject_dispatch_keys};+use super::super::weak_pool::WeakPool;+use super::super::*;+use super::bloom::AncestorHashes;+use super::extent_map::{Extent, ExtentMap, FrozenExtentMap, PagedExtentMap};+use super::rule_changes::{Regrouped, RuleIndexChanges, StayedEntry};+use super::rule_store::UserAgentVariant;+use super::shared_pages::{PagePool, SharedPages};+use crate::css::container_conditions::ContainerConditionsData;+use crate::css::selector::Specificity;+use smallvec::SmallVec;+use std::hash::Hash;+use std::sync::Arc;++/// The container conditions a rule applies under, in the rule index's gates.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub(super) struct ContainerGateID(std::num::NonZeroU32);++/// The number of a document's first entry of its own. The numbers below it are those of the user+/// agent index the document shares, so a document's own entries keep their numbers whichever user+/// agent index it shares.+pub(super) const FIRST_DOCUMENT_ENTRY: u32 = 1024;++/// The tree scopes whose sheets an entry is of: the document, or a group of shadow trees deciding+/// with the same ordered sheets and layers, which share the entries of those sheets.+#[derive(Clone, Copy, Debug, Hash, PartialEq, Eq, PartialOrd, Ord)]+pub(super) struct ScopeGroupID(u32);++impl ScopeGroupID {+ /// The document's own sheets.+ pub(super) const DOCUMENT: Self = Self(0);+}++/// The entries a group of shadow trees shares, with what the trees have alike.+#[derive(Clone)]+pub(super) struct ScopeGroup {+ pub(super) index: ScopeIndex,+ /// The trees of the group, in the order they joined it. The first ranks the layers of the+ /// entries, which are the same in every tree of the group.+ scopes: SmallVec<[TreeScopeID; 1]>,+ /// The sheets attached to each tree, in cascade order, the entries of which rank by their+ /// place here.+ sheets: Box<[SheetID]>,+ /// The ranks of the layers of each tree.+ layer_ranks: HashMap<CascadeLayerID, u32>,+}++/// The rule an entry is of: a rule of the document's rule store, or of the process's user agent+/// rules, as every document names those.+#[derive(Clone, Copy, PartialEq, Eq)]+struct EntryRule(u32);++impl EntryRule {+ fn document(rule: RuleID) -> Self {+ assert!(rule.in_user_agent_rules().is_none(), "rule identity space exhausted");+ Self(rule.0)+ }++ fn user_agent(rule: RuleID) -> Self {+ Self(RuleID::of_user_agent(rule).0)+ }+}++/// The number of an [`EntryPlacement`] among those of the entries it numbers.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub(super) struct PlacementID(u32);++/// Where the entries of the rules of one layer of one sheet deciding in one group of scopes+/// decide: every such entry shares the origin, group and ranks it holds, which move here alone+/// when the order of the sheets or layers does.+///+/// NB: An entry holds its rule's position alone, and leaves the sheet's origin, scope and layer+/// order to its placement, which every entry of the sheet and layer shares.+#[derive(Clone, Copy)]+pub(super) struct EntryPlacement {+ pub(super) origin: CascadeOrigin,+ pub(super) group: ScopeGroupID,+ pub(super) layer_rank: u64,+ pub(super) sheet_rank: u64,+ layer: CascadeLayerID,+}++/// Where the selector of an entry is: the list of its rule, and where it starts in the list's arena.+#[derive(Clone)]+pub(in crate::css::style) struct EntrySource {+ selectors: crate::css::selector::SelectorListRef,+ at: crate::css::selector_arena::ComponentOffset,+}++impl EntrySource {+ pub(in crate::css::style) fn selector(&self) -> crate::css::selector::Selector<'_> {+ self.selectors.selector_at(self.at)+ }++ /// What tells the selector from another for as long as the process lives.+ fn identity(&self) -> crate::css::selector_arena::SelectorKey {+ crate::css::selector_arena::SelectorKey {+ arena: self.selectors.serial(),+ at: self.at,+ }+ }+}++/// What an entry's pseudo-element kind is for an entry styling the element itself.+pub(super) const ELEMENT_PSEUDO_KIND: u8 = u8::MAX;++/// The entries the selector list `selectors` makes: one for each selector, and a second for a+/// selector styling every search text match, for the current one; with the specificity and the+/// kind of pseudo-element each styles, or `ELEMENT_PSEUDO_KIND` for the element itself.+pub(in crate::css::style) fn entries_of(+ selectors: &crate::css::selector::SelectorListRef,+) -> impl Iterator<Item = (crate::css::selector::Selector<'_>, Specificity, u8)> + '_ {+ use crate::css::selector::PseudoElementType;+ selectors.iter().flat_map(move |selector| {+ let specificity = selector.specificity();+ let kind = |pseudo_element: Option<PseudoElementType>| {+ pseudo_element.map_or(ELEMENT_PSEUDO_KIND, |kind| {+ u8::try_from(kind as u16).unwrap_or(ELEMENT_PSEUDO_KIND - 1)+ })+ };+ let current = selector+ .styles_every_search_text_match()+ .then(|| (selector, specificity, kind(Some(PseudoElementType::SearchTextCurrent))));+ std::iter::once((selector, specificity, kind(selector.target_pseudo_element()))).chain(current)+ })+}++/// One top-level complex selector of one attached style rule.+#[derive(Clone, Copy)]+pub(super) struct IndexedEntry {+ rule: EntryRule,+ /// Where the entry decides, among the placements of the entries numbering it.+ placement: PlacementID,+ /// The entry's selector, in the space of the index holding the entry.+ selector: SelectorRef,+ specificity: PackedSpecificity,+ pub(super) rule_rank: u64,+ /// The kind of pseudo-element the entry styles, or `ELEMENT_PSEUDO_KIND` for the element itself.+ pub(super) pseudo_kind: u8,+ flags: EntryFlags,+}++// NB: Every attached style rule's selector has one, in every document and group of scopes it decides+// in, so what grows it grows every index. Its selector is a reference into the index's space,+// and the container conditions of the few gated rules are the index's to say, by rule.+const _: () = assert!(size_of::<IndexedEntry>() == 32);++/// The specificity of a selector packed into one word: its ids, classes and types counted in eight+/// bits each, from the most significant down, so that packed specificities compare as the+/// specificities do.+///+/// INTEROP: Other engines count each part of a specificity in eight bits too, saturating at 255.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]+struct PackedSpecificity(u32);++impl PackedSpecificity {+ fn pack(specificity: Specificity) -> Self {+ Self(specificity.packed())+ }++ fn unpacked(self) -> Specificity {+ let part = |shift: u32| ((self.0 >> shift) & 0xff) as u16;+ Specificity {+ ids: part(16),+ classes: part(8),+ types: part(0),+ }+ }+}++/// The yes-or-no facts of an [`IndexedEntry`], one bit each.+#[derive(Clone, Copy, PartialEq, Eq, Hash)]+struct EntryFlags(u8);++impl EntryFlags {+ const SCOPED: u8 = 1 << 0;+ /// The number was of a segment the index let go of, which took the entry's selector with it.+ const SELECTOR_GONE: u8 = 1 << 7;+ /// The entry can match one of two elements and not the other where the style sharing key+ /// holds for both.+ const REVALIDATES: u8 = 1 << 1;+ /// The rule declares custom properties.+ const DECLARES_CUSTOM_PROPERTIES: u8 = 1 << 2;+ /// The rule declares something important.+ const DECLARES_IMPORTANT: u8 = 1 << 3;+ /// The entry is indexed: one whose rule left or changed is in no bucket, and keeps its number+ /// until the index is built again.+ const LIVE: u8 = 1 << 4;+ /// The rule applies under container conditions, which the index holds by rule.+ const GATED: u8 = 1 << 5;+ /// The entry stands for the number of an entry a segment the index binds holds, or for a+ /// number before or after such entries that no entry has.+ const BOUND: u8 = 1 << 6;++ fn has(self, flag: u8) -> bool {+ self.0 & flag != 0+ }+}++impl IndexedEntry {+ /// What tells the entry from another: its selector by its reference in the index's space, and+ /// the rest. Two indexes holding equal entries hold them alike for their own spaces.+ fn identity(&self) -> impl Eq + Hash + '_ {+ let Self {+ rule,+ placement,+ selector,+ specificity,+ rule_rank,+ pseudo_kind,+ flags,+ } = self;+ (+ rule.0,+ *selector,+ (*specificity, *placement, *rule_rank, *pseudo_kind, *flags),+ )+ }++ /// What stands in the document's entries for the number of an entry a bound segment holds, alike+ /// in every document, so that the pages of a segment's numbers are one page of the process.+ const BOUND_NUMBER: Self = Self {+ rule: EntryRule(0),+ placement: PlacementID(0),+ selector: SelectorRef(0),+ specificity: PackedSpecificity(0),+ rule_rank: 0,+ pseudo_kind: ELEMENT_PSEUDO_KIND,+ flags: EntryFlags(EntryFlags::BOUND),+ };++ pub(super) fn declares_important(&self) -> bool {+ self.flags.has(EntryFlags::DECLARES_IMPORTANT)+ }++ pub(super) fn live(&self) -> bool {+ self.flags.has(EntryFlags::LIVE)+ }++ fn kill(&mut self) {+ self.flags.0 &= !EntryFlags::LIVE;+ }+}++/// An entry read in place where it is held: in the entries of the index numbering it or of the+/// user agent index, or in the segment the index binds, whose binding says the rest of it.+#[derive(Clone, Copy)]+pub(super) enum EntryView<'a> {+ /// An entry of the index's own entries, or of the user agent index's where `user_agent`.+ Held { entry: &'a IndexedEntry, user_agent: bool },+ /// An entry a bound segment holds.+ Bound {+ bound: &'a BoundSegment,+ entry: &'a SegmentEntry,+ /// Whether the entry died for the index binding the segment, which the segment knows nothing of.+ dead: bool,+ },+}++/// What `entry`, held by the document or by a segment, says alike in both of its shapes.+macro_rules! of_either_entry {+ ($view:expr, $entry:ident => $read:expr) => {+ match $view {+ EntryView::Held { entry: $entry, .. } => $read,+ EntryView::Bound { entry: $entry, .. } => $read,+ }+ };+}++impl EntryView<'_> {+ fn flags(&self) -> EntryFlags {+ match self {+ Self::Held { entry, .. } => entry.flags,+ Self::Bound { entry, dead: false, .. } => entry.flags,+ Self::Bound { entry, dead: true, .. } => EntryFlags(entry.flags.0 & !EntryFlags::LIVE),+ }+ }++ /// The kind of pseudo-element the entry styles, or `ELEMENT_PSEUDO_KIND` for the element itself.+ pub(super) fn pseudo_kind(&self) -> u8 {+ of_either_entry!(self, entry => entry.pseudo_kind)+ }++ pub(super) fn rule_rank(&self) -> u64 {+ of_either_entry!(self, entry => entry.rule_rank)+ }++ /// The entry's selector, in the space of the index or segment holding the entry.+ fn selector(&self) -> SelectorRef {+ of_either_entry!(self, entry => entry.selector)+ }++ fn rule(&self) -> EntryRule {+ match self {+ Self::Held { entry, .. } => entry.rule,+ Self::Bound { bound, entry, .. } => EntryRule::document(RuleID(bound.first_rule.0 + entry.rule)),+ }+ }++ pub(super) fn specificity(&self) -> Specificity {+ of_either_entry!(self, entry => entry.specificity.unpacked())+ }++ /// Whether the entry styles a pseudo-element.+ pub(super) fn pseudo_element(&self) -> bool {+ self.pseudo_kind() != ELEMENT_PSEUDO_KIND+ }++ pub(super) fn scoped(&self) -> bool {+ self.flags().has(EntryFlags::SCOPED)+ }++ pub(super) fn revalidates(&self) -> bool {+ self.flags().has(EntryFlags::REVALIDATES)+ }++ pub(super) fn declares_custom_properties(&self) -> bool {+ self.flags().has(EntryFlags::DECLARES_CUSTOM_PROPERTIES)+ }++ pub(super) fn declares_important(&self) -> bool {+ self.flags().has(EntryFlags::DECLARES_IMPORTANT)+ }++ pub(super) fn live(&self) -> bool {+ self.flags().has(EntryFlags::LIVE)+ }++ fn gated(&self) -> bool {+ self.flags().has(EntryFlags::GATED)+ }++ /// The entry as the document has it, but for a bound entry's selector, which is in the+ /// segment's space.+ fn indexed(&self) -> IndexedEntry {+ match *self {+ Self::Held { entry, .. } => *entry,+ Self::Bound { bound, entry, .. } => IndexedEntry {+ rule: self.rule(),+ placement: bound.placements[usize::from(entry.placement)],+ selector: entry.selector,+ specificity: entry.specificity,+ rule_rank: entry.rule_rank,+ pseudo_kind: entry.pseudo_kind,+ flags: self.flags(),+ },+ }+ }+}++impl PartialEq for IndexedEntry {+ fn eq(&self, other: &Self) -> bool {+ self.identity() == other.identity()+ }+}++impl Hash for IndexedEntry {+ fn hash<H: std::hash::Hasher>(&self, state: &mut H) {+ self.identity().hash(state);+ }+}++/// One entry of a rule bucket, on its way into [`Buckets`], with the keys some ancestor of a matching+/// subject necessarily carries, and its selector.+#[derive(Clone, Copy)]+pub(super) struct BucketEntry {+ ancestor_hashes: AncestorHashes,+ /// The entry's number, from the first of the segment where the buckets are a segment's, with+ /// [`Self::IN_OTHER_BUCKETS`], [`Self::SCOPED`], [`Self::COVERED`] and+ /// [`Self::HAS_SIBLING_KEY`].+ entry: u32,+ /// The entry's selector, in the space of the buckets' part.+ selector: SelectorRef,+ /// The key every earlier sibling of a subject right of `~` carries one of, where+ /// [`Self::HAS_SIBLING_KEY`] says the entry has one.+ sibling_key: u32,+ /// The dispatch bloom bits of the ids and classes the subject compound tests, which an element+ /// lacking any of cannot match.+ subject_bloom: u64,+}++const _: () = assert!(size_of::<BucketEntry>() == 32);++impl BucketEntry {+ /// The entry is in more buckets than this one, which an element can reach it by.+ const IN_OTHER_BUCKETS: u32 = 1 << 31;+ /// The entry's rule is inside `@scope`, whose levels matching reads from the entry.+ const SCOPED: u32 = 1 << 30;+ /// The bucket's key alone proves the selector: an element reaching the entry by its key matches.+ const COVERED: u32 = 1 << 29;+ /// The entry has a [`Self::sibling_key`].+ const HAS_SIBLING_KEY: u32 = 1 << 28;+ /// The bucket's key alone proves the subject compound of the selector, which an element reaching+ /// the entry by its key is matched left of, as it is the only thing the compound tests.+ const SUBJECT_COVERED: u32 = 1 << 26;+ /// [`Self::SUBJECT_COVERED`], where the element's tag is its own ASCII-lowercase form.+ const SUBJECT_COVERED_FOR_A_LOWERCASE_TAG: u32 = 1 << 25;+ /// The bucket's key proves the selector for an element whose tag is its own ASCII-lowercase+ /// form: the selector is a type selector alone, written in ASCII lowercase.+ const COVERED_FOR_A_LOWERCASE_TAG: u32 = 1 << 27;+ const FLAGS: u32 = Self::IN_OTHER_BUCKETS+ | Self::SCOPED+ | Self::COVERED+ | Self::HAS_SIBLING_KEY+ | Self::COVERED_FOR_A_LOWERCASE_TAG+ | Self::SUBJECT_COVERED+ | Self::SUBJECT_COVERED_FOR_A_LOWERCASE_TAG;++ /// The slot of the entry `entry` of `selector`, inside `@scope` where `scoped`.+ fn new(selector: crate::css::selector::Selector<'_>, entry: u32, selector_ref: SelectorRef, scoped: bool) -> Self {+ assert!(entry & Self::FLAGS == 0, "rule entry space exhausted");+ let sibling_key = super::bloom::earlier_sibling_key(selector);+ let mut flags = 0;+ if scoped {+ flags |= Self::SCOPED;+ }+ match is_covered_by_its_key(selector) {+ _ if scoped => {}+ Covered::No => {}+ Covered::Always => flags |= Self::COVERED,+ Covered::ForALowercaseTag => flags |= Self::COVERED_FOR_A_LOWERCASE_TAG,+ }+ match subject_is_covered_by_its_key(selector) {+ _ if scoped => {}+ Covered::No => {}+ Covered::Always => flags |= Self::SUBJECT_COVERED,+ Covered::ForALowercaseTag => flags |= Self::SUBJECT_COVERED_FOR_A_LOWERCASE_TAG,+ }+ if sibling_key.is_some() {+ flags |= Self::HAS_SIBLING_KEY;+ }+ Self {+ ancestor_hashes: AncestorHashes::required_left_of(super::super::selector_analysis::subject_compound(+ selector,+ )),+ entry: entry | flags,+ selector: selector_ref,+ sibling_key: sibling_key.unwrap_or(0),+ subject_bloom: selector.required_dispatch_bloom(),+ }+ }+}++/// The entries reached by each dispatch key.+///+/// A slot is one word for an entry its key proves, its number and flags, which no element reaching+/// it is rejected from. Any other is [`BUCKET_SLOT_WORDS`] words at fixed places, so a scan rejecting+/// candidates reads what it rejects on with nothing to decode.+///+/// NB: The buckets of a sheet segment never change once it is built, and take the smaller shape.+#[derive(Clone)]+pub(super) enum Buckets {+ Growing(ExtentMap<DispatchKey, u32>),+ Frozen(FrozenExtentMap<DispatchKey, u32>),+}++impl Default for Buckets {+ fn default() -> Self {+ Self::Growing(ExtentMap::default())+ }+}++impl Buckets {+ /// The slots of `key`, where it has any.+ #[inline]+ pub(super) fn get(&self, key: &DispatchKey) -> Option<BucketSlots<'_>> {+ let words = match self {+ Self::Growing(map) => map.get(key),+ Self::Frozen(map) => map.get(key),+ };+ words.map(|words| BucketSlots { words })+ }++ pub(super) fn is_empty(&self) -> bool {+ match self {+ Self::Growing(map) => map.is_empty(),+ Self::Frozen(map) => map.is_empty(),+ }+ }++ pub(super) fn keys(&self) -> Box<dyn Iterator<Item = &DispatchKey> + '_> {+ match self {+ Self::Growing(map) => Box::new(map.keys()),+ Self::Frozen(map) => Box::new(map.keys()),+ }+ }++ fn heap_size(&self) -> usize {+ match self {+ Self::Growing(map) => map.heap_size(),+ Self::Frozen(map) => map.heap_size(),+ }+ }++ fn shrink_to_fit(&mut self) {+ if let Self::Growing(map) = self {+ map.shrink_to_fit();+ }+ }++ fn freeze(&mut self) {+ if let Self::Growing(map) = self {+ *self = Self::Frozen(FrozenExtentMap::of(std::mem::take(map)));+ }+ }++ fn has_slack(&self) -> bool {+ matches!(self, Self::Growing(map) if map.has_slack())+ }++ fn growing(&mut self) -> &mut ExtentMap<DispatchKey, u32> {+ match self {+ Self::Growing(map) => map,+ Self::Frozen(_) => unreachable!("the buckets of a segment do not change"),+ }+ }++ fn push(&mut self, key: DispatchKey, slot: &BucketEntry) {+ let words = self.growing();+ if slot.entry & BucketEntry::COVERED != 0 {+ words.push(key, slot.entry);+ return;+ }+ // NB: A key proving the subject leaves nothing an element reaching the slot could lack.+ let subject_bloom = match slot.entry & BucketEntry::SUBJECT_COVERED != 0 {+ true => 0,+ false => slot.subject_bloom,+ };+ let [first_hash, second_hash, third_hash] = slot.ancestor_hashes.packed_words();+ for word in [+ slot.entry,+ slot.selector.0,+ subject_bloom as u32,+ (subject_bloom >> 32) as u32,+ first_hash,+ second_hash,+ third_hash,+ slot.sibling_key,+ ] {+ words.push(key, word);+ }+ }++ /// Take the slots of the entry `entry` out of the list of `key`.+ fn remove(&mut self, key: &DispatchKey, entry: u32) {+ let Some(kept) = self.get(key).map(|slots| {+ slots+ .filter(|slot| slot.entry() != entry)+ .map(|slot| slot.entry_to_hold())+ .collect::<Vec<_>>()+ }) else {+ return;+ };+ self.growing().remove(key);+ for slot in &kept {+ self.push(*key, slot);+ }+ }++ #[cfg(test)]+ fn count(&self) -> usize {+ let keys: Vec<DispatchKey> = self.keys().copied().collect();+ keys.iter().filter_map(|key| self.get(key)).map(Iterator::count).sum()+ }+}++/// How many words a slot of an entry its key does not prove takes, and where it holds what.+const BUCKET_SLOT_WORDS: usize = 8;+const BUCKET_SLOT_SELECTOR: usize = 1;+const BUCKET_SLOT_BLOOM_LOW: usize = 2;+const BUCKET_SLOT_BLOOM_HIGH: usize = 3;+const BUCKET_SLOT_HASHES: usize = 4;+const BUCKET_SLOT_SIBLING_KEY: usize = 7;++/// The slots of one bucket, as [`Buckets`] holds them.+#[derive(Clone)]+pub(super) struct BucketSlots<'a> {+ words: &'a [u32],+}++impl<'a> Iterator for BucketSlots<'a> {+ type Item = BucketSlot<'a>;++ #[inline(always)]+ fn next(&mut self) -> Option<BucketSlot<'a>> {+ let &first = self.words.first()?;+ if first & BucketEntry::COVERED != 0 {+ self.words = &self.words[1..];+ // NB: Nothing rejects an element reaching a proven entry: it requires no bit of an element's, and no key+ // of its ancestors or earlier siblings.+ return Some(BucketSlot {+ entry: first,+ words: &[0; BUCKET_SLOT_WORDS],+ });+ }+ let (words, rest) = self+ .words+ .split_first_chunk::<BUCKET_SLOT_WORDS>()+ .expect("a slot holds the words of a slot");+ self.words = rest;+ Some(BucketSlot { entry: first, words })+ }+}++/// One entry of a rule bucket, read where [`Buckets`] holds it, so that a candidate rejected on its+/// subject's bloom loads that and nothing more.+#[derive(Clone, Copy)]+pub(super) struct BucketSlot<'a> {+ entry: u32,+ words: &'a [u32; BUCKET_SLOT_WORDS],+}++impl BucketSlot<'_> {+ /// The dispatch bloom bits of the ids and classes the subject compound tests, which an element+ /// lacking any of cannot match.+ #[inline(always)]+ pub(super) fn subject_bloom(&self) -> u64 {+ u64::from(self.words[BUCKET_SLOT_BLOOM_LOW]) | u64::from(self.words[BUCKET_SLOT_BLOOM_HIGH]) << 32+ }++ /// The keys some ancestor of a matching subject necessarily carries.+ #[inline(always)]+ pub(super) fn ancestor_hashes(&self) -> AncestorHashes {+ AncestorHashes::from_packed_words([+ self.words[BUCKET_SLOT_HASHES],+ self.words[BUCKET_SLOT_HASHES + 1],+ self.words[BUCKET_SLOT_HASHES + 2],+ ])+ }++ /// The entry's selector, in the space of the buckets' part, where the entry is not [`Self::covered`].+ #[inline(always)]+ pub(super) fn selector(&self) -> SelectorRef {+ SelectorRef(self.words[BUCKET_SLOT_SELECTOR])+ }++ /// The entry's number, from the first of the segment where the buckets are a segment's.+ #[inline(always)]+ pub(super) fn entry(&self) -> u32 {+ self.entry & !BucketEntry::FLAGS+ }++ #[inline(always)]+ pub(super) fn in_other_buckets(&self) -> bool {+ self.entry & BucketEntry::IN_OTHER_BUCKETS != 0+ }++ #[inline(always)]+ pub(super) fn scoped(&self) -> bool {+ self.entry & BucketEntry::SCOPED != 0+ }++ /// Whether the bucket's key proves the selector for an element reaching the entry by it, whose+ /// tag is its own ASCII-lowercase form where `tag_is_lowercase`.+ #[inline(always)]+ pub(super) fn covered(&self, tag_is_lowercase: bool) -> bool {+ self.entry & BucketEntry::COVERED != 0+ || (tag_is_lowercase && self.entry & BucketEntry::COVERED_FOR_A_LOWERCASE_TAG != 0)+ }++ /// Whether the bucket's key proves the subject compound for an element reaching the entry by it,+ /// whose tag is its own ASCII-lowercase form where `tag_is_lowercase`.+ #[inline(always)]+ pub(super) fn subject_covered(&self, tag_is_lowercase: bool) -> bool {+ self.entry & BucketEntry::SUBJECT_COVERED != 0+ || (tag_is_lowercase && self.entry & BucketEntry::SUBJECT_COVERED_FOR_A_LOWERCASE_TAG != 0)+ }++ /// The key an earlier sibling of a matching subject carries, where the entry has one.+ #[inline(always)]+ pub(super) fn sibling_key(&self) -> Option<u32> {+ (self.entry & BucketEntry::HAS_SIBLING_KEY != 0).then_some(self.words[BUCKET_SLOT_SIBLING_KEY])+ }++ /// The entry as [`Buckets`] takes it.+ fn entry_to_hold(&self) -> BucketEntry {+ BucketEntry {+ ancestor_hashes: self.ancestor_hashes(),+ entry: self.entry,+ selector: self.selector(),+ sibling_key: self.words[BUCKET_SLOT_SIBLING_KEY],+ subject_bloom: self.subject_bloom(),+ }+ }+}++/// Whether an element reaching an entry by the key of its bucket matches its selector.+enum Covered {+ No,+ Always,+ /// Where the element's tag is its own ASCII-lowercase form: the bucket of a type selector is+ /// reached by an element's tag and by its folding.+ ForALowercaseTag,+}++/// Whether an element reaching `selector`'s entry by the key of its bucket matches it: the selector+/// is one simple selector alone, which the bucket is the key of, or styles a pseudo-element of the+/// element it describes and nothing more, and is of a sheet declaring no default namespace, which+/// would constrain the type it implies. That simple selector is an id or a class written in ASCII+/// lowercase, `*` or a type selector in any namespace, `:root`, or a state.+fn is_covered_by_its_key(selector: crate::css::selector::Selector<'_>) -> Covered {+ use crate::css::selector::Combinator;+ if selector.names_the_scope() || selector.namespaces().default.is_some() {+ return Covered::No;+ }+ // A pseudo-element alone in its compound, other than `::part()` and `::slotted()`, is of the+ // element the compound left of it describes, which is matched for it.+ let subject = match selector.target_pseudo_element() {+ None => selector,+ Some(_) => {+ let target = selector.first_compound();+ if target.simple_selectors.len() != 1+ || target.combinator != Combinator::PseudoElement+ || !matches!(+ super::super::component_matching::compound_target(&target),+ super::super::component_matching::CompoundTarget::Transparent+ )+ {+ return Covered::No;+ }+ match selector.left() {+ Some((_, left)) if !left.is_relative_anchor() => left,+ _ => return Covered::No,+ }+ }+ };+ if subject.left().is_some() {+ return Covered::No;+ }+ compound_is_covered_by_its_key(subject)+}++/// Whether an element reaching `selector`'s entry by the key of its bucket matches it, whatever it+/// is otherwise.+pub(super) fn proves_the_whole_selector(selector: crate::css::selector::Selector<'_>) -> bool {+ matches!(is_covered_by_its_key(selector), Covered::Always)+}++/// Whether an element reaching `selector`'s entry by the key of its bucket matches its subject+/// compound, whatever it takes of the elements left of it: the selector has compounds left of a+/// subject that [`compound_is_covered_by_its_key`], and has no target pseudo-element.+fn subject_is_covered_by_its_key(selector: crate::css::selector::Selector<'_>) -> Covered {+ if selector.names_the_scope()+ || selector.namespaces().default.is_some()+ || !selector.describes_its_subject()+ || !selector.left().is_some_and(|(_, left)| !left.is_relative_anchor())+ {+ return Covered::No;+ }+ compound_is_covered_by_its_key(selector)+}++/// Whether the first compound of `subject` is one simple selector the key of a bucket proves.+fn compound_is_covered_by_its_key(subject: crate::css::selector::Selector<'_>) -> Covered {+ use crate::css::selector::{NamespaceType, PseudoClassType, SimpleSelector};+ let mut simple_selectors = subject.first_compound().simple_selectors.iter();+ let (Some(simple), None) = (simple_selectors.next(), simple_selectors.next()) else {+ return Covered::No;+ };+ let any_namespace = |namespace: NamespaceType| matches!(namespace, NamespaceType::Default | NamespaceType::Any);+ match simple {+ SimpleSelector::Id(name) | SimpleSelector::Class(name) if name.is_ascii_lowercase => Covered::Always,+ SimpleSelector::Universal(name) if any_namespace(name.namespace_type) => Covered::Always,+ SimpleSelector::TagName(name) if name.name_is_ascii_lowercase && any_namespace(name.namespace_type) => {+ Covered::ForALowercaseTag+ }+ SimpleSelector::PseudoClass(pseudo_class)+ if pseudo_class.pseudo_class == PseudoClassType::Root+ || super::super::compiler::state_fact_for(pseudo_class.pseudo_class).is_some() =>+ {+ Covered::Always+ }+ _ => Covered::No,+ }+}++/// A selector the buckets of one part of a rule index address: the page of the part's space it+/// is in, and where it starts in the page.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+pub(super) struct SelectorRef(u32);++/// An arena of a selector space, by its place among the space's arenas.+#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]+struct ArenaSlot(u32);++/// How many components a page of a selector space spans, as a power of two.+const SELECTOR_PAGE_BITS: u32 = 12;++/// The selectors one part of a rule index addresses, its own buckets', a segment's or the user+/// agent index's: the arenas they live in, mapped into one space of 32-bit references in pages of+/// 4096 components. An arena whose selectors span several pages takes several, which need not+/// stand together. A reference resolves through the space that made it alone.+#[derive(Clone, Default)]+pub(super) struct SelectorSpace {+ /// One handle to each arena, which keeps it.+ arenas: Vec<crate::css::selector::SelectorListRef>,+ /// Whose each page is, and where it starts in that arena.+ pages: Vec<(ArenaSlot, crate::css::selector_arena::ComponentOffset)>,+ /// The slot of each arena, by its serial.+ slots: HashMap<crate::css::selector_arena::SelectorArenaSerial, ArenaSlot>,+ /// The page of each page start of each arena.+ page_of: HashMap<(ArenaSlot, crate::css::selector_arena::ComponentOffset), u32>,+}++impl SelectorSpace {+ /// The reference of the selector of `selectors`' arena starting at `at`.+ fn add(+ &mut self,+ selectors: &crate::css::selector::SelectorListRef,+ at: crate::css::selector_arena::ComponentOffset,+ ) -> SelectorRef {+ let arenas = &mut self.arenas;+ let slot = *self.slots.entry(selectors.serial()).or_insert_with(|| {+ arenas.push(selectors.clone());+ ArenaSlot(u32::try_from(arenas.len() - 1).expect("selector space exhausted"))+ });+ let (start, offset) = at.in_page(SELECTOR_PAGE_BITS);+ let pages = &mut self.pages;+ let page = *self.page_of.entry((slot, start)).or_insert_with(|| {+ pages.push((slot, start));+ u32::try_from(pages.len() - 1).expect("selector space exhausted")+ });+ assert!(page < 1 << (32 - SELECTOR_PAGE_BITS), "selector space exhausted");+ SelectorRef(page << SELECTOR_PAGE_BITS | offset)+ }++ /// The reference of the selector of an entry.+ fn add_entry(&mut self, source: &EntrySource) -> SelectorRef {+ self.add(&source.selectors, source.at)+ }++ /// The selector `selector` names.+ pub(super) fn resolve(&self, selector: SelectorRef) -> crate::css::selector::Selector<'_> {+ let source = self.locate(selector);+ self.arenas[source.0.0 as usize].selector_at(source.1)+ }++ /// Where the selector `selector` names is, held by its arena.+ fn source(&self, selector: SelectorRef) -> EntrySource {+ let (slot, at) = self.locate(selector);+ EntrySource {+ selectors: self.arenas[slot.0 as usize].clone(),+ at,+ }+ }++ fn locate(&self, selector: SelectorRef) -> (ArenaSlot, crate::css::selector_arena::ComponentOffset) {+ let (slot, start) = self.pages[(selector.0 >> SELECTOR_PAGE_BITS) as usize];+ (slot, start.into_page(selector.0 & ((1 << SELECTOR_PAGE_BITS) - 1)))+ }++ fn heap_size(&self) -> usize {+ use crate::heap_size::{map_bytes, vec_bytes};+ vec_bytes(&self.arenas) + vec_bytes(&self.pages) + map_bytes(&self.slots) + map_bytes(&self.page_of)+ }++ fn shrink_to_fit(&mut self) {+ self.arenas.shrink_to_fit();+ self.pages.shrink_to_fit();+ self.slots.shrink_to_fit();+ self.page_of.shrink_to_fit();+ }+}++/// The entries of one tree scope, bucketed once for each kind of element they can match: the+/// elements of the scope, the host of its shadow root, the elements slotted into its slots, and+/// the parts exposed to it. An entry is in the families its subject allows besides the first.+#[derive(Clone, Default)]+pub(super) struct ScopeIndex {+ /// Every entry, which the elements of the scope match.+ pub(super) own: Buckets,+ /// The entries of `own` that revalidate.+ pub(super) own_revalidation: Buckets,+ /// The entries whose subject can be the host of the scope's shadow root, for `:host`.+ pub(super) host: Buckets,+ /// The entries whose subject is an element slotted into the scope, for `::slotted()`.+ pub(super) slotted: Buckets,+ /// The entries whose subject is a part exposed to the scope, for `::part()`.+ pub(super) part: Buckets,+}++/// Rule entries bucketed by the keys their subjects can be reached by, per tree scope. An entry whose+/// subject can be reached by any of several keys is in each of their buckets; one with no dispatchable+/// key set is in the universal bucket, which every element reaches.+///+/// NB: Where a scope's shadow root is, how deeply it is nested and whether it decides with the+/// document's author sheets are facts of the tree, not of the sheets, so the matcher reads+/// them where it matches rather than the index holding them.+#[derive(Clone, Default)]+pub(super) struct RuleIndex {+ /// Every entry, numbered across scopes, the dead ones among them.+ pub(super) entries: IndexEntries,+ /// How many of `entries` are dead.+ pub(super) dead_entries: usize,+ /// The entries of the document's sheets, but for the user agent's, which the user agent index+ /// holds.+ pub(super) document: ScopeIndex,+ /// The entries of the document's user sheets, which also decide in every shadow tree that does+ /// not decide with the document's author sheets, as the user agent's do. An index of the+ /// entries some change brought holds the user agent's that arrived here too.+ pub(super) document_non_author: ScopeIndex,+ /// The entries of the sheets of the shadow trees with sheets of their own, by the group of+ /// trees with the same sheets that shares them.+ pub(super) groups: HashMap<ScopeGroupID, ScopeGroup>,+ /// The group of each shadow tree with sheets of its own.+ group_of_scope: HashMap<TreeScopeID, ScopeGroupID>,+ /// The groups whose trees have each list of sheets, which their layers tell apart.+ groups_by_sheets: HashMap<Box<[SheetID]>, SmallVec<[ScopeGroupID; 1]>>,+ /// The number of the next group.+ next_group: u32,+ /// The ids an entry that does not revalidate tests for. No such entry tells an element with any+ /// other id from one with none.+ pub(super) tested_ids: HashSet<StyleAtomID>,+ /// The selector entries this build or update analyzed for its buckets, those of a user agent+ /// index it built among them.+ pub(super) compiled_selectors: u64,+ /// The entries this build or update indexed, those of a user agent index it built among them.+ pub(super) indexed_entries: u64,+ /// Whether this build or update built the user agent index it shares, which no document of the+ /// process had built before.+ pub(super) built_user_agent_index: bool,+ /// The container conditions of the gated rules, each rule's once, innermost first.+ gates: Vec<Box<[Arc<ContainerConditionsData>]>>,+ /// Whether one of the gates asks a `style()` question, which reads the custom properties of+ /// any element above its subject.+ pub(super) gates_ask_container_style: bool,+ /// What the index indexed, by the rule store's identities.+ indexed: Indexed,+ /// The space the selectors of the index's own buckets are in.+ pub(super) selectors: SelectorSpace,+ /// The `@scope` levels the rule of each entry inside any is inside.+ entry_scopes: HashMap<u32, Arc<super::super::bridge::BoundScopeChain>>,+}++/// The placement of the entries of each layer of one sheet deciding in one group.+type LayerPlacements = SmallVec<[(CascadeLayerID, PlacementID); 1]>;++/// The entries of a rule index, by their numbers: those of the user agent index the document+/// shares below [`FIRST_DOCUMENT_ENTRY`], and the document's own from there on.+#[derive(Clone, Default)]+pub(super) struct IndexEntries {+ user_agent: Option<Arc<UserAgentIndex>>,+ /// The document's entries, in pages documents numbering their entries alike share.+ own: SharedPages<IndexedEntry>,+ /// The number of the first of `own`: zero in a user agent index, which has no other entries.+ first: u32,+ /// Where the entries of `own` decide, which the tree scopes of the sheet attachment each is of+ /// name: a sheet attached to several scopes, as a constructed sheet adopted by several shadow+ /// roots is, has its entries indexed once for each group of them.+ placements: Vec<EntryPlacement>,+ /// The placement of the entries of each layer of each sheet deciding in each group.+ placements_of_sheet: HashMap<(SheetID, ScopeGroupID), LayerPlacements>,+ /// The sheets whose entries are bucketed and kept in a segment the process shares, rather than+ /// in the index's own buckets and entries, in the order of their numbers.+ segments: Vec<BoundSegment>,+ /// The place among `segments` of the segment holding the entries of each page of `own`, or+ /// `NO_SEGMENT`: a segment's numbers end a page, so no page holds two segments' entries.+ segment_of_page: Vec<u32>,+}++const NO_SEGMENT: u32 = u32::MAX;++impl IndexEntries {+ /// Where the entry `id` decides.+ pub(super) fn placement(&self, id: usize) -> &EntryPlacement {+ self.placement_of(self.view(id))+ }++ /// Where the entry `view` decides.+ pub(super) fn placement_of(&self, view: EntryView<'_>) -> &EntryPlacement {+ match view {+ EntryView::Held {+ entry,+ user_agent: false,+ } => &self.placements[entry.placement.0 as usize],+ EntryView::Held {+ entry,+ user_agent: true,+ } => {+ &self+ .user_agent+ .as_ref()+ .expect("a user agent entry has its index")+ .index+ .entries+ .placements[entry.placement.0 as usize]+ }+ EntryView::Bound { bound, entry, .. } => {+ &self.placements[bound.placements[usize::from(entry.placement)].0 as usize]+ }+ }+ }++ /// The entry numbered `id`.+ pub(super) fn entry(&self, id: usize) -> IndexedEntry {+ self.get(id).expect("an entry has its number")+ }++ /// The entry numbered `id`, read in place.+ pub(super) fn view(&self, id: usize) -> EntryView<'_> {+ self.try_view(id).expect("an entry has its number")+ }++ /// The segment holding the entry `entry`, by its place among the index's.+ fn segment_holding(&self, entry: u32) -> Option<usize> {+ let own = entry.checked_sub(self.first)? as usize;+ let place = *self.segment_of_page.get(own / super::shared_pages::VALUES_PER_PAGE)?;+ (place != NO_SEGMENT && self.segments[place as usize].holds(entry)).then_some(place as usize)+ }++ /// Note which segment holds the entries of each page of `own`, once the segments moved.+ fn note_segment_pages(&mut self) {+ let pages = self.own.len().div_ceil(super::shared_pages::VALUES_PER_PAGE);+ self.segment_of_page.clear();+ self.segment_of_page.resize(pages, NO_SEGMENT);+ for (place, bound) in self.segments.iter().enumerate() {+ let start = (bound.first - self.first) as usize;+ let end = start + bound.segment.len() as usize;+ for page in start / super::shared_pages::VALUES_PER_PAGE..end.div_ceil(super::shared_pages::VALUES_PER_PAGE)+ {+ self.segment_of_page[page] = u32::try_from(place).expect("segment space exhausted");+ }+ }+ }++ /// Have the numbers from here on start a page of `own`, which the numbers of entries a bound+ /// segment holds fill.+ fn pad_to_page(&mut self) {+ while !self.own.len().is_multiple_of(super::shared_pages::VALUES_PER_PAGE) {+ self.own.push(IndexedEntry::BOUND_NUMBER);+ }+ }++ /// Where an entry of a rule of `layer` of `sheet` deciding in `group` decides, which `placement`+ /// says where none such was placed before.+ fn place(+ &mut self,+ sheet: SheetID,+ group: ScopeGroupID,+ layer: CascadeLayerID,+ placement: impl FnOnce() -> EntryPlacement,+ ) -> PlacementID {+ let of_sheet = self.placements_of_sheet.entry((sheet, group)).or_default();+ if let Some(&(_, id)) = of_sheet.iter().find(|(placed, _)| *placed == layer) {+ return id;+ }+ let id = PlacementID(u32::try_from(self.placements.len()).expect("entry placement space exhausted"));+ self.placements.push(placement());+ of_sheet.push((layer, id));+ id+ }++ /// Have `rank` rank the placements of the entries of `sheet` deciding in `group` anew.+ fn rank_placements_of(&mut self, sheet: SheetID, group: ScopeGroupID, mut rank: impl FnMut(&mut EntryPlacement)) {+ for &(_, id) in self.placements_of_sheet.get(&(sheet, group)).into_iter().flatten() {+ rank(&mut self.placements[id.0 as usize]);+ }+ }++ /// How many numbers there are: one past the greatest.+ pub(super) fn len(&self) -> usize {+ self.first as usize + self.own.len()+ }++ /// How many entries there are, the dead ones among them.+ pub(super) fn count(&self) -> usize {+ self.user_agent_count() + self.own.len()+ }++ pub(super) fn get(&self, id: usize) -> Option<IndexedEntry> {+ self.try_view(id).map(|view| view.indexed())+ }++ /// The entry numbered `id`, read in place where it is held, if any has the number.+ pub(super) fn try_view(&self, id: usize) -> Option<EntryView<'_>> {+ match id.checked_sub(self.first as usize) {+ Some(own) => {+ let entry = self.own.get(own)?;+ let held = EntryView::Held {+ entry,+ user_agent: false,+ };+ if !entry.flags.has(EntryFlags::BOUND) {+ return Some(held);+ }+ // NB: The padding after a segment's entries is of its last page, and is no entry.+ let id = u32::try_from(id).expect("rule entry space exhausted");+ Some(self.segment_holding(id).map_or(held, |place| {+ let bound = &self.segments[place];+ EntryView::Bound {+ bound,+ entry: &bound.segment.entries[(id - bound.first) as usize],+ dead: bound.is_dead(id),+ }+ }))+ }+ None => self+ .user_agent+ .as_ref()+ .and_then(|user_agent| user_agent.index.entries.own.get(id))+ .map(|entry| EntryView::Held {+ entry,+ user_agent: true,+ }),+ }+ }++ /// How many entries the user agent index the document shares has.+ fn user_agent_count(&self) -> usize {+ self.user_agent+ .as_ref()+ .map_or(0, |user_agent| user_agent.index.entries.own.len())+ }++ /// The number of every entry, in order.+ #[cfg(test)]+ pub(super) fn numbers(&self) -> impl Iterator<Item = usize> {+ (0..self.user_agent_count()).chain(self.first as usize..self.len())+ }++ /// The numbers of the document's own entries.+ pub(super) fn own_numbers(&self) -> std::ops::Range<usize> {+ self.first as usize..self.len()+ }++ fn next_number(&self) -> u32 {+ u32::try_from(self.len()).expect("rule entry space exhausted")+ }++ fn own_mut(&mut self, id: u32) -> &mut IndexedEntry {+ debug_assert!(self.segment_holding(id).is_none(), "a bound segment holds its entries");+ self.own.get_mut((id - self.first) as usize)+ }+}++/// The entries of the user agent's rules deciding in a document, which every document of the+/// process whose user agent rules are the same shares: their buckets, selectors and+/// invalidation map are built once.+///+/// NB: The index is keyed by the user agent rules that decide, so documents whose media select+/// the same rules share one.+pub(in crate::css::style) struct UserAgentIndex {+ /// The rules the index indexes.+ variant: UserAgentVariant,+ /// The entries, numbered from zero, bucketed in the document's buckets.+ index: RuleIndex,+ /// The invalidation map of the entries, which a document's own map starts from.+ pub(super) invalidation: super::invalidation::InvalidationPart,+}++impl UserAgentIndex {+ /// Index the rules of `variant`, which `rules`, the process's user agent rules, hold.+ fn build(rules: &RuleStore, variant: &UserAgentVariant) -> Self {+ let mut index = RuleIndex::default();+ let mut added = Vec::new();+ for (rank, &sheet) in variant.sheets().iter().enumerate() {+ let placement = SheetPlacement {+ origin: CascadeOrigin::UserAgent,+ sheet_rank: rank as u64,+ };+ for rule in rules.rules_in_sheet(sheet) {+ if variant.leaves_out(rule) {+ continue;+ }+ let first = index.entries.own.len();+ let first_added = added.len();+ index.index_rule(rules, rule, ScopeGroupID::DOCUMENT, placement, &mut added);+ for &id in &added[first_added..] {+ index.bucket(id);+ }+ for number in first..index.entries.own.len() {+ index.entries.own.get_mut(number).rule = EntryRule::user_agent(rule);+ }+ }+ }+ assert!(+ index.entries.own.len() <= FIRST_DOCUMENT_ENTRY as usize,+ "the user agent's entries fit below the document's"+ );+ assert!(+ index.gates.is_empty(),+ "no user agent rule applies under container conditions"+ );+ // NB: The identities the rules were indexed by are the process's, which no document names.+ index.indexed = Indexed::default();+ index.document_non_author = ScopeIndex::default();+ index.shrink_to_fit();+ // NB: Every document's map starts from this one, sharing what it holds.+ let mut invalidation = super::invalidation::InvalidationPart::default();+ invalidation.extend(0..index.entries.len(), |entry| {+ let indexed = index.entries.entry(entry as usize);+ indexed+ .live()+ .then(|| (index.entry_selector(entry), index.arena_of_entry(entry)))+ });+ invalidation.freeze();+ Self {+ variant: variant.clone(),+ index,+ invalidation,+ }+ }+}++/// The fewest entries a sheet has for its entries to be bucketed in a segment the process shares.+/// Matching probes the buckets of each segment apart, which costs more than a few entries of the+/// document's own buckets save.+const SEGMENT_MIN_ENTRIES: usize = 64;++/// One entry of a sheet segment, which every document binding the segment shares: what the entry+/// is relative to its sheet. The binding says the rest: the rule the offsets count from, and the+/// placement of each slot.+#[derive(Clone, Copy, PartialEq, Eq, Hash)]+pub(super) struct SegmentEntry {+ /// The entry's rule, as an offset from the binding's first rule.+ rule: u32,+ /// The entry's selector, in the segment's space.+ selector: SelectorRef,+ specificity: PackedSpecificity,+ /// The slot of the entry's placement among the binding's placements.+ placement: u16,+ pseudo_kind: u8,+ flags: EntryFlags,+ /// The rank of the entry's rule in its sheet, which the documents sharing the sheet's rule+ /// order share.+ rule_rank: u64,+}++const _: () = assert!(size_of::<SegmentEntry>() == 24);++/// What a document asks a segment to hold for one entry: the entry relative to its sheet, where its+/// selector is, and the `@scope` levels its rule is inside, if any.+struct HeldEntry {+ entry: SegmentEntry,+ source: EntrySource,+ scope: Option<Arc<super::super::bridge::BoundScopeChain>>,+}++/// What tells a segment entry from another for as long as the process lives: the entry but for its+/// selector, the selector by its arena's serial and offset, and the address of its scope chain.+type HeldIdentity = (+ (u32, PackedSpecificity, u16, u8, EntryFlags, u64),+ crate::css::selector_arena::SelectorKey,+ usize,+);++fn held_identity(+ entry: &SegmentEntry,+ selector: crate::css::selector_arena::SelectorKey,+ scope: Option<&Arc<super::super::bridge::BoundScopeChain>>,+) -> HeldIdentity {+ (+ (+ entry.rule,+ entry.specificity,+ entry.placement,+ entry.pseudo_kind,+ entry.flags,+ entry.rule_rank,+ ),+ selector,+ scope.map_or(0, |scope| Arc::as_ptr(scope) as usize),+ )+}++impl HeldEntry {+ fn selector(&self) -> super::super::component_matching::EntrySelector<'_> {+ super::super::component_matching::EntrySelector::new(self.source.selector(), self.scope.as_deref())+ }++ fn identity(&self) -> HeldIdentity {+ held_identity(&self.entry, self.source.identity(), self.scope.as_ref())+ }+}++/// The entries of one sheet's rules deciding in a document, bucketed, which every+/// document of the process indexing the same selectors for one of its sheets shares: the frames of+/// a site loading one sheet bucket its rules once, and hold none of its entries. Each document+/// numbers the entries from a first number of its own, and binds the rest of what an entry is to+/// it: the rule the entries' rules count from, and the placements of their layers.+///+/// NB: A document matches against its own buckets and then the segment of each sheet it binds,+/// in turn.+pub(in crate::css::style) struct SheetSegment {+ /// Each entry, in the order of their numbers.+ entries: Box<[SegmentEntry]>,+ /// The `@scope` levels of the rules of the entries inside any, by entry, in the order of the+ /// entries.+ scopes: Box<[(u32, Arc<super::super::bridge::BoundScopeChain>)]>,+ /// The space the entries' and the buckets' selectors are in.+ selector_space: SelectorSpace,+ /// The entries, numbered from zero, bucketed as the document's entries of a scope are.+ index: ScopeIndex,+ /// The ids an entry that does not revalidate tests for.+ tested_ids: HashSet<StyleAtomID>,+ /// The invalidation map of the entries, numbered from zero, which the maps of the documents+ /// binding the segment share.+ pub(super) invalidation: super::invalidation::InvalidationPart,+}++impl SheetSegment {+ fn build(held: Vec<HeldEntry>) -> Self {+ let mut index = ScopeIndex::default();+ let mut tested_ids = HashSet::default();+ let mut selector_space = SelectorSpace::default();+ let mut entries = Vec::with_capacity(held.len());+ let mut scopes = Vec::new();+ for (number, held) in held.iter().enumerate() {+ let number = u32::try_from(number).expect("rule entry space exhausted");+ let entry_selector = held.selector();+ let facts = EntryFacts::of(entry_selector);+ let selector = selector_space.add_entry(&held.source);+ let slot = BucketEntry::new(entry_selector.selector, number, selector, held.scope.is_some());+ let (keys, families) = placement_in_buckets(entry_selector.selector, facts);+ index.insert(slot, &keys, families);+ if !facts.never_matches && !facts.revalidates {+ let mut ids = Vec::new();+ collect_tested_ids(entry_selector.selector, &mut ids);+ tested_ids.extend(ids);+ }+ entries.push(SegmentEntry { selector, ..held.entry });+ if let Some(scope) = &held.scope {+ scopes.push((number, Arc::clone(scope)));+ }+ }+ index.shrink_to_fit();+ tested_ids.shrink_to_fit();+ selector_space.shrink_to_fit();+ let mut invalidation = super::invalidation::InvalidationPart::default();+ for buckets in [+ &mut index.own,+ &mut index.own_revalidation,+ &mut index.host,+ &mut index.slotted,+ &mut index.part,+ ] {+ buckets.freeze();+ }+ invalidation.leave_lone_entries_to_buckets();+ invalidation.extend(0..held.len(), |entry| {+ let held = &held[entry as usize];+ Some((held.selector(), &held.source.selectors))+ });+ invalidation.freeze();+ Self {+ entries: entries.into(),+ scopes: scopes.into(),+ selector_space,+ index,+ tested_ids,+ invalidation,+ }+ }++ pub(super) fn len(&self) -> u32 {+ self.entries.len() as u32+ }++ /// The entries of the segment the bucket of `key` holds that its key proves.+ pub(super) fn entries_proven_by(&self, key: DispatchKey) -> impl Iterator<Item = u32> + '_ {+ self.index+ .own+ .get(&key)+ .into_iter()+ .flatten()+ .filter(|slot| slot.covered(false))+ .map(|slot| slot.entry())+ }++ /// Whether the buckets of the segment hold any entry under `key`.+ pub(super) fn buckets_hold(&self, key: DispatchKey) -> bool {+ self.index.own.get(&key).is_some()+ }++ /// The `@scope` levels the rule of entry `entry` of the segment is inside, if any.+ fn scope_of(&self, entry: u32) -> Option<&Arc<super::super::bridge::BoundScopeChain>> {+ self.scopes+ .binary_search_by_key(&entry, |&(number, _)| number)+ .ok()+ .map(|place| &self.scopes[place].1)+ }++ fn hash_of(held: &[HeldEntry]) -> u64 {+ use std::hash::{Hash, Hasher};+ let mut hasher = super::super::fast_hash::fast_hasher();+ for held in held {+ held.identity().hash(&mut hasher);+ }+ hasher.finish()+ }++ fn holds(&self, held: &[HeldEntry]) -> bool {+ self.entries.len() == held.len()+ && self+ .entries+ .iter()+ .zip(held)+ .enumerate()+ .all(|(number, (entry, other))| {+ let number = number as u32;+ held_identity(+ entry,+ self.selector_space.resolve(entry.selector).key(),+ self.scope_of(number),+ ) == other.identity()+ })+ }++ /// The bytes of the segment, which the documents binding it reach through it.+ fn heap_size(&self) -> usize {+ use crate::heap_size::set_bytes;+ let buckets = |buckets: &Buckets| buckets.heap_size();+ size_of_val::<[SegmentEntry]>(&self.entries)+ + size_of_val::<[(u32, Arc<super::super::bridge::BoundScopeChain>)]>(&self.scopes)+ + [+ &self.index.own,+ &self.index.own_revalidation,+ &self.index.host,+ &self.index.slotted,+ &self.index.part,+ ]+ .into_iter()+ .map(buckets)+ .sum::<usize>()+ + set_bytes(&self.tested_ids)+ + self.selector_space.heap_size()+ + self.invalidation.heap_size()+ + self.invalidation.shared_heap_size()+ }+}++/// A segment the entries of one sheet deciding in one group are bucketed and kept in, numbered in+/// the document from `first`.+#[derive(Clone)]+pub(super) struct BoundSegment {+ segment: Arc<SheetSegment>,+ first: u32,+ sheet: SheetID,+ group: ScopeGroupID,+ origin: CascadeOrigin,+ /// The rule the segment's entries count their rules from.+ first_rule: RuleID,+ /// The placement of each slot the segment's entries name.+ placements: SmallVec<[PlacementID; 1]>,+ /// One bit for each of the segment's entries that died for this index, whose buckets, shared+ /// with the other documents binding the segment, go on holding them. Empty until one dies.+ dead: Vec<u64>,+}++impl BoundSegment {+ /// Whether the entry `id`, which the segment holds, died for this index.+ pub(super) fn is_dead(&self, id: u32) -> bool {+ let at = (id - self.first) as usize;+ self.dead.get(at / 64).is_some_and(|word| word & (1 << (at % 64)) != 0)+ }++ /// Note that the entry `id`, which the segment holds, died for this index.+ fn note_dead(&mut self, id: u32) {+ let at = (id - self.first) as usize;+ if self.dead.is_empty() {+ self.dead = vec![0; (self.segment.len() as usize).div_ceil(64)];+ }+ self.dead[at / 64] |= 1 << (at % 64);+ }++ fn holds(&self, entry: u32) -> bool {+ (self.first..self.first + self.segment.len()).contains(&entry)+ }++ /// The entry `id` of the document, which the segment holds, as the document has it but for its+ /// selector, which is in the segment's space.+ fn entry(&self, id: u32) -> IndexedEntry {+ EntryView::Bound {+ bound: self,+ entry: &self.segment.entries[(id - self.first) as usize],+ dead: self.is_dead(id),+ }+ .indexed()+ }+}++/// The buckets of one part of an index, and the number their entries are numbered from.+#[derive(Clone, Copy)]+pub(super) struct BucketSource<'a> {+ pub(super) buckets: &'a ScopeIndex,+ pub(super) first: u32,+ /// The space the buckets' selectors are in.+ pub(super) space: &'a SelectorSpace,+ /// The bound segment the buckets are of, which holds their entries, where they are a segment's.+ bound: Option<&'a BoundSegment>,+}++/// What a match of an entry takes from it.+#[derive(Clone, Copy)]+pub(super) struct MatchedEntry {+ pub(super) rule: RuleID,+ /// The group of trees the entry decides in.+ pub(super) group: ScopeGroupID,+ pub(super) specificity: Specificity,+ pub(super) pseudo_kind: u8,+}++impl<'a> BucketSource<'a> {+ /// The binding of the segment the buckets are of, where entries of its died for the index.+ pub(super) fn binding_with_dead_entries(&self) -> Option<&'a BoundSegment> {+ self.bound.filter(|bound| !bound.dead.is_empty())+ }++ /// What a match of the entry numbered `id` of `index`, which the buckets hold, takes from it:+ /// read in place from the segment the buckets are of, which decides in its binding's group,+ /// where they are a segment's.+ pub(super) fn matched(&self, index: &RuleIndex, id: u32) -> MatchedEntry {+ match self.bound {+ Some(bound) => {+ let entry = &bound.segment.entries[(id - bound.first) as usize];+ MatchedEntry {+ rule: RuleID(bound.first_rule.0 + entry.rule),+ group: bound.group,+ specificity: entry.specificity.unpacked(),+ pseudo_kind: entry.pseudo_kind,+ }+ }+ None => {+ let view = index.entries.view(id as usize);+ MatchedEntry {+ rule: index.rule_of_view(view),+ group: index.entries.placement_of(view).group,+ specificity: view.specificity(),+ pseudo_kind: view.pseudo_kind(),+ }+ }+ }+ }+}++/// The rule index data the process shares between documents: the user agent indexes, one for each+/// set of user agent rules a document decided with, and the segments of the sheets documents+/// index alike.+#[derive(Default)]+pub(in crate::css::style) struct ProcessRuleIndexes {+ indexes: std::sync::Mutex<Vec<Arc<UserAgentIndex>>>,+ /// The segments the process built, by the hash of their selectors, which go once no document+ /// binds them and `kept_segments` lets go of them.+ segments: std::sync::Mutex<HashMap<u64, SmallVec<[std::sync::Weak<SheetSegment>; 1]>>>,+ /// The segments a page of the same site finds as it binds them again.+ kept_segments: std::sync::Mutex<crate::css::style::kept_past_release::KeptPastRelease<SheetSegment>>,+ /// The pages of the documents' entries, which documents numbering their entries alike share.+ entry_pages: PagePool<IndexedEntry>,+ /// The pages of the lists of the entries of each rule, which documents numbering their rules+ /// and entries alike share.+ entry_extents: PagePool<Extent>,+ entry_lists: PagePool<u32>,+ /// The top-level rules and rule orders of the documents' sheets, which documents whose sheets+ /// hold their rules alike share.+ sheet_rules: std::sync::Mutex<WeakPool<Vec<RuleID>>>,+ sheet_rule_orders: std::sync::Mutex<WeakPool<crate::css::style::order::OrderMaintenance>>,+ /// The pages of the documents' rule records, rule versions and native rule targets, which+ /// documents holding their rules alike share.+ pub(super) rule_record_pages: super::rule_store::RuleRecordPages,+ pub(super) rule_version_pages: super::rule_store::RuleVersionPages,+ pub(super) target_pages: super::rule_store::TargetPages,+}++impl ProcessRuleIndexes {+ /// Share the top-level rules and rule order of a sheet with the documents of the process+ /// whose sheets hold their rules alike.+ pub(super) fn share_sheet_rules(+ &self,+ rules: &mut Arc<Vec<RuleID>>,+ rule_order: &mut Arc<crate::css::style::order::OrderMaintenance>,+ ) {+ fn share<T: PartialEq + Hash>(pool: &std::sync::Mutex<WeakPool<T>>, value: &mut Arc<T>) {+ let mut hasher = super::super::fast_hash::fast_hasher();+ value.hash(&mut hasher);+ let hash = std::hash::Hasher::finish(&hasher);+ let mut pool = pool.lock().unwrap_or_else(std::sync::PoisonError::into_inner);+ match pool.find(hash, |candidate| candidate == &**value) {+ Some(found) => *value = found,+ None => pool.insert(hash, value),+ }+ }+ share(&self.sheet_rules, rules);+ share(&self.sheet_rule_orders, rule_order);+ }++ /// The segment of `selectors`, built where no document of the process binds one, and whether+ /// it was.+ fn segment_of(&self, held: Vec<HeldEntry>) -> (Arc<SheetSegment>, bool) {+ let hash = SheetSegment::hash_of(&held);+ let mut segments = self.segments.lock().unwrap_or_else(std::sync::PoisonError::into_inner);+ if let Some(found) = segments+ .get(&hash)+ .into_iter()+ .flatten()+ .filter_map(std::sync::Weak::upgrade)+ .find(|segment| segment.holds(&held))+ {+ self.kept_segments+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .note_use(&found);+ return (found, false);+ }+ // NB: Building under the lock has a document indexing the same sheet beside this one wait+ // for the segment and share it, rather than build another.+ let segment = Arc::new(SheetSegment::build(held));+ segments.retain(|_, held| {+ held.retain(|segment| segment.strong_count() > 0);+ !held.is_empty()+ });+ segments.entry(hash).or_default().push(Arc::downgrade(&segment));+ let left = self+ .kept_segments+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .keep(&segment, size_of::<SheetSegment>() + segment.heap_size());+ drop(segments);+ drop(left);+ (segment, true)+ }++ /// Let go of the segments only the process keeps and nothing asked for lately.+ pub(in crate::css::style) fn prune_kept_segments(&self) {+ let left = self+ .kept_segments+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .prune();+ drop(left);+ }++ /// Let go of the segments only the process keeps.+ pub(in crate::css::style) fn release_kept_segments(&self) {+ let left = self+ .kept_segments+ .lock()+ .unwrap_or_else(std::sync::PoisonError::into_inner)+ .release_all();+ drop(left);+ }++ /// Build the index of `variant` where no document of the process built it yet.+ pub(in crate::css::style) fn index_ahead(&self, rules: &RuleStore, variant: &UserAgentVariant) {+ self.get_or_build(rules, variant);+ }++ /// The index of `variant`, built from `rules`, the process's user agent rules, where no document+ /// of the process built it yet, and whether it was.+ fn get_or_build(&self, rules: &RuleStore, variant: &UserAgentVariant) -> (Arc<UserAgentIndex>, bool) {+ let mut indexes = self.indexes.lock().unwrap_or_else(std::sync::PoisonError::into_inner);+ if let Some(index) = indexes.iter().find(|index| index.variant == *variant) {+ return (Arc::clone(index), false);+ }+ let index = Arc::new(UserAgentIndex::build(rules, variant));+ indexes.push(Arc::clone(&index));+ (index, true)+ }+}++/// The selectors `rule` indexes entries from, if it indexes any.+fn indexed_selectors(program: &RuleStore, rule: RuleID) -> Option<crate::css::selector::SelectorListRef> {+ if !program.rule_can_decide(rule) {+ return None;+ }+ if !program.rule_version(rule).kind.matches_elements() {+ return None;+ }+ program.rule_selectors(rule)+}++/// Whether the rules of `sheet` decide through the user agent index: those of a user agent sheet of+/// the document.+fn is_user_agent_sheet(program: &RuleStore, sheet: SheetID) -> bool {+ program.sheet_origin(sheet) == CascadeOrigin::UserAgent+}++/// What a rule index indexed, by the identities of the rules and sheets in the rule store, which a+/// change names the rules and sheets it moved by.+#[derive(Clone, Default)]+struct Indexed {+ /// The live entries of each rule, in every scope.+ entries_of_rule: PagedExtentMap<u32>,+ /// The groups each contributing sheet's rules are indexed in, with the rank of the sheet in+ /// each that its entries hold.+ sheets: HashMap<SheetID, SmallVec<[(ScopeGroupID, u64); 1]>>,+ /// How many times the rule order of each sheet was relabeled, as the rule ranks of its entries+ /// follow.+ rule_order_relabels: HashMap<SheetID, u64>,+ /// The gate of each rule under container conditions.+ gate_of_rule: HashMap<RuleID, ContainerGateID>,+ /// The gate of each list of container conditions, by the addresses of the conditions: the+ /// rules of one container rule share its gate.+ gate_of_conditions: HashMap<Box<[usize]>, ContainerGateID>,+}++/// What a change to the rules names: the rules and sheets that moved, and the scopes whose sheet+/// or layer order moved.+pub(super) struct IndexChanges<'a> {+ /// The rules whose contents, conditions, layering or existence moved.+ pub(super) rules: &'a HashSet<RuleID>,+ /// The sheets attached to or detached from a scope, or whose activation moved.+ pub(super) sheets: &'a HashSet<SheetID>,+ /// The scopes whose sheets or layers were reordered.+ pub(super) reordered_scopes: &'a HashSet<TreeScopeID>,+ /// The scopes whose layer order moved, which moves the layer ranks of their entries.+ pub(super) layered_scopes: &'a HashSet<TreeScopeID>,+}++/// Where a sheet decides in one group of scopes: its origin and rank there.+#[derive(Clone, Copy)]+struct SheetPlacement {+ origin: CascadeOrigin,+ sheet_rank: u64,+}++impl SheetPlacement {+ /// Where `sheet` decides in the document.+ fn in_document(program: &RuleStore, sheet: SheetID) -> Self {+ Self {+ origin: program.sheet_origin(sheet),+ sheet_rank: program+ .attachment_in_scope(sheet, TreeScopeID::DOCUMENT)+ .map_or(0, |attachment| program.sheet_rank(attachment)),+ }+ }+}++fn is_non_author(origin: CascadeOrigin) -> bool {+ matches!(origin, CascadeOrigin::UserAgent | CascadeOrigin::User)+}++/// Whether elements report carrying the key when they are probed.+pub(super) fn is_probed(key: &DispatchKey) -> bool {+ matches!(+ key,+ DispatchKey::Universal+ | DispatchKey::State(_)+ | DispatchKey::Root+ | DispatchKey::Heading+ | DispatchKey::TagName(_)+ | DispatchKey::Id(_)+ | DispatchKey::Class(_)+ | DispatchKey::Directionality(_)+ | DispatchKey::CustomState(_)+ | DispatchKey::Part(_)+ | DispatchKey::AttributeName(_)+ )+}++impl RuleIndex {+ /// The bytes of the index's entries and buckets, without the user agent index the process shares between documents.+ pub(in crate::css::style) fn heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {+ use crate::heap_size::{map_bytes, set_bytes, vec_bytes};+ fn buckets_heap(buckets: &Buckets) -> usize {+ buckets.heap_size()+ }+ fn scope_heap(scope: &ScopeIndex) -> usize {+ [+ &scope.own,+ &scope.own_revalidation,+ &scope.host,+ &scope.slotted,+ &scope.part,+ ]+ .into_iter()+ .map(buckets_heap)+ .sum()+ }+ let entries = self.entries.own.heap_size(sizer, |_, _| 0);+ let indexed = &self.indexed;+ let indexed_bytes = indexed.entries_of_rule.heap_size(sizer)+ + map_bytes(&indexed.sheets)+ + indexed+ .sheets+ .values()+ .map(crate::heap_size::small_vec_bytes)+ .sum::<usize>()+ + map_bytes(&indexed.rule_order_relabels)+ + map_bytes(&indexed.gate_of_rule)+ + map_bytes(&indexed.gate_of_conditions)+ + indexed+ .gate_of_conditions+ .keys()+ .map(|key| size_of_val::<[usize]>(key))+ .sum::<usize>();+ entries+ + self.selectors.heap_size()+ + map_bytes(&self.entry_scopes)+ + vec_bytes(&self.entries.segments)+ + scope_heap(&self.document)+ + scope_heap(&self.document_non_author)+ + map_bytes(&self.groups)+ + self+ .groups+ .values()+ .map(|group| {+ scope_heap(&group.index)+ + crate::heap_size::small_vec_bytes(&group.scopes)+ + size_of_val::<[SheetID]>(&group.sheets)+ + map_bytes(&group.layer_ranks)+ })+ .sum::<usize>()+ + map_bytes(&self.group_of_scope)+ + map_bytes(&self.groups_by_sheets)+ + self+ .groups_by_sheets+ .iter()+ .map(|(sheets, groups)| size_of_val::<[SheetID]>(sheets) + crate::heap_size::small_vec_bytes(groups))+ .sum::<usize>()+ + set_bytes(&self.tested_ids)+ + vec_bytes(&self.gates)+ + self+ .gates+ .iter()+ .map(|gate| size_of_val::<[Arc<ContainerConditionsData>]>(gate))+ .sum::<usize>()+ + indexed_bytes+ }++ /// The bytes of the user agent index the process shares between documents, the first time+ /// `sizer` reaches it.+ pub(in crate::css::style) fn user_agent_heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {+ let Some(user_agent) = &self.entries.user_agent else {+ return 0;+ };+ if !sizer.first_sight(Arc::as_ptr(user_agent)) {+ return 0;+ }+ crate::heap_size::ARC_HEADER_BYTES+ + size_of::<UserAgentIndex>()+ + user_agent.variant.heap_size()+ + user_agent.index.heap_size(sizer)+ + user_agent.invalidation.heap_size()+ + user_agent.invalidation.shared_heap_size()+ }++ /// The bytes of the sheet segments the index binds, which the process shares between+ /// documents, each the first time `sizer` reaches it.+ pub(in crate::css::style) fn segments_heap_size(&self, sizer: &mut crate::heap_size::HeapSizer) -> usize {+ let mut bytes = 0;+ for bound in &self.entries.segments {+ bytes += crate::heap_size::vec_bytes(&bound.dead);+ if sizer.first_sight(Arc::as_ptr(&bound.segment)) {+ bytes += crate::heap_size::ARC_HEADER_BYTES + size_of::<SheetSegment>() + bound.segment.heap_size();+ }+ }+ bytes+ }++ /// The entry of this index that stands for each entry of `previous`, the same selector of the+ /// same rule deciding in the same scope, or none where the rule left it or the entry is dead.+ pub(super) fn renumbering_from(&self, previous: &RuleIndex) -> Vec<Option<u32>> {+ // NB: The groups of the scopes are numbered anew, and named here by their first scope.+ #[allow(clippy::type_complexity)]+ let mut by_key: HashMap<+ (+ RuleID,+ (crate::css::selector_arena::ComponentOffset, u8),+ Option<TreeScopeID>,+ ),+ u32,+ > = HashMap::default();+ for id in self.entries.own_numbers() {+ let entry = self.entries.entry(id);+ if !entry.live() {+ continue;+ }+ by_key.insert(+ (+ self.rule_of(id as u32),+ (self.selector_of_entry(id as u32).offset(), entry.pseudo_kind),+ self.first_scope_of(self.entries.placement(id).group),+ ),+ u32::try_from(id).expect("rule entry space exhausted"),+ );+ }+ // The user agent's entries stand for themselves where the same selector has the same+ // number in both.+ let user_agent_stays = stays_in_user_agent_index(previous, self);+ (0..previous.entries.len())+ .map(|id| {+ let entry = previous.entries.get(id).filter(|entry| entry.live())?;+ let number = u32::try_from(id).expect("rule entry space exhausted");+ match id < previous.entries.first as usize {+ true => user_agent_stays(id).then_some(number),+ false => by_key+ .get(&(+ previous.rule_of(number),+ (previous.selector_of_entry(number).offset(), entry.pseudo_kind),+ previous.first_scope_of(previous.entries.placement(id).group),+ ))+ .copied(),+ }+ })+ .collect()+ }++ /// The group whose entries decide in `scope`, where it has sheets.+ /// Whether every entry decides in the document's tree: no shadow tree has sheets of its own.+ pub(super) fn decides_only_in_the_document(&self) -> bool {+ self.groups.is_empty()+ && self+ .entries+ .segments+ .iter()+ .all(|bound| bound.group == ScopeGroupID::DOCUMENT)+ }++ pub(super) fn group_of(&self, scope: TreeScopeID) -> Option<ScopeGroupID> {+ match scope {+ TreeScopeID::DOCUMENT => Some(ScopeGroupID::DOCUMENT),+ _ => self.group_of_scope.get(&scope).copied(),+ }+ }++ /// The buckets of the entries deciding in the shadow tree `scope`, where it has sheets.+ #[cfg(test)]+ pub(super) fn scope_index(&self, scope: TreeScopeID) -> Option<&ScopeIndex> {+ let group = self.group_of_scope.get(&scope)?;+ self.groups.get(group).map(|group| &group.index)+ }++ /// The tree scopes deciding with the entries of `group`: none for a group that is gone.+ pub(super) fn scopes_of(&self, group: ScopeGroupID) -> &[TreeScopeID] {+ match group {+ ScopeGroupID::DOCUMENT => &[TreeScopeID::DOCUMENT],+ _ => self.groups.get(&group).map_or(&[], |group| group.scopes.as_slice()),+ }+ }++ /// The least of the tree scopes of `group`, which names it across builds.+ fn first_scope_of(&self, group: ScopeGroupID) -> Option<TreeScopeID> {+ self.scopes_of(group).iter().copied().min()+ }++ /// The tree scope the layers of the entries of `group` rank in.+ fn layer_scope_of(&self, group: ScopeGroupID) -> TreeScopeID {+ match group {+ ScopeGroupID::DOCUMENT => TreeScopeID::DOCUMENT,+ _ => self.groups[&group].scopes[0],+ }+ }++ /// The sheets the entries of `group` are of, in cascade order.+ fn sheets_of_group<'a>(&'a self, program: &'a RuleStore, group: ScopeGroupID) -> &'a [SheetID] {+ match group {+ ScopeGroupID::DOCUMENT => program.sheets_in_scope(TreeScopeID::DOCUMENT),+ _ => &self.groups[&group].sheets,+ }+ }++ /// Where `sheet` decides in `group`: in a group of shadow trees, the sheet ranks by its place+ /// among their sheets, which are the same in each.+ fn placement(&self, program: &RuleStore, sheet: SheetID, group: ScopeGroupID) -> SheetPlacement {+ match group {+ ScopeGroupID::DOCUMENT => SheetPlacement::in_document(program, sheet),+ _ => SheetPlacement {+ origin: program.sheet_origin(sheet),+ sheet_rank: self.groups[&group]+ .sheets+ .iter()+ .position(|&held| held == sheet)+ .map_or(0, |position| position as u64),+ },+ }+ }++ /// The group of the shadow trees whose sheets and layers are those of the shadow tree `scope`,+ /// if one exists.+ fn group_alike(&self, program: &RuleStore, scope: TreeScopeID) -> Option<ScopeGroupID> {+ self.groups_by_sheets+ .get(program.sheets_in_scope(scope))?+ .iter()+ .copied()+ .find(|group| program.layer_ranks_match(scope, &self.groups[group].layer_ranks))+ }++ /// Have the shadow tree `scope`, which is in no group, join the group of the trees alike, or a+ /// new one of its own. Answers the group, and whether it is new, which holds no entries yet.+ fn join_group(&mut self, program: &RuleStore, scope: TreeScopeID) -> (ScopeGroupID, bool) {+ debug_assert!(!self.group_of_scope.contains_key(&scope));+ if let Some(group) = self.group_alike(program, scope) {+ self.groups+ .get_mut(&group)+ .expect("a group alike is held")+ .scopes+ .push(scope);+ self.group_of_scope.insert(scope, group);+ return (group, false);+ }+ self.next_group += 1;+ let group = ScopeGroupID(self.next_group);+ let sheets: Box<[SheetID]> = program.sheets_in_scope(scope).into();+ self.groups_by_sheets.entry(sheets.clone()).or_default().push(group);+ self.groups.insert(+ group,+ ScopeGroup {+ index: ScopeIndex::default(),+ scopes: smallvec::smallvec![scope],+ sheets,+ layer_ranks: program.layer_ranks(scope),+ },+ );+ self.group_of_scope.insert(scope, group);+ (group, true)+ }++ /// Have the shadow tree `scope` leave its group, which dies with its last tree: its entries+ /// die, noted in `died`. Answers the group it left.+ fn leave_group(&mut self, program: &RuleStore, scope: TreeScopeID, died: &mut Vec<u32>) -> Option<ScopeGroupID> {+ let group = self.group_of_scope.remove(&scope)?;+ let held = self.groups.get_mut(&group).expect("a scope's group is held");+ held.scopes.retain(|&mut member| member != scope);+ if !held.scopes.is_empty() {+ return Some(group);+ }+ let held = self.groups.remove(&group).expect("a scope's group is held");+ if let Some(groups) = self.groups_by_sheets.get_mut(&held.sheets) {+ groups.retain(|&mut other| other != group);+ if groups.is_empty() {+ self.groups_by_sheets.remove(&held.sheets);+ }+ }+ self.drop_segments(None, group, died);+ for &sheet in &held.sheets {+ let Some(groups) = self.indexed.sheets.get_mut(&sheet) else {+ continue;+ };+ let before = groups.len();+ groups.retain(|&mut (indexed, _)| indexed != group);+ if groups.len() == before {+ continue;+ }+ if groups.is_empty() {+ self.indexed.sheets.remove(&sheet);+ }+ self.entries.placements_of_sheet.remove(&(sheet, group));+ for rule in program.all_rules_in_sheet(sheet) {+ self.kill_rule(rule, Some(group), died);+ }+ }+ Some(group)+ }++ /// Have the group of the shadow tree `scope`, its only tree, take the sheets and layers the+ /// tree has now, where no other group has them.+ fn regroup_alone(&mut self, program: &RuleStore, scope: TreeScopeID) -> bool {+ let Some(&group) = self.group_of_scope.get(&scope) else {+ return false;+ };+ if self.groups[&group].scopes.len() != 1 || self.group_alike(program, scope).is_some() {+ return false;+ }+ let held = self.groups.get_mut(&group).expect("a scope's group is held");+ let sheets: Box<[SheetID]> = program.sheets_in_scope(scope).into();+ let previous = std::mem::replace(&mut held.sheets, sheets.clone());+ held.layer_ranks = program.layer_ranks(scope);+ if let Some(groups) = self.groups_by_sheets.get_mut(&previous) {+ groups.retain(|&mut other| other != group);+ if groups.is_empty() {+ self.groups_by_sheets.remove(&previous);+ }+ }+ self.groups_by_sheets.entry(sheets).or_default().push(group);+ true+ }++ /// Each entry as itself where it lives, and none where it is dead.+ pub(super) fn live_numbering(&self) -> Vec<Option<u32>> {+ (0..self.entries.len())+ .map(|id| {+ self.entries+ .get(id)+ .is_some_and(|entry| entry.live())+ .then(|| u32::try_from(id).expect("rule entry space exhausted"))+ })+ .collect()+ }++ /// The rule of the document `entry` is of.+ pub(super) fn rule_of(&self, entry: u32) -> RuleID {+ self.rule_of_view(self.entries.view(entry as usize))+ }++ /// The rule of the entry `view`.+ pub(super) fn rule_of_view(&self, view: EntryView<'_>) -> RuleID {+ RuleID(view.rule().0)+ }++ /// Whether an entry that does not revalidate tests for the id `id`.+ pub(super) fn tests_id(&self, id: StyleAtomID) -> bool {+ self.tested_ids.contains(&id)+ || self+ .entries+ .user_agent+ .as_ref()+ .is_some_and(|user_agent| user_agent.index.tested_ids.contains(&id))+ || self+ .entries+ .segments+ .iter()+ .any(|bound| bound.segment.tested_ids.contains(&id))+ }++ /// The buckets of the user agent's entries, which decide in every tree.+ pub(super) fn user_agent_buckets(&self) -> Option<BucketSource<'_>> {+ self.entries.user_agent.as_ref().map(|user_agent| BucketSource {+ buckets: &user_agent.index.document,+ first: 0,+ space: &user_agent.index.selectors,+ bound: None,+ })+ }++ /// The buckets of the entries of `group`: those of its scope index where it has one, and+ /// those of the segments of its sheets, or of only those of a user agent or user origin+ /// where `non_author`, in which case the scope index is the document's non-author one.+ pub(super) fn bucket_sources(+ &self,+ group: ScopeGroupID,+ non_author: bool,+ ) -> impl Iterator<Item = BucketSource<'_>> + '_ {+ let own = match (group, non_author) {+ (ScopeGroupID::DOCUMENT, false) => Some(&self.document),+ (ScopeGroupID::DOCUMENT, true) => Some(&self.document_non_author),+ (group, _) => self.groups.get(&group).map(|group| &group.index),+ };+ own.map(|buckets| BucketSource {+ buckets,+ first: 0,+ space: &self.selectors,+ bound: None,+ })+ .into_iter()+ .chain(+ self.entries+ .segments+ .iter()+ .filter(move |bound| bound.group == group && (!non_author || is_non_author(bound.origin)))+ .map(|bound| BucketSource {+ buckets: &bound.segment.index,+ first: bound.first,+ space: &bound.segment.selector_space,+ bound: Some(bound),+ }),+ )+ }++ /// The dispatch bloom bits of the keys of the buckets the index holds itself, those an element+ /// is matched by among them: its own, and those of the other trees reaching it.+ pub(super) fn bucket_key_bits(&self) -> u64 {+ let of_scope = |scope: &ScopeIndex| {+ [&scope.own, &scope.host, &scope.slotted, &scope.part]+ .into_iter()+ .flat_map(|buckets| buckets.keys())+ .fold(0, |bits, key| bits | dispatch_bloom_bit(*key))+ };+ self.groups+ .values()+ .map(|group| &group.index)+ .chain([&self.document, &self.document_non_author])+ .fold(0, |bits, scope| bits | of_scope(scope))+ }++ /// Whether any entry is of a rule inside `@scope`.+ pub(super) fn has_scoped_entries(&self) -> bool {+ !self.entry_scopes.is_empty()+ }++ /// Whether the entry `entry`, which may have died, still has its selector.+ pub(super) fn holds_selector_of(&self, entry: u32) -> bool {+ !self.entries.view(entry as usize).flags().has(EntryFlags::SELECTOR_GONE)+ }++ /// The selector entry `entry` matches by, inside the `@scope` levels of its rule.+ pub(super) fn entry_selector(&self, entry: u32) -> super::super::component_matching::EntrySelector<'_> {+ let indexed = self.entries.view(entry as usize);+ // NB: Only the entries of rules inside `@scope` have levels to look up.+ let scope = match indexed.scoped() {+ true => self.entry_scopes.get(&entry).map(|scope| &**scope),+ false => None,+ };+ super::super::component_matching::EntrySelector::new(+ self.space_of_entry(entry).resolve(indexed.selector()),+ scope,+ )+ }++ /// The space the selector of entry `entry` is in: the user agent index's for its entries, and+ /// the index's own for the rest.+ fn space_of_entry(&self, entry: u32) -> &SelectorSpace {+ if entry < self.entries.first {+ return &self+ .entries+ .user_agent+ .as_ref()+ .expect("a user agent entry has its index")+ .index+ .selectors;+ }+ match self.entries.segment_holding(entry) {+ Some(place) => &self.entries.segments[place].segment.selector_space,+ None => &self.selectors,+ }+ }++ /// The selector of entry `entry`.+ pub(super) fn selector_of_entry(&self, entry: u32) -> crate::css::selector::Selector<'_> {+ self.space_of_entry(entry)+ .resolve(self.entries.view(entry as usize).selector())+ }++ /// The arena holding the selector of entry `entry`.+ pub(super) fn arena_of_entry(&self, entry: u32) -> &crate::css::selector::SelectorListRef {+ let space = self.space_of_entry(entry);+ let (slot, _) = space.locate(self.entries.view(entry as usize).selector());+ &space.arenas[slot.0 as usize]+ }++ /// Where the selector of entry `entry` is, held by its arena.+ pub(super) fn source_of_entry(&self, entry: u32) -> EntrySource {+ self.space_of_entry(entry)+ .source(self.entries.view(entry as usize).selector())+ }++ /// The container conditions the rule of entry `entry` applies under, where it is gated.+ pub(super) fn gate_of_entry(&self, entry: u32) -> Option<ContainerGateID> {+ if !self.entries.view(entry as usize).gated() {+ return None;+ }+ let gate = self.indexed.gate_of_rule.get(&self.rule_of(entry));+ Some(*gate.expect("a gated entry's rule has its gate"))+ }++ /// Whether `entry` is bucketed in a segment the index binds.+ pub(super) fn in_segment(&self, entry: u32) -> bool {+ self.segment_holding(entry).is_some()+ }++ /// The segments the index binds, with the number of the first entry of each.+ pub(super) fn bound_segments(&self) -> impl Iterator<Item = (&Arc<SheetSegment>, u32)> {+ self.entries.segments.iter().map(|bound| (&bound.segment, bound.first))+ }++ /// The segment holding `entry`, by its place among the index's.+ fn segment_holding(&self, entry: u32) -> Option<usize> {+ self.entries.segment_holding(entry)+ }++ /// The user agent index the document shares, if its user agent sheets have rules.+ pub(super) fn user_agent_index(&self) -> Option<&Arc<UserAgentIndex>> {+ self.entries.user_agent.as_ref()+ }++ /// Whether so many entries are dead that building the index again is worth it.+ pub(super) fn wants_compaction(&self) -> bool {+ self.dead_entries > 256 && self.dead_entries * 2 > self.entries.own.len()+ }++ /// The container conditions of `gate`.+ pub(super) fn gate(&self, gate: ContainerGateID) -> &[Arc<ContainerConditionsData>] {+ &self.gates[gate.0.get() as usize - 1]+ }++ /// Whether a rule indexed applies under container conditions.+ pub(super) fn has_gates(&self) -> bool {+ !self.gates.is_empty()+ }++ /// Index every rule entry attached to any tree scope, sharing the user agent index of+ /// `process_indexes` where it has one for the document's user agent rules, or building one+ /// of the document's own where it is none.+ pub(super) fn build(program: &RuleStore, process_indexes: Option<&ProcessRuleIndexes>) -> Self {+ let mut index = Self::default();+ index.entries.first = FIRST_DOCUMENT_ENTRY;+ index.bind_user_agent(program, process_indexes);+ let mut added = Vec::new();+ for scope in program.scopes_with_sheets() {+ let group = match scope {+ TreeScopeID::DOCUMENT => ScopeGroupID::DOCUMENT,+ _ => match index.join_group(program, scope) {+ (group, true) => group,+ // A shadow tree alike to one before shares its group's entries.+ (_, false) => continue,+ },+ };+ index.index_sheets_of_group(program, group, process_indexes, &mut added);+ }+ index.indexed_entries += added.len() as u64;+ index.shrink_to_fit();+ index.share_entries(process_indexes);+ index+ }++ /// Share the pages of the index's entries with the documents of the process holding equal ones.+ fn share_entries(&mut self, process_indexes: Option<&ProcessRuleIndexes>) {+ if let Some(process_indexes) = process_indexes {+ self.entries.own.share(&process_indexes.entry_pages);+ self.indexed+ .entries_of_rule+ .share(&process_indexes.entry_extents, &process_indexes.entry_lists);+ }+ }++ /// Releases what building the index reserved beyond what it holds. An update grows it again as+ /// it needs, and the next build gives the room back.+ fn shrink_to_fit(&mut self) {+ self.entries.own.shrink_to_fit();+ self.entries.placements.shrink_to_fit();+ self.entries.placements_of_sheet.shrink_to_fit();+ self.entries.segments.shrink_to_fit();+ self.document.shrink_to_fit();+ self.document_non_author.shrink_to_fit();+ for group in self.groups.values_mut() {+ group.index.shrink_to_fit();+ }+ self.groups.shrink_to_fit();+ self.group_of_scope.shrink_to_fit();+ self.groups_by_sheets.shrink_to_fit();+ self.tested_ids.shrink_to_fit();+ self.gates.shrink_to_fit();+ self.selectors.shrink_to_fit();+ self.entry_scopes.shrink_to_fit();+ let indexed = &mut self.indexed;+ indexed.entries_of_rule.shrink_to_fit();+ indexed.sheets.shrink_to_fit();+ indexed.rule_order_relabels.shrink_to_fit();+ indexed.gate_of_rule.shrink_to_fit();+ indexed.gate_of_conditions.shrink_to_fit();+ }++ /// Share the user agent index of the user agent rules deciding in the document of `program`,+ /// and answer the one shared before.+ fn bind_user_agent(+ &mut self,+ program: &RuleStore,+ process_indexes: Option<&ProcessRuleIndexes>,+ ) -> Option<Arc<UserAgentIndex>> {+ let (index, built) = match (+ program.user_agent_variant(),+ program.user_agent_rules(),+ process_indexes,+ ) {+ (Some(variant), Some(rules), Some(indexes)) => {+ let (index, built) = indexes.get_or_build(rules.store(), &variant);+ (Some(index), built)+ }+ (Some(variant), Some(rules), None) => {+ (Some(Arc::new(UserAgentIndex::build(rules.store(), &variant))), true)+ }+ _ => (None, false),+ };+ if built && let Some(index) = &index {+ self.built_user_agent_index = true;+ self.indexed_entries += index.index.entries.own.len() as u64;+ self.compiled_selectors += index.index.compiled_selectors;+ }+ std::mem::replace(&mut self.entries.user_agent, index)+ }++ /// Index the rules of the contributing sheets of `group`, which holds no entries, but for the+ /// user agent's.+ fn index_sheets_of_group(+ &mut self,+ program: &RuleStore,+ group: ScopeGroupID,+ process_indexes: Option<&ProcessRuleIndexes>,+ added: &mut Vec<u32>,+ ) {+ let sheets: SmallVec<[SheetID; 8]> = self.sheets_of_group(program, group).iter().copied().collect();+ for sheet in sheets {+ if !program.sheet_contributes(sheet) || is_user_agent_sheet(program, sheet) {+ continue;+ }+ self.index_sheet(program, sheet, group, process_indexes, added);+ }+ }++ /// Index the rules of `sheet` deciding in `group`, which the index had none of. Their entries+ /// are bucketed in the segment of the process indexing the same selectors where they are many+ /// enough, and in the index's own buckets otherwise.+ fn index_sheet(+ &mut self,+ program: &RuleStore,+ sheet: SheetID,+ group: ScopeGroupID,+ process_indexes: Option<&ProcessRuleIndexes>,+ added: &mut Vec<u32>,+ ) {+ let placement = self.placement(program, sheet, group);+ let groups = self.indexed.sheets.entry(sheet).or_default();+ debug_assert!(groups.iter().all(|&(indexed, _)| indexed != group));+ groups.push((group, placement.sheet_rank));+ self.indexed+ .rule_order_relabels+ .insert(sheet, program.rule_order_relabels(sheet));+ let rules = program.rules_in_sheet(sheet);+ // NB: Whether the sheet's entries are kept in a segment is decided before they are numbered,+ // so that the segment's numbers start a page of the document's entries.+ let process_indexes = process_indexes.filter(|_| {+ rules+ .iter()+ .filter_map(|&rule| indexed_selectors(program, rule))+ .map(|selectors| selectors.len())+ .sum::<usize>()+ >= SEGMENT_MIN_ENTRIES+ });+ if process_indexes.is_some() {+ self.entries.pad_to_page();+ }+ let first = self.entries.next_number();+ let first_added = added.len();+ for &rule in &rules {+ self.index_rule(program, rule, group, placement, added);+ }+ let Some(process_indexes) = process_indexes else {+ for &id in &added[first_added..] {+ self.bucket(id);+ }+ return;+ };+ let end = self.entries.next_number();+ if end == first {+ return;+ }+ self.bind_segment(process_indexes, first..end, sheet, group, placement.origin);+ }++ /// Have the segment of the process holding the entries `numbers`, those of `sheet` deciding in+ /// `group` the index just numbered, hold them for the index, which keeps none of them itself.+ fn bind_segment(+ &mut self,+ process_indexes: &ProcessRuleIndexes,+ numbers: std::ops::Range<u32>,+ sheet: SheetID,+ group: ScopeGroupID,+ origin: CascadeOrigin,+ ) {+ let entries: Vec<IndexedEntry> = numbers.clone().map(|id| self.entries.entry(id as usize)).collect();+ let first_rule = entries+ .iter()+ .map(|entry| entry.rule.0)+ .min()+ .expect("a segment holds entries");+ let mut placements: SmallVec<[PlacementID; 1]> = SmallVec::new();+ let held = numbers+ .clone()+ .zip(&entries)+ .map(|(id, entry)| {+ let placement = match placements.iter().position(|&placed| placed == entry.placement) {+ Some(slot) => slot,+ None => {+ placements.push(entry.placement);+ placements.len() - 1+ }+ };+ HeldEntry {+ entry: SegmentEntry {+ rule: entry.rule.0 - first_rule,+ selector: SelectorRef(0),+ specificity: entry.specificity,+ placement: u16::try_from(placement).expect("entry placement space exhausted"),+ pseudo_kind: entry.pseudo_kind,+ flags: entry.flags,+ rule_rank: entry.rule_rank,+ },+ source: self.selectors.source(entry.selector),+ scope: self.entry_scopes.get(&id).cloned(),+ }+ })+ .collect();+ let (segment, _) = process_indexes.segment_of(held);+ // NB: The segment tells the entries of its rules, which the document need not list.+ for entry in &entries {+ let rule = entry.rule.0 as usize;+ let left = self.indexed.entries_of_rule.retain(rule, |id| !numbers.contains(id));+ if left == 0 {+ self.indexed.entries_of_rule.remove(rule);+ }+ }+ self.entries.own.truncate((numbers.start - self.entries.first) as usize);+ for _ in numbers.clone() {+ self.entries.own.push(IndexedEntry::BOUND_NUMBER);+ }+ self.entries.pad_to_page();+ self.entries.segments.push(BoundSegment {+ segment,+ first: numbers.start,+ sheet,+ group,+ origin,+ first_rule: RuleID(first_rule),+ placements,+ dead: Vec::new(),+ });+ self.entries.note_segment_pages();+ }++ /// Put the entry `id` in the index's own buckets.+ fn bucket(&mut self, id: u32) {+ let placement = self.entries.placement(id as usize);+ let (group, origin) = (placement.group, placement.origin);+ let source = self.source_of_entry(id);+ let scope = self.entry_scopes.get(&id).cloned();+ self.bucket_as(id, &source, scope.as_deref(), group, origin);+ }++ /// Put the entry `id`, of the selector `entry_index` of `program`, deciding in `group` from a+ /// sheet of `origin`, in the index's own buckets.+ fn bucket_as(+ &mut self,+ id: u32,+ source: &EntrySource,+ scope: Option<&super::super::bridge::BoundScopeChain>,+ group: ScopeGroupID,+ origin: CascadeOrigin,+ ) {+ let entry_selector = super::super::component_matching::EntrySelector::new(source.selector(), scope);+ let facts = EntryFacts::of(entry_selector);+ let selector = self.selectors.add_entry(source);+ let scoped = scope.is_some();+ let slot = BucketEntry::new(entry_selector.selector, id, selector, scoped);+ let (keys, families) = placement_in_buckets(entry_selector.selector, facts);+ insert_entry(self, group, origin, slot, &keys, families);+ if !facts.never_matches && !facts.revalidates {+ let mut tested_ids = Vec::new();+ collect_tested_ids(entry_selector.selector, &mut tested_ids);+ self.tested_ids.extend(tested_ids);+ }+ }++ /// Have the entries the segment at `place` buckets kept and bucketed in the index's own entries+ /// and buckets instead, before one of them dies: a sheet whose rules change has buckets of its+ /// own from then on.+ fn copy_segment_out(&mut self, place: usize) {+ let bound = self.entries.segments.remove(place);+ self.entries.note_segment_pages();+ for id in bound.first..bound.first + bound.segment.len() {+ if bound.is_dead(id) {+ *self.entries.own_mut(id) = IndexedEntry {+ placement: bound.entry(id).placement,+ flags: EntryFlags(EntryFlags::SELECTOR_GONE),+ ..IndexedEntry::BOUND_NUMBER+ };+ continue;+ }+ let mut entry = bound.entry(id);+ entry.selector = self+ .selectors+ .add_entry(&bound.segment.selector_space.source(entry.selector));+ self.indexed.entries_of_rule.push(entry.rule.0 as usize, id);+ *self.entries.own_mut(id) = entry;+ self.bucket(id);+ }+ }++ /// Let go of the segment of the entries of `sheet` deciding in `group`, or of every sheet+ /// deciding in it where `sheet` is none, whose entries die, noting each in `died`. Their numbers+ /// keep only where they decided, which what changed tells the trees of.+ fn drop_segments(&mut self, sheet: Option<SheetID>, group: ScopeGroupID, died: &mut Vec<u32>) {+ for place in (0..self.entries.segments.len()).rev() {+ let bound = &self.entries.segments[place];+ if bound.group != group || sheet.is_some_and(|sheet| bound.sheet != sheet) {+ continue;+ }+ let bound = self.entries.segments.remove(place);+ self.entries.note_segment_pages();+ for id in bound.first..bound.first + bound.segment.len() {+ *self.entries.own_mut(id) = IndexedEntry {+ placement: bound.entry(id).placement,+ flags: EntryFlags(EntryFlags::SELECTOR_GONE),+ ..IndexedEntry::BOUND_NUMBER+ };+ if !bound.is_dead(id) {+ self.dead_entries += 1;+ died.push(id);+ }+ }+ }+ }++ /// Index the entries of `rule` deciding in `group`, appending their numbers to `added`, which+ /// the caller buckets.+ fn index_rule(+ &mut self,+ program: &RuleStore,+ rule: RuleID,+ group: ScopeGroupID,+ placement: SheetPlacement,+ added: &mut Vec<u32>,+ ) {+ let Some(selectors) = indexed_selectors(program, rule) else {+ return;+ };+ let version = program.rule_version(rule);+ // The conditions of the container rules around the rule are what it applies under,+ // whatever else says it is gated. A rule attached to several scopes, or with several+ // entries, has its gate once.+ let gate = match self.indexed.gate_of_rule.get(&rule) {+ Some(&gate) => Some(gate),+ None => program+ .native+ .targets+ .get(&rule)+ .map(|target| target.containers())+ .filter(|containers| !containers.is_empty())+ .map(|containers| {+ let key: Box<[usize]> = containers+ .iter()+ .map(|container| Arc::as_ptr(container).addr())+ .collect();+ let id = match self.indexed.gate_of_conditions.get(&key) {+ Some(&id) => id,+ None => {+ self.gates_ask_container_style |=+ super::super::container_queries::conditions_ask_container_style(containers);+ let id = ContainerGateID(+ u32::try_from(self.gates.len() + 1)+ .ok()+ .and_then(std::num::NonZeroU32::new)+ .expect("container gate space exhausted"),+ );+ self.gates.push(containers.into());+ self.indexed.gate_of_conditions.insert(key, id);+ id+ }+ };+ // NB: Only the rules under container conditions are noted, which most rules are+ // not: one with none finds that again as cheaply as it would be looked up.+ self.indexed.gate_of_rule.insert(rule, id);+ id+ }),+ };+ let layer_scope = self.layer_scope_of(group);+ let sheet = program.rule_sheet(rule);+ let placement = self.entries.place(sheet, group, version.layer, || EntryPlacement {+ origin: placement.origin,+ group,+ layer_rank: program.layer_rank(layer_scope, version.layer),+ sheet_rank: placement.sheet_rank,+ layer: version.layer,+ });+ let declared = program.declared_properties_of(rule);+ let declares_custom_properties = !program.custom_declarations_of(rule).is_empty();+ let declares_important = declared.iter().any(|declaration| declaration.important())+ || program+ .custom_declarations_of(rule)+ .iter()+ .any(|declaration| declaration.important());+ let rule_rank = program.rule_rank(rule);+ let scope = program.scope_chain(version.scope);+ for (of_rule, specificity, pseudo_kind) in entries_of(&selectors) {+ self.compiled_selectors += 1;+ let compiled = EntryFacts::of(super::super::component_matching::EntrySelector::new(+ of_rule,+ scope.map(|scope| &**scope),+ ));+ if compiled.never_matches {+ continue;+ }+ let id = self.entries.next_number();+ let selector = self.selectors.add(&selectors, of_rule.offset());+ self.entries.own.push(IndexedEntry {+ rule: EntryRule::document(rule),+ placement,+ selector,+ specificity: PackedSpecificity::pack(specificity),+ rule_rank,+ pseudo_kind,+ flags: EntryFlags(+ [+ (compiled.scoped, EntryFlags::SCOPED),+ (compiled.revalidates, EntryFlags::REVALIDATES),+ (declares_custom_properties, EntryFlags::DECLARES_CUSTOM_PROPERTIES),+ (declares_important, EntryFlags::DECLARES_IMPORTANT),+ (true, EntryFlags::LIVE),+ (gate.is_some(), EntryFlags::GATED),+ ]+ .into_iter()+ .filter(|&(holds, _)| holds)+ .fold(0, |flags, (_, flag)| flags | flag),+ ),+ });+ self.indexed.entries_of_rule.push(rule.0 as usize, id);+ if let Some(scope) = scope {+ self.entry_scopes.insert(id, Arc::clone(scope));+ }+ added.push(id);+ }+ }++ /// Kill the live entries of `rule`, or those deciding in `group` where it is some, noting the+ /// number of each in `died`.+ fn kill_rule(&mut self, rule: RuleID, group: Option<ScopeGroupID>, died: &mut Vec<u32>) {+ // https://drafts.csswg.org/css-conditional-3/#conditional-group-rules+ // NB: A rule of a sheet the process keeps in a segment leaves this document alone, so its+ // entries stay in the segment's shared buckets and invalidation map, marked dead here.+ for bound in &mut self.entries.segments {+ if !group.is_none_or(|group| bound.group == group) {+ continue;+ }+ let Some(offset) = rule.0.checked_sub(bound.first_rule.0) else {+ continue;+ };+ let dying: SmallVec<[u32; 4]> = (bound.first..bound.first + bound.segment.len())+ .filter(|&id| bound.segment.entries[(id - bound.first) as usize].rule == offset && !bound.is_dead(id))+ .collect();+ for id in dying {+ bound.note_dead(id);+ self.dead_entries += 1;+ died.push(id);+ }+ }+ let mut dying: SmallVec<[u32; 4]> = SmallVec::new();+ let entries = &self.entries;+ let left = self.indexed.entries_of_rule.retain(rule.0 as usize, |&id| {+ let dies = group.is_none_or(|group| entries.placement(id as usize).group == group);+ if dies {+ dying.push(id);+ }+ !dies+ });+ if left == 0 {+ self.indexed.entries_of_rule.remove(rule.0 as usize);+ }+ for id in dying {+ self.kill(id);+ died.push(id);+ }+ }++ /// Take the entry `id` out of every bucket it is in.+ fn kill(&mut self, id: u32) {+ let placement = *self.entries.placement(id as usize);+ let entry = self.entries.own_mut(id);+ debug_assert!(entry.live());+ entry.kill();+ self.dead_entries += 1;+ let (group, origin) = (placement.group, placement.origin);+ let source = self.source_of_entry(id);+ let scope = self.entry_scopes.get(&id).cloned();+ let entry_selector = super::super::component_matching::EntrySelector::new(source.selector(), scope.as_deref());+ let (keys, families) = placement_in_buckets(entry_selector.selector, EntryFacts::of(entry_selector));+ let remove = |scope_index: &mut ScopeIndex| scope_index.remove(id, &keys, families);+ match group {+ ScopeGroupID::DOCUMENT => {+ remove(&mut self.document);+ if is_non_author(origin) {+ remove(&mut self.document_non_author);+ }+ }+ _ => {+ if let Some(held) = self.groups.get_mut(&group) {+ remove(&mut held.index);+ }+ }+ }+ }++ /// Index again what `changes` moved alone: the entries of the rules and sheets it names that+ /// left die, and those that arrived are appended. The entries that stayed take the ranks of+ /// their sheets and layers where those moved. Answers what changed, for the elements it can+ /// restyle.+ pub(super) fn update(+ &mut self,+ program: &RuleStore,+ process_indexes: Option<&ProcessRuleIndexes>,+ changes: &IndexChanges<'_>,+ ) -> RuleIndexChanges {+ let first_added = self.entries.len();+ self.compiled_selectors = 0;+ self.built_user_agent_index = false;+ let mut died: Vec<u32> = Vec::new();+ let mut added: Vec<u32> = Vec::new();++ // The rules that moved, and those inside them, lose their entries, and their+ // declarations and gates are read again. Those of the user agent decide through the user+ // agent index, which the document shares again, and is bound to again.+ let mut rules: Vec<RuleID> = changes+ .rules+ .iter()+ .flat_map(|&rule| program.rule_subtree(rule))+ .collect();+ rules.sort_unstable();+ rules.dedup();+ let user_agent_moved = rules+ .iter()+ .any(|&rule| is_user_agent_sheet(program, program.rule_sheet(rule)))+ || changes.sheets.iter().any(|&sheet| is_user_agent_sheet(program, sheet));+ rules.retain(|&rule| !is_user_agent_sheet(program, program.rule_sheet(rule)));+ if user_agent_moved {+ let previous = self.bind_user_agent(program, process_indexes);+ let current = self.entries.user_agent.clone();+ let entries =+ |index: &Option<Arc<UserAgentIndex>>| index.as_ref().map_or(0, |index| index.index.entries.own.len());+ let same = |number: usize| match (&previous, ¤t) {+ (Some(previous), Some(current)) => same_user_agent_selector(previous, current, number),+ _ => false,+ };+ for number in 0..entries(&previous).max(entries(¤t)) {+ if same(number) {+ continue;+ }+ let number_u32 = u32::try_from(number).expect("rule entry space exhausted");+ if number < entries(&previous) {+ died.push(number_u32);+ }+ if number < entries(¤t) {+ added.push(number_u32);+ }+ }+ }+ // A sheet every rule of which moved, as one whose text was replaced, is indexed whole+ // again where it decides, as a sheet arriving is: in the segment of the process indexing+ // the same selectors where it has enough of them, rather than in the index's own buckets.+ let mut replaced: Vec<SheetID> = rules.iter().map(|&rule| program.rule_sheet(rule)).collect();+ replaced.sort_unstable();+ replaced.dedup();+ replaced.retain(|sheet| {+ if changes.sheets.contains(sheet) || !self.indexed.sheets.contains_key(sheet) {+ return false;+ }+ let live = program.rules_in_sheet(*sheet);+ !live.is_empty() && live.iter().all(|rule| rules.binary_search(rule).is_ok())+ });+ for &sheet in &replaced {+ let groups: SmallVec<[ScopeGroupID; 4]> =+ self.indexed.sheets[&sheet].iter().map(|&(group, _)| group).collect();+ for group in groups {+ self.drop_segments(Some(sheet), group, &mut died);+ }+ }+ for &rule in &rules {+ self.kill_rule(rule, None, &mut died);+ self.indexed.gate_of_rule.remove(&rule);+ }++ // A shadow tree whose sheets or layers moved stops deciding with the entries of the trees+ // it was alike to, and decides with those of the trees it is alike to now, which are+ // indexed where no tree had them. A group whose only tree moved takes what the tree has+ // instead, where no other group has it, and its entries change as the tree's sheets did.+ let mut sheets: Vec<SheetID> = changes+ .sheets+ .iter()+ .copied()+ .filter(|&sheet| !is_user_agent_sheet(program, sheet))+ .collect();+ sheets.sort_unstable();+ let mut moved_scopes: Vec<TreeScopeID> = changes+ .reordered_scopes+ .iter()+ .chain(changes.layered_scopes.iter())+ .copied()+ .chain(sheets.iter().flat_map(|&sheet| program.sheet_scopes(sheet)))+ .chain(sheets.iter().flat_map(|sheet| {+ self.indexed+ .sheets+ .get(sheet)+ .into_iter()+ .flatten()+ .flat_map(|&(group, _)| self.scopes_of(group).iter().copied())+ }))+ .filter(|&scope| scope != TreeScopeID::DOCUMENT)+ .collect();+ moved_scopes.sort_unstable();+ moved_scopes.dedup();+ let mut regrouped: Vec<Regrouped> = Vec::new();+ let mut reordered_groups: Vec<ScopeGroupID> = Vec::new();+ for scope in moved_scopes {+ let reordered = changes.reordered_scopes.contains(&scope) || changes.layered_scopes.contains(&scope);+ let sheets_in_scope = program.sheets_in_scope(scope);+ if let Some(group) = self.group_of_scope.get(&scope).copied() {+ let held = &self.groups[&group];+ if *held.sheets == *sheets_in_scope && program.layer_ranks_match(scope, &held.layer_ranks) {+ if reordered {+ reordered_groups.push(group);+ }+ continue;+ }+ if !sheets_in_scope.is_empty() && self.regroup_alone(program, scope) {+ reordered_groups.push(group);+ continue;+ }+ }+ let left = self.leave_group(program, scope, &mut died);+ let joined = match sheets_in_scope.is_empty() {+ true => None,+ false => match self.join_group(program, scope) {+ (group, true) => {+ self.index_sheets_of_group(program, group, process_indexes, &mut added);+ // NB: The entries of a new group arrived, and restyle what they match.+ None+ }+ (group, false) => Some(group),+ },+ };+ regrouped.push(Regrouped { scope, left, joined });+ }++ // A sheet that stopped deciding in a group loses its entries there; one that started is+ // indexed there.+ let mut ranked_groups: Vec<ScopeGroupID> = changes+ .reordered_scopes+ .iter()+ .chain(changes.layered_scopes.iter())+ .filter_map(|&scope| self.group_of(scope))+ .chain(reordered_groups.iter().copied())+ .collect();+ if changes.reordered_scopes.contains(&TreeScopeID::DOCUMENT)+ || changes.layered_scopes.contains(&TreeScopeID::DOCUMENT)+ {+ reordered_groups.push(ScopeGroupID::DOCUMENT);+ }+ let mut arriving: Vec<(SheetID, ScopeGroupID)> = Vec::new();+ for sheet in sheets {+ let mut attached: Vec<ScopeGroupID> = program+ .sheet_scopes(sheet)+ .into_iter()+ .filter_map(|scope| self.group_of(scope))+ .collect();+ attached.sort_unstable();+ attached.dedup();+ ranked_groups.extend(attached.iter().copied());+ let deciding = match program.sheet_contributes(sheet) {+ true => attached,+ false => Vec::new(),+ };+ let indexed = self.indexed.sheets.remove(&sheet).unwrap_or_default();+ let leaving: Vec<ScopeGroupID> = indexed+ .iter()+ .map(|&(group, _)| group)+ .filter(|group| !deciding.contains(group))+ .collect();+ ranked_groups.extend(indexed.iter().map(|&(group, _)| group));+ if !leaving.is_empty() {+ for &group in &leaving {+ self.drop_segments(Some(sheet), group, &mut died);+ // NB: Where it decides next it stands where it stands then.+ self.entries.placements_of_sheet.remove(&(sheet, group));+ }+ for rule in program.all_rules_in_sheet(sheet) {+ for &group in &leaving {+ self.kill_rule(rule, Some(group), &mut died);+ }+ }+ }+ let kept: SmallVec<[(ScopeGroupID, u64); 1]> = indexed+ .into_iter()+ .filter(|(group, _)| deciding.contains(group))+ .collect();+ arriving.extend(+ deciding+ .iter()+ .filter(|&&group| kept.iter().all(|&(indexed, _)| indexed != group))+ .map(|&group| (sheet, group)),+ );+ if !kept.is_empty() {+ self.indexed.sheets.insert(sheet, kept);+ }+ }++ // The rules that moved are indexed again where their sheets stayed, and the sheets that+ // arrived are indexed whole.+ for &rule in &rules {+ let sheet = program.rule_sheet(rule);+ if replaced.binary_search(&sheet).is_ok() {+ continue;+ }+ let Some(groups) = self.indexed.sheets.get(&sheet) else {+ continue;+ };+ let groups: SmallVec<[ScopeGroupID; 4]> = groups.iter().map(|&(group, _)| group).collect();+ for group in groups {+ let placement = self.placement(program, sheet, group);+ let first_added = added.len();+ self.index_rule(program, rule, group, placement, &mut added);+ for &id in &added[first_added..] {+ self.bucket(id);+ }+ }+ }+ for sheet in replaced {+ for (group, _) in self.indexed.sheets.remove(&sheet).unwrap_or_default() {+ self.entries.placements_of_sheet.remove(&(sheet, group));+ self.index_sheet(program, sheet, group, process_indexes, &mut added);+ }+ }+ for (sheet, group) in arriving {+ self.index_sheet(program, sheet, group, process_indexes, &mut added);+ }++ // The entries that stayed take the ranks their rules moved to, which keeps their order+ // where the rule order of their sheet was only relabeled.+ let mut relabeled: Vec<SheetID> = rules.iter().map(|&rule| program.rule_sheet(rule)).collect();+ relabeled.sort_unstable();+ relabeled.dedup();+ for sheet in relabeled {+ let relabels = program.rule_order_relabels(sheet);+ if self.indexed.rule_order_relabels.insert(sheet, relabels) == Some(relabels) {+ continue;+ }+ // NB: The documents sharing a segment share the rule order its entries hold.+ for place in (0..self.entries.segments.len()).rev() {+ let bound = &self.entries.segments[place];+ if bound.sheet == sheet+ && (bound.first..bound.first + bound.segment.len()).any(|id| {+ let entry = bound.entry(id);+ entry.rule_rank != program.rule_rank(RuleID(entry.rule.0))+ })+ {+ self.copy_segment_out(place);+ }+ }+ for rule in program.all_rules_in_sheet(sheet) {+ let rule_rank = program.rule_rank(rule);+ let ids: SmallVec<[u32; 4]> = self.indexed.entries_of_rule.get(rule.0 as usize).collect();+ for id in ids {+ if self.entries.view(id as usize).rule_rank() != rule_rank {+ self.entries.own_mut(id).rule_rank = rule_rank;+ }+ }+ }+ }++ // And the ranks their sheets and layers moved to, where an entry that moved against+ // another in the cascade order restyles the elements it matched.+ ranked_groups.sort_unstable();+ ranked_groups.dedup();+ let mut moved: Vec<u32> = Vec::new();+ for group in ranked_groups {+ // NB: A group that died has no sheets to rank.+ if group != ScopeGroupID::DOCUMENT && !self.groups.contains_key(&group) {+ continue;+ }+ let reordered = reordered_groups.contains(&group);+ let layer_scope = self.layer_scope_of(group);+ let mut stayed: Vec<StayedEntry> = Vec::new();+ let group_sheets: SmallVec<[SheetID; 8]> = self.sheets_of_group(program, group).iter().copied().collect();+ for sheet in group_sheets {+ let sheet_rank = self.placement(program, sheet, group).sheet_rank;+ let Some(slot) = self+ .indexed+ .sheets+ .get_mut(&sheet)+ .and_then(|groups| groups.iter_mut().find(|(indexed, _)| *indexed == group))+ else {+ continue;+ };+ let sheet_moved = std::mem::replace(&mut slot.1, sheet_rank) != sheet_rank;+ if !sheet_moved && !reordered {+ continue;+ }+ for bound in &self.entries.segments {+ if bound.sheet == sheet && bound.group == group {+ stayed.extend(+ (bound.first..bound.first + bound.segment.len())+ .filter(|&id| (id as usize) < first_added)+ .map(|id| StayedEntry::of(id, &self.entries)),+ );+ }+ }+ for rule in program.rules_in_sheet(sheet) {+ for id in self.indexed.entries_of_rule.get(rule.0 as usize) {+ if self.entries.placement(id as usize).group != group || id as usize >= first_added {+ continue;+ }+ stayed.push(StayedEntry::of(id, &self.entries));+ }+ }+ // The entries take the ranks of their sheet and layers where they are placed.+ self.entries.rank_placements_of(sheet, group, |placement| {+ placement.sheet_rank = sheet_rank;+ placement.layer_rank = program.layer_rank(layer_scope, placement.layer);+ });+ }+ // NB: A sheet whose rank was only relabeled keeps its order against the others.+ if reordered {+ super::rule_changes::note_moved(&self.entries, &stayed, &mut moved);+ }+ }+ // An update that added at least as many entries as the index had gives back the room its+ // growth reserved, as a build does: each entry pays for that once, however the rules+ // arrive. One that moved many rules' entry lists gives back the room they left.+ if self.entries.len() - first_added >= first_added.saturating_sub(self.entries.own_numbers().start) {+ self.shrink_to_fit();+ } else if self.indexed.entries_of_rule.has_slack() {+ self.indexed.entries_of_rule.shrink_to_fit();+ }+ self.share_entries(process_indexes);++ RuleIndexChanges::new(self, died, &moved, &added, user_agent_moved, regrouped)+ }++ /// The buckets holding the entries `entries` alone, where they are live.+ pub(super) fn buckets_of(&self, entries: &[u32]) -> RuleIndex {+ let mut buckets = RuleIndex::default();+ for &id in entries {+ let entry = self.entries.entry(id as usize);+ if !entry.live() {+ continue;+ }+ let placement = self.entries.placement(id as usize);+ buckets.bucket_as(+ id,+ &self.source_of_entry(id),+ self.entry_scopes.get(&id).map(|scope| &**scope),+ placement.group,+ placement.origin,+ );+ }+ // The shadow trees reach the entries of their groups.+ buckets.group_of_scope = self+ .group_of_scope+ .iter()+ .filter(|(_, group)| buckets.groups.contains_key(group))+ .map(|(&scope, &group)| (scope, group))+ .collect();+ buckets+ }++ /// The live entries of `group`.+ pub(super) fn live_entries_of(&self, group: ScopeGroupID) -> Vec<u32> {+ self.entries+ .own_numbers()+ .filter(|&id| {+ let view = self.entries.view(id);+ view.live() && self.entries.placement_of(view).group == group+ })+ .map(|id| u32::try_from(id).expect("rule entry space exhausted"))+ .collect()+ }+}++/// Whether the entry `number` of the user agent indexes `before` and `after` is of the same selector.+fn same_user_agent_selector(before: &UserAgentIndex, after: &UserAgentIndex, number: usize) -> bool {+ let (before, after) = (&before.index, &after.index);+ let number_u32 = u32::try_from(number).expect("rule entry space exhausted");+ number < before.entries.own.len().min(after.entries.own.len())+ && before.selector_of_entry(number_u32).key() == after.selector_of_entry(number_u32).key()+}++/// Whether each number of the user agent's entries of `previous` stands for the same selector in+/// `current`.+fn stays_in_user_agent_index<'a>(previous: &'a RuleIndex, current: &'a RuleIndex) -> impl Fn(usize) -> bool + 'a {+ move |number| match (&previous.entries.user_agent, ¤t.entries.user_agent) {+ (Some(before), Some(after)) if Arc::ptr_eq(before, after) => true,+ (Some(before), Some(after)) => same_user_agent_selector(before, after, number),+ _ => false,+ }+}++/// The keys an entry's subject can be reached by, and the families of its scope's buckets it is+/// in besides its own elements'.+fn placement_in_buckets(+ selector: crate::css::selector::Selector<'_>,+ compiled: EntryFacts,+) -> (SmallVec<[DispatchKey; 4]>, Families) {+ let mut keys = subject_dispatch_keys(selector);+ if keys.is_empty()+ && let Some(key) = state_dispatch_key(selector)+ {+ keys.push(key);+ }+ let families = Families {+ revalidates: compiled.revalidates,+ host: compiled.host,+ slotted: compiled.slotted,+ part: compiled.part,+ };+ (keys, families)+}++/// Put `slot` in the buckets of `group` in `index`, and in the document's non-author buckets+/// where it is of a user agent or user sheet of the document.+fn insert_entry(+ index: &mut RuleIndex,+ group: ScopeGroupID,+ origin: CascadeOrigin,+ slot: BucketEntry,+ keys: &[DispatchKey],+ families: Families,+) {+ let scope_index = match group {+ ScopeGroupID::DOCUMENT => &mut index.document,+ _ => {+ &mut index+ .groups+ .entry(group)+ .or_insert_with(|| ScopeGroup {+ index: ScopeIndex::default(),+ scopes: SmallVec::new(),+ sheets: Box::default(),+ layer_ranks: HashMap::default(),+ })+ .index+ }+ };+ scope_index.insert(slot, keys, families);+ if group == ScopeGroupID::DOCUMENT && is_non_author(origin) {+ index.document_non_author.insert(slot, keys, families);+ }+}++/// The families of a scope's buckets an entry is in besides its own elements'.+#[derive(Clone, Copy)]+struct Families {+ revalidates: bool,+ host: bool,+ slotted: bool,+ part: bool,+}++impl ScopeIndex {+ /// Releases what the buckets reserved beyond the entries they hold.+ fn shrink_to_fit(&mut self) {+ for buckets in [+ &mut self.own,+ &mut self.own_revalidation,+ &mut self.host,+ &mut self.slotted,+ &mut self.part,+ ] {+ buckets.shrink_to_fit();+ }+ }++ fn families_mut(&mut self, families: Families) -> [(bool, &mut Buckets); 5] {+ [+ (true, &mut self.own),+ (families.revalidates, &mut self.own_revalidation),+ (families.host, &mut self.host),+ (families.slotted, &mut self.slotted),+ (families.part, &mut self.part),+ ]+ }++ fn insert(&mut self, slot: BucketEntry, keys: &[DispatchKey], families: Families) {+ for (member, buckets) in self.families_mut(families) {+ if member {+ insert(buckets, slot, keys);+ }+ }+ }++ fn remove(&mut self, entry: u32, keys: &[DispatchKey], families: Families) {+ for (member, buckets) in self.families_mut(families) {+ if member {+ remove(buckets, entry, keys);+ }+ }+ }+}++/// The keys of the buckets an entry reached by `keys` is in.+fn bucket_keys(keys: &[DispatchKey]) -> &[DispatchKey] {+ if keys.is_empty() || !keys.iter().all(is_probed) {+ return &[DispatchKey::Universal];+ }+ keys+}++fn insert(buckets: &mut Buckets, mut bucket_entry: BucketEntry, keys: &[DispatchKey]) {+ let keys = bucket_keys(keys);+ if keys.len() > 1 {+ bucket_entry.entry |= BucketEntry::IN_OTHER_BUCKETS;+ }+ for &key in keys {+ buckets.push(key, &bucket_entry);+ }+}++fn remove(buckets: &mut Buckets, entry: u32, keys: &[DispatchKey]) {+ for key in bucket_keys(keys) {+ buckets.remove(key, entry);+ }+ // NB: Packing the lists again once half the backing is room no list holds keeps the room the+ // removals and moved lists leave bounded, at an amortized constant cost per removal.+ if buckets.has_slack() {+ buckets.shrink_to_fit();+ }+}++#[cfg(test)]+mod tests {+ use super::super::rule_store::RuleKind;+ use super::*;++ /// The selectors `text` writes.+ fn sourced(text: &str) -> crate::css::selector::SelectorListRef {+ let parsed = crate::css::selector_parser::parse_selector_list(+ &text.encode_utf16().collect::<Vec<u16>>()[..],+ &[],+ crate::css::selector_parser::SelectorType::Standalone,+ crate::css::selector_parser::SelectorParsingMode::Standard,+ )+ .expect("a test writes valid selectors");+ crate::css::selector::SelectorListRef::pack(&parsed.selectors)+ }++ /// Append a style rule with the selectors `text` writes to `sheet`.+ fn add_rule(program: &mut RuleStore, sheet: SheetID, text: &str) -> RuleID {+ let rule = program.append_rule(sheet, None, RuleKind::Style);+ let mut version = program.rule_version(rule).clone();+ version.selectors = program.start_of_selectors(sheet, &sourced(text));+ program.replace_rule_version(rule, version);+ rule+ }++ fn count(buckets: &Buckets) -> usize {+ buckets.count()+ }++ /// Have a sheet of `program` stand for the user agent sheet of `process` whose rules select+ /// `selectors`, which the process publishes from the native sheet `source`.+ fn attach_user_agent_sheet(+ program: &mut RuleStore,+ process: &Arc<crate::css::style::ProcessStyle>,+ source: u64,+ selectors: &[&crate::css::selector::SelectorListRef],+ ) -> SheetID {+ process.publish_user_agent_sheet(source, |engine, sheet| {+ for &selectors in selectors {+ let rule = engine.rules.append_rule(sheet, None, RuleKind::Style);+ let mut version = engine.rules.rule_version(rule).clone();+ version.selectors = engine.rules.start_of_selectors(sheet, selectors);+ engine.rules.replace_rule_version(rule, version);+ }+ });+ let rules = process.user_agent_rules();+ let published = rules.sheet_of_source(source).expect("the sheet was published");+ let sheet = program.add_sheet(CascadeOrigin::UserAgent);+ program.bind_user_agent_sheet(sheet, rules, published);+ program.attach_sheet(sheet, TreeScopeID::DOCUMENT);+ sheet+ }++ #[test]+ fn rules_are_indexed_per_tree_scope_and_attachment() {+ let mut program = RuleStore::new();+ let first_scope = TreeScopeID(1);+ let second_scope = TreeScopeID(2);++ // The document: a user agent rule, an author rule and an author `::part()` rule.+ let process = Arc::<crate::css::style::ProcessStyle>::default();+ attach_user_agent_sheet(&mut program, &process, 1, &[&sourced(&format!(".c{}", 100))]);+ let document = program.add_sheet(CascadeOrigin::Author);+ program.attach_sheet(document, TreeScopeID::DOCUMENT);+ add_rule(&mut program, document, &format!(".c{}", 101));+ add_rule(&mut program, document, "::part(p102)");++ // The first shadow tree's own sheet: `:host` and `::slotted(.x)`.+ let own = program.add_sheet(CascadeOrigin::Author);+ program.attach_sheet(own, first_scope);+ add_rule(&mut program, own, ":host");+ add_rule(&mut program, own, "::slotted(.c103)");++ // A constructed sheet both shadow trees adopt.+ let shared = program.add_sheet(CascadeOrigin::Author);+ program.attach_sheet(shared, first_scope);+ program.attach_sheet(shared, second_scope);+ let shared_rule = add_rule(&mut program, shared, &format!(".c{}", 104));++ let index = RuleIndex::build(&program, None);+ let entries = || {+ index+ .entries+ .numbers()+ .map(|number| (number as u32, index.entries.entry(number)))+ };++ // One entry per rule and attachment.+ assert_eq!(index.entries.count(), 7);+ for (scope, expected) in [(TreeScopeID::DOCUMENT, 3), (first_scope, 3), (second_scope, 1)] {+ let group = index.group_of(scope).expect("the scope has sheets");+ assert_eq!(+ entries()+ .filter(|&(number, _)| index.entries.placement(number as usize).group == group)+ .count(),+ expected+ );+ }+ // The adopted sheet's rule is indexed for each scope, sharing its compiled selector and+ // declarations.+ let shared_entries: Vec<_> = entries()+ .filter(|&(number, _)| index.rule_of(number) == shared_rule)+ .collect();+ assert_eq!(shared_entries.len(), 2);+ assert!(+ index.selector_of_entry(shared_entries[0].0).key() == index.selector_of_entry(shared_entries[1].0).key()+ );+ assert_ne!(+ index.entries.placement(shared_entries[0].0 as usize).group,+ index.entries.placement(shared_entries[1].0 as usize).group+ );++ // The user agent rule is in the user agent index alone.+ assert_eq!(count(&index.document.own), 2);+ assert_eq!(count(&index.document.part), 1);+ assert_eq!(count(&index.document.host), 0);+ assert_eq!(count(&index.document.slotted), 0);+ assert_eq!(count(&index.document_non_author.own), 0);+ let user_agent = index.user_agent_buckets().expect("the user agent sheet has a rule");+ assert_eq!(count(&user_agent.buckets.own), 1);+ assert_eq!(count(&user_agent.buckets.part), 0);++ let first = index.scope_index(first_scope).expect("the first scope has sheets");+ assert_eq!(count(&first.own), 3);+ assert_eq!(count(&first.host), 1);+ assert_eq!(count(&first.slotted), 1);+ assert_eq!(count(&first.part), 0);+ let second = index.scope_index(second_scope).expect("the second scope has sheets");+ assert_eq!(count(&second.own), 1);+ assert_eq!(count(&second.host) + count(&second.slotted) + count(&second.part), 0);+ assert!(index.scope_index(TreeScopeID(3)).is_none());+ }++ #[test]+ fn shadow_trees_with_the_same_sheets_share_their_entries() {+ let mut program = RuleStore::new();+ let scopes: Vec<TreeScopeID> = (1..=3).map(TreeScopeID).collect();+ let shared = program.add_sheet(CascadeOrigin::Author);+ for &scope in &scopes {+ program.attach_sheet(shared, scope);+ }+ add_rule(&mut program, shared, &format!(".c{}", 100));+ add_rule(&mut program, shared, &format!(".c{}", 101));+ let mut index = RuleIndex::build(&program, None);+ let update = |index: &mut RuleIndex, program: &RuleStore, sheet: SheetID| {+ index.update(+ program,+ None,+ &IndexChanges {+ rules: &HashSet::default(),+ sheets: &[sheet].into_iter().collect(),+ reordered_scopes: &HashSet::default(),+ layered_scopes: &HashSet::default(),+ },+ )+ };++ // The three trees are one group, whose entries are indexed once.+ assert_eq!(index.entries.count(), 2);+ assert_eq!(index.indexed_entries, 2);+ let group = index.group_of(scopes[0]).expect("the scope has sheets");+ assert_eq!(index.scopes_of(group), &scopes[..]);++ // A tree taking another sheet leaves the group for one of its own, and the elements of+ // that tree alone are restyled.+ let own = program.add_sheet(CascadeOrigin::Author);+ program.attach_sheet(own, scopes[1]);+ add_rule(&mut program, own, &format!(".c{}", 102));+ let changes = update(&mut index, &program, own);+ let diverged = index.group_of(scopes[1]).expect("the scope has sheets");+ assert_ne!(diverged, group);+ assert_eq!(index.scopes_of(group), [scopes[0], scopes[2]]);+ assert_eq!(index.scopes_of(diverged), [scopes[1]]);+ assert_eq!(changes.arrived_entries, 3);+ assert!(changes.died().is_empty());+ assert_eq!(changes.scopes, [scopes[1]]);++ // Giving the sheet up has it join the group again, and the group of its own dies.+ program.detach_sheet(own, scopes[1]);+ let changes = update(&mut index, &program, own);+ assert_eq!(index.group_of(scopes[1]), Some(group));+ assert!(index.scopes_of(diverged).is_empty());+ assert_eq!(changes.arrived_entries, 0);+ assert_eq!(changes.died().len(), 3);+ assert_eq!(changes.scopes, [scopes[1]]);+ assert_eq!(index.groups.len(), 1);+ }++ #[test]+ fn documents_with_the_same_user_agent_rules_share_one_user_agent_index() {+ // The process compiles one selector program for each user agent rule, which every+ // document's rule attaches.+ let programs: Vec<crate::css::selector::SelectorListRef> =+ (0..3).map(|atom| sourced(&format!(".c{}", 100 + atom))).collect();+ let process = Arc::<crate::css::style::ProcessStyle>::default();+ let document = |user_agent_sheets: &[&[usize]]| {+ let mut program = RuleStore::new();+ for rules in user_agent_sheets {+ let source = rules.iter().fold(1, |source, &rule| source * 10 + rule as u64);+ let selectors: Vec<_> = rules.iter().map(|&rule| &programs[rule]).collect();+ attach_user_agent_sheet(&mut program, &process, source, &selectors);+ }+ let author = program.add_sheet(CascadeOrigin::Author);+ program.attach_sheet(author, TreeScopeID::DOCUMENT);+ add_rule(&mut program, author, &format!(".c{}", 200));+ program+ };+ let indexes = ProcessRuleIndexes::default();++ // The first document builds the user agent index, and the second shares it.+ let first = RuleIndex::build(&document(&[&[0, 1]]), Some(&indexes));+ assert!(first.built_user_agent_index);+ let second = RuleIndex::build(&document(&[&[0, 1]]), Some(&indexes));+ assert!(!second.built_user_agent_index);+ assert!(Arc::ptr_eq(+ first.user_agent_index().unwrap(),+ second.user_agent_index().unwrap()+ ));+ // Their invalidation maps start from the user agent index's, sharing what it holds rather+ // than copying it, and hold their own selectors' alone.+ use super::super::invalidation::InvalidationMap;+ let (first_map, second_map) = (InvalidationMap::build(&first), InvalidationMap::build(&second));+ let (first_map, second_map) = (first_map.base(), second_map.base());+ assert!(first_map.starts_from(&first.user_agent_index().unwrap().invalidation));+ assert!(second_map.starts_from(&first.user_agent_index().unwrap().invalidation));+ assert_eq!(+ second_map.by_trigger.own_keys().count() + second_map.lone_by_trigger.own_keys().count(),+ 1+ );+ // Its entries are numbered below the document's own, which count only those.+ assert_eq!(second.indexed_entries, 1);+ assert_eq!(+ second.entries.numbers().collect::<Vec<_>>(),+ [0, 1, FIRST_DOCUMENT_ENTRY as usize]+ );++ // A document with another user agent sheet decides with another index, in which the+ // rules both have keep their numbers.+ let third = RuleIndex::build(&document(&[&[0, 1], &[2]]), Some(&indexes));+ assert!(third.built_user_agent_index);+ let stays = stays_in_user_agent_index(&first, &third);+ assert!(stays(0) && stays(1) && !stays(2));+ assert_eq!(first.renumbering_from(&first)[..2], [Some(0), Some(1)]);++ // Each document's entries name its own rules and declarations.+ let fourth_program = document(&[&[0, 1]]);+ let fourth = RuleIndex::build(&fourth_program, Some(&indexes));+ assert!(!fourth.built_user_agent_index);+ let user_agent_rules: Vec<RuleID> = fourth_program+ .rules_in_sheet(fourth_program.sheets_in_scope(TreeScopeID::DOCUMENT)[0])+ .into_iter()+ .collect();+ assert_eq!([fourth.rule_of(0), fourth.rule_of(1)], user_agent_rules[..]);++ // A document attaching the process's sheets in another order than the process published+ // them in has them decide in its order.+ let reversed = RuleIndex::build(&document(&[&[2], &[0, 1]]), Some(&indexes));+ assert!(reversed.built_user_agent_index);+ let rank = |entry: usize| reversed.entries.placement(entry).sheet_rank;+ assert!(rank(0) < rank(1) && rank(1) == rank(2));+ assert_eq!(reversed.selector_of_entry(0).key(), third.selector_of_entry(2).key());+ }++ #[test]+ fn documents_indexing_the_same_sheet_share_its_segment() {+ // The process compiles one selector program for each selector of a sheet whose parsed+ // contents documents share, which every document's rule attaches.+ let programs: Vec<crate::css::selector::SelectorListRef> = (0..SEGMENT_MIN_ENTRIES as u32)+ .map(|atom| sourced(&format!(".c{}", 300 + atom)))+ .collect();+ let document = || {+ let mut program = RuleStore::new();+ let sheet = program.add_sheet(CascadeOrigin::Author);+ program.attach_sheet(sheet, TreeScopeID::DOCUMENT);+ for selectors in &programs {+ let id = program.append_rule(sheet, None, RuleKind::Style);+ let mut version = program.rule_version(id).clone();+ version.selectors = program.start_of_selectors(sheet, selectors);+ program.replace_rule_version(id, version);+ }+ (program, sheet)+ };+ let indexes = ProcessRuleIndexes::default();+ let (first_program, sheet) = document();+ let (second_program, _) = document();+ let mut first = RuleIndex::build(&first_program, Some(&indexes));+ let second = RuleIndex::build(&second_program, Some(&indexes));++ // Both bucket the sheet's entries in one segment, and none in buckets of their own.+ assert_eq!(first.entries.segments.len(), 1);+ assert!(Arc::ptr_eq(+ &first.entries.segments[0].segment,+ &second.entries.segments[0].segment+ ));+ assert_eq!(count(&first.document.own), 0);+ assert_eq!(first.bucket_sources(ScopeGroupID::DOCUMENT, false).count(), 2);++ // A rule of the sheet that dies is dead for that document alone, which keeps the segment+ // and buckets nothing itself.+ let rule = first_program.rules_in_sheet(sheet).into_iter().next().unwrap();+ let mut died = Vec::new();+ first.kill_rule(rule, None, &mut died);+ assert!(!died.is_empty());+ assert_eq!(first.entries.segments.len(), 1);+ assert_eq!(count(&first.document.own), 0);+ assert!(died.iter().all(|&id| !first.entries.view(id as usize).live()));+ assert!(died.iter().all(|&id| second.entries.view(id as usize).live()));+ // NB: The process keeps it too, for a document of a page yet to come.+ assert_eq!(Arc::strong_count(&second.entries.segments[0].segment), 3);+ }++ #[test]+ fn a_sheet_whose_rules_were_all_replaced_binds_a_segment() {+ let indexes = ProcessRuleIndexes::default();+ let mut program = RuleStore::new();+ let sheet = program.add_sheet(CascadeOrigin::Author);+ program.attach_sheet(sheet, TreeScopeID::DOCUMENT);+ let replaced: Vec<RuleID> = (0..SEGMENT_MIN_ENTRIES as u32)+ .map(|atom| add_rule(&mut program, sheet, &format!(".c{}", 500 + atom)))+ .collect();+ let mut index = RuleIndex::build(&program, Some(&indexes));+ assert_eq!(index.entries.segments.len(), 1);++ // The sheet's text is replaced: every rule leaves, and as many others arrive.+ let mut moved: HashSet<RuleID> = replaced.iter().copied().collect();+ for &rule in &replaced {+ program.remove_rule(rule);+ }+ for atom in 0..SEGMENT_MIN_ENTRIES as u32 {+ moved.insert(add_rule(&mut program, sheet, &format!(".c{}", 600 + atom)));+ }+ index.update(+ &program,+ Some(&indexes),+ &IndexChanges {+ rules: &moved,+ sheets: &HashSet::default(),+ reordered_scopes: &HashSet::default(),+ layered_scopes: &HashSet::default(),+ },+ );++ // The arriving rules are bucketed in a segment, as those of an arriving sheet are, and the+ // document buckets none of the sheet's entries itself.+ assert_eq!(index.entries.segments.len(), 1);+ assert_eq!(index.entries.segments[0].segment.len(), SEGMENT_MIN_ENTRIES as u32);+ assert_eq!(count(&index.document.own), 0);+ }++ #[test]+ fn animation_names_are_declared_in_the_scope_of_their_attachment() {+ use super::super::super::animations::DeclarationScope;+ use super::super::cascade::declaration_scope;+ let mut program = RuleStore::new();+ let first_scope = TreeScopeID(1);+ let second_scope = TreeScopeID(2);++ let process = Arc::<crate::css::style::ProcessStyle>::default();+ let user_agent = attach_user_agent_sheet(&mut program, &process, 1, &[&sourced(&format!(".c{}", 100))]);+ let user_agent_rule = program.rules_in_sheet(user_agent)[0];+ let document = program.add_sheet(CascadeOrigin::Author);+ program.attach_sheet(document, TreeScopeID::DOCUMENT);+ let document_rule = add_rule(&mut program, document, &format!(".c{}", 101));+ // A constructed sheet the document and two shadow trees adopt.+ let shared = program.add_sheet(CascadeOrigin::Author);+ program.attach_sheet(shared, TreeScopeID::DOCUMENT);+ program.attach_sheet(shared, first_scope);+ program.attach_sheet(shared, second_scope);+ let shared_rule = add_rule(&mut program, shared, &format!(".c{}", 102));++ let index = RuleIndex::build(&program, None);+ let scope_of = |rule: RuleID, scope: TreeScopeID| {+ let entry = index+ .entries+ .numbers()+ .find(|&number| {+ index.rule_of(number as u32) == rule+ && Some(index.entries.placement(number).group) == index.group_of(scope)+ })+ .expect("the rule is indexed for the scope");+ declaration_scope(&index.entries, entry as u32, scope)+ };+ assert_eq!(+ scope_of(user_agent_rule, TreeScopeID::DOCUMENT),+ DeclarationScope::Unscoped+ );+ assert_eq!(+ scope_of(document_rule, TreeScopeID::DOCUMENT),+ DeclarationScope::Unscoped+ );+ // Each attachment of the adopted sheet declares in its own scope, though the rule is one.+ assert_eq!(scope_of(shared_rule, TreeScopeID::DOCUMENT), DeclarationScope::Unscoped);+ assert_eq!(+ scope_of(shared_rule, first_scope),+ DeclarationScope::Shadow(first_scope)+ );+ assert_eq!(+ scope_of(shared_rule, second_scope),+ DeclarationScope::Shadow(second_scope)+ );+ // An element's own declarations have no scope.+ assert_eq!(+ declaration_scope(&index.entries, u32::MAX, TreeScopeID::DOCUMENT),+ DeclarationScope::Unscoped+ );+ }+}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/shared_pages.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/shared_pages.rsnew file mode 100644index 00000000000..7760dee4a03--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/shared_pages.rs@@ -0,0 +1,175 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! A vector held in pages that documents holding equal pages share through a pool of the+//! process's: frames of a site whose rules are numbered alike hold one copy of each page.+//!+//! A page is shared once it is published to the pool, and copied by the first edit after that, so+//! an edit never reaches another holder of the page.++use super::super::weak_pool::WeakPool;+use std::hash::{Hash, Hasher};+use std::sync::{Arc, Mutex};++pub(super) const VALUES_PER_PAGE: usize = 128;++#[derive(Clone)]+pub(super) struct Page<T> {+ values: Vec<T>,+ /// The hash the page is published to the pool under, or none while it is unpublished.+ shared_hash: Option<u64>,+}++/// The pool of a process's pages of one kind.+pub(super) type PagePool<T> = Mutex<WeakPool<Page<T>>>;++#[derive(Clone)]+pub(super) struct SharedPages<T> {+ pages: Vec<Arc<Page<T>>>,+ len: usize,+}++impl<T> Default for SharedPages<T> {+ fn default() -> Self {+ Self {+ pages: Vec::new(),+ len: 0,+ }+ }+}++impl<T: Clone + PartialEq + Hash> SharedPages<T> {+ pub(super) fn len(&self) -> usize {+ self.len+ }++ pub(super) fn get(&self, index: usize) -> Option<&T> {+ (index < self.len).then(|| &self.pages[index / VALUES_PER_PAGE].values[index % VALUES_PER_PAGE])+ }++ pub(super) fn get_mut(&mut self, index: usize) -> &mut T {+ assert!(index < self.len);+ let page = Arc::make_mut(&mut self.pages[index / VALUES_PER_PAGE]);+ page.shared_hash = None;+ &mut page.values[index % VALUES_PER_PAGE]+ }++ pub(super) fn push(&mut self, value: T) {+ if self.len.is_multiple_of(VALUES_PER_PAGE) {+ self.pages.push(Arc::new(Page {+ values: Vec::with_capacity(VALUES_PER_PAGE),+ shared_hash: None,+ }));+ }+ let page = Arc::make_mut(self.pages.last_mut().expect("a page has room"));+ page.shared_hash = None;+ page.values.push(value);+ self.len += 1;+ }++ /// Keep the first `len` values alone.+ pub(super) fn truncate(&mut self, len: usize) {+ if len >= self.len {+ return;+ }+ self.pages.truncate(len.div_ceil(VALUES_PER_PAGE));+ if let Some(last) = self.pages.last_mut()+ && !len.is_multiple_of(VALUES_PER_PAGE)+ {+ let page = Arc::make_mut(last);+ page.shared_hash = None;+ page.values.truncate(len % VALUES_PER_PAGE);+ }+ self.len = len;+ }++ pub(super) fn shrink_to_fit(&mut self) {+ self.pages.shrink_to_fit();+ if let Some(last) = self.pages.last_mut()+ && last.values.len() != last.values.capacity()+ {+ Arc::make_mut(last).values.shrink_to_fit();+ }+ }++ /// Publish the pages to `pool`, taking an equal page another holder published instead of each.+ pub(super) fn share(&mut self, pool: &PagePool<T>) {+ let mut pool = pool.lock().unwrap_or_else(std::sync::PoisonError::into_inner);+ for page in &mut self.pages {+ if page.shared_hash.is_some() {+ continue;+ }+ let mut hasher = super::super::fast_hash::fast_hasher();+ page.values.hash(&mut hasher);+ let hash = hasher.finish();+ if let Some(found) = pool.find(hash, |candidate| candidate.values == page.values) {+ *page = found;+ continue;+ }+ Arc::make_mut(page).shared_hash = Some(hash);+ pool.insert(hash, page);+ }+ }++ /// The bytes of the pages, each counted the first time `sizer` reaches it, with what+ /// `value_heap` says each value holds.+ pub(super) fn heap_size(+ &self,+ sizer: &mut crate::heap_size::HeapSizer,+ mut value_heap: impl FnMut(&T, &mut crate::heap_size::HeapSizer) -> usize,+ ) -> usize {+ let mut bytes = crate::heap_size::vec_bytes(&self.pages);+ for page in &self.pages {+ if sizer.first_sight(Arc::as_ptr(page)) {+ bytes += crate::heap_size::ARC_HEADER_BYTES+ + size_of::<Page<T>>()+ + crate::heap_size::vec_bytes(&page.values)+ + page.values.iter().map(|value| value_heap(value, sizer)).sum::<usize>();+ }+ }+ bytes+ }+}++impl<T: Clone + PartialEq + Hash> std::ops::Index<usize> for SharedPages<T> {+ type Output = T;++ fn index(&self, index: usize) -> &T {+ self.get(index).expect("an index within the pages")+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn equal_pages_share_and_an_edit_copies_only_its_page() {+ let pool = PagePool::<u32>::default();+ let make = || {+ let mut pages = SharedPages::default();+ for value in 0..(VALUES_PER_PAGE * 2 + 1) as u32 {+ pages.push(value);+ }+ pages.share(&pool);+ pages+ };+ let first = make();+ let mut second = make();+ for (left, right) in first.pages.iter().zip(&second.pages) {+ assert!(Arc::ptr_eq(left, right));+ }+ *second.get_mut(VALUES_PER_PAGE + 3) = 7;+ assert_eq!(first[VALUES_PER_PAGE + 3], (VALUES_PER_PAGE + 3) as u32);+ assert_eq!(second[VALUES_PER_PAGE + 3], 7);+ assert!(Arc::ptr_eq(&first.pages[0], &second.pages[0]));+ assert!(!Arc::ptr_eq(&first.pages[1], &second.pages[1]));+ second.push(9);+ assert_eq!(first.len(), VALUES_PER_PAGE * 2 + 1);+ assert_eq!(second.len(), first.len() + 1);+ assert_eq!(second[first.len()], 9);+ }+}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/shared_prefix.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/shared_prefix.rsnew file mode 100644index 00000000000..a3aea36febc--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/shared_prefix.rs@@ -0,0 +1,136 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! A vector that starts with the elements of a frozen one it shares with others, and goes on with+//! its own: a structure built once for the process, such as the invalidation map of the user+//! agent's rules, is the shared start of every document's, which adds its own after it, and the+//! numbers of the shared elements are the same in every document.++use std::ops::{Index, IndexMut, Range};+use std::sync::Arc;++#[derive(Clone)]+pub(super) struct SharedPrefixVec<T> {+ shared: Arc<[T]>,+ own: Vec<T>,+}++impl<T> Default for SharedPrefixVec<T> {+ fn default() -> Self {+ Self {+ shared: Arc::from(Vec::new()),+ own: Vec::new(),+ }+ }+}++impl<T: Clone> SharedPrefixVec<T> {+ pub(super) fn len(&self) -> usize {+ self.shared.len() + self.own.len()+ }++ pub(super) fn push(&mut self, value: T) {+ self.own.push(value);+ }++ #[cfg(test)]+ pub(super) fn iter(&self) -> impl Iterator<Item = &T> {+ self.shared.iter().chain(&self.own)+ }++ pub(super) fn shrink_to_fit(&mut self) {+ self.own.shrink_to_fit();+ }++ /// Make every element shared: clones of the vector then share all of them.+ pub(super) fn freeze(&mut self) {+ if self.own.is_empty() {+ return;+ }+ let mut all = Vec::with_capacity(self.len());+ all.extend_from_slice(&self.shared);+ all.append(&mut self.own);+ self.shared = Arc::from(all);+ self.own = Vec::new();+ }++ /// Whether the vector shares every element `base` holds, all of which it shares.+ #[cfg(test)]+ pub(super) fn shares_prefix_of(&self, base: &Self) -> bool {+ base.own.is_empty() && Arc::ptr_eq(&self.shared, &base.shared)+ }++ /// The bytes of the vector's own elements.+ pub(super) fn heap_size(&self) -> usize {+ crate::heap_size::vec_bytes(&self.own)+ }++ /// The bytes of the elements the vector shares.+ pub(super) fn shared_heap_size(&self) -> usize {+ size_of_val::<[T]>(&self.shared)+ }+}++impl<T> Index<usize> for SharedPrefixVec<T> {+ type Output = T;++ fn index(&self, index: usize) -> &T {+ match index.checked_sub(self.shared.len()) {+ Some(own) => &self.own[own],+ None => &self.shared[index],+ }+ }+}++impl<T> IndexMut<usize> for SharedPrefixVec<T> {+ fn index_mut(&mut self, index: usize) -> &mut T {+ let own = index+ .checked_sub(self.shared.len())+ .expect("a shared element is never written");+ &mut self.own[own]+ }+}++/// A range of elements all shared or all the vector's own, as the elements one thing added are.+impl<T> Index<Range<usize>> for SharedPrefixVec<T> {+ type Output = [T];++ fn index(&self, range: Range<usize>) -> &[T] {+ let shared = self.shared.len();+ if range.end <= shared {+ return &self.shared[range];+ }+ assert!(range.start >= shared, "a range is all shared or all own");+ &self.own[range.start - shared..range.end - shared]+ }+}++#[cfg(test)]+mod tests {+ use super::*;++ #[test]+ fn a_clone_of_a_frozen_vector_shares_its_elements_and_adds_its_own() {+ let mut base = SharedPrefixVec::default();+ for value in [1, 2, 3] {+ base.push(value);+ }+ base.freeze();+ let mut document = base.clone();+ document.push(4);+ document.push(5);+ assert!(Arc::ptr_eq(&base.shared, &document.shared));+ assert_eq!(document.len(), 5);+ assert_eq!(document[1], 2);+ assert_eq!(document[4], 5);+ assert_eq!(&document[3..5], &[4, 5]);+ assert_eq!(&document[0..2], &[1, 2]);+ document[3] = 6;+ document[4] = 7;+ assert_eq!(document.iter().copied().collect::<Vec<_>>(), [1, 2, 3, 6, 7]);+ assert_eq!(base.len(), 3);+ }+}diff --git a/Libraries/LibWeb/Rust/src/css/style/prefix.rs b/Libraries/LibWeb/Rust/src/css/style/prefix.rsdeleted file mode 100644index 38d7016c1fa..00000000000--- a/Libraries/LibWeb/Rust/src/css/style/prefix.rs+++ /dev/null@@ -1,5420 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! Top-down state for ordinary selector chains over all four tree axes.-//!-//! A selector such as `.a > .b .c` is a small match automaton. Matching `.a` enables the `.b`-//! child step for one edge; matching `.b` enables the `.c` descendant step until that step matches.-//! A preorder traversal can propagate those enabled steps once instead of making every `.c`-//! candidate rediscover the same prefix by walking left through the tree.-//!-//! Sibling combinators are the same machine turned right. `.a + .b ~ .c` enables the `.b` step at-//! exactly the next sibling and the `.c` step at every later one, so a node's transition reads two-//! entering states - the parent's downward state and the previous sibling's rightward state - and-//! produces two output states in the same interned space. A following step persists along a child-//! sequence exactly as a descendant step persists down the tree, so the state representation, the-//! interner, and the retained form serve both axes unchanged.--use super::fast_hash::FastMap as HashMap;-use super::fast_hash::fast_hasher;-use super::selector::SelectorPrefixPredicate;-use super::shared_vector::{PagedSharedVector, SharedVectorPool};-use std::collections::hash_map::Entry;-use std::hash::Hash;-use std::hash::Hasher;-use std::mem::size_of;-use std::num::NonZeroU32;-use std::sync::Arc;--use super::ScopeProgramID;-use super::column::Column;-use super::column::EpochColumn;-use super::column::advance_epoch;-use super::fast_hash::FastSet as HashSet;-use super::index::AttributeFact;-use super::index::DispatchKey;-use super::index::StyleAtomID;-use super::index::StyleNodeFacts;-use super::instrumentation::Counter;-use super::instrumentation::Counters;-use super::partial_view::Lookup;-use super::program::EntryID;-use super::program::SelectorProgramID;-use super::selector::AttributeOperator;-use super::selector::Incomplete;-use super::selector::MatchEvaluator;-use super::selector::MatchFactRow;-use super::selector::NamespaceTest;-use super::selector::PrefixStructuralTest;-use super::selector::SelectorPrefixAxis;-use super::selector::SelectorPrefixLocal;-use super::selector::SelectorPrefixStep;-use super::selector::SelectorPrograms;-use super::selector::{AttributeTest, FeatureTest, TagTest};-use super::tree::StyleNodeID;-use super::tree::StyleNodeTree;--mod relation;-pub(super) use relation::PrefixRelation;--define_id! { struct PrefixCompoundID(); }--define_id! { pub(super) struct PrefixStepID(); }--#[derive(Clone, Copy)]-pub(super) struct PrefixProducer {- pub step: PrefixStepID,-}--impl PrefixProducer {- pub(super) fn index(self) -> usize {- self.step.0 as usize- }-}--define_id! { default pub(super) struct PrefixMatchSetID(); }--impl PrefixMatchSetID {- pub(super) fn index(self) -> usize {- self.0 as usize- }-}--impl super::intern_table::InternIdentity for PrefixMatchSetID {- fn index(self) -> usize {- self.0 as usize - 1- }-}--define_id! { default struct PrefixTruthSetID(); }--impl super::intern_table::InternIdentity for PrefixTruthSetID {- fn index(self) -> usize {- self.0 as usize - 1- }-}--define_id! { default struct PrefixResultID(); }--impl super::intern_table::InternIdentity for PrefixResultID {- fn index(self) -> usize {- self.0 as usize - 1- }-}--#[derive(Clone, Copy)]-struct PrefixResult {- matches: PrefixMatchSetID,- truth: PrefixTruthSetID,-}--#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]-struct PrefixStepKey {- compound: PrefixCompoundID,- predecessor: Option<PrefixStepID>,- axis: SelectorPrefixAxis,-}--#[derive(Clone, Debug, PartialEq, Eq, Hash)]-enum PrefixPredicateKey {- /// A canonical compound: interned feature tests answered from the fact row, plus the- /// structural tests it requires, answered from the node's precomputed truth bits. Keeping- /// the structural part as a bit mask rather than a program reference lets equal shapes- /// share one compound across programs and keeps the match evaluator out of transitions.- Features {- features: Box<[FeatureTest]>,- required_positional_bits: u32,- },- Program(Arc<SelectorPrefixPredicate>),-}--// Keep common class and ID tests in compact rows. Larger tag and attribute payloads-// live in separate flat arrays, with no per-test allocation.-#[derive(Clone, Copy, PartialEq, Eq, Hash)]-enum PrefixFeature {- AnyElement,- TagName(u32),- Id(StyleAtomID),- Class(StyleAtomID),- Attribute(u32),- NoNamespace,- Namespace(StyleAtomID),-}--impl PrefixFeature {- fn new(feature: FeatureTest, tags: &mut Vec<TagTest>, attributes: &mut Vec<AttributeTest>) -> Self {- match feature {- FeatureTest::AnyElement => Self::AnyElement,- FeatureTest::Id(id) => Self::Id(id),- FeatureTest::Class(class) => Self::Class(class),- FeatureTest::Namespace(NamespaceTest::None) => Self::NoNamespace,- FeatureTest::Namespace(NamespaceTest::Named(namespace)) => Self::Namespace(namespace),- FeatureTest::TagName(tag) => {- let index = u32::try_from(tags.len()).expect("prefix tag test space exhausted");- tags.push(tag);- Self::TagName(index)- }- FeatureTest::Attribute(attribute) => {- let index = u32::try_from(attributes.len()).expect("prefix attribute test space exhausted");- attributes.push(attribute);- Self::Attribute(index)- }- }- }-- fn feature(self, tags: &[TagTest], attributes: &[AttributeTest]) -> FeatureTest {- match self {- Self::AnyElement => FeatureTest::AnyElement,- Self::Id(id) => FeatureTest::Id(id),- Self::Class(class) => FeatureTest::Class(class),- Self::NoNamespace => FeatureTest::Namespace(NamespaceTest::None),- Self::Namespace(namespace) => FeatureTest::Namespace(NamespaceTest::Named(namespace)),- Self::TagName(index) => FeatureTest::TagName(tags[index as usize]),- Self::Attribute(index) => FeatureTest::Attribute(attributes[index as usize]),- }- }-}--#[derive(Clone, PartialEq, Eq, Hash)]-enum PrefixPredicate {- Features {- feature_start: u32,- feature_len: u32,- required_positional_bits: u32,- },- Program {- program: SelectorProgramID,- local: SelectorPrefixLocal,- identity: Arc<SelectorPrefixPredicate>,- },-}--#[derive(Clone, PartialEq, Eq, Hash)]-struct PrefixCompound {- predicate: PrefixPredicate,- dispatch_key: DispatchKey,-}--#[derive(Clone)]-struct PrefixStep {- compound: PrefixCompoundID,- /// The step's terminals and four successor kinds, compiled into one immutable action stream.- output_start: u32,- output_len: u32,-}--/// Mutable output storage used only while selector chains are registered. Keeping it separate-/// lets the finished automaton discard five vector headers per step.-#[derive(Clone, Default)]-struct PrefixStepOutputBuilder {- child_successors: Vec<PrefixStepID>,- descendant_successors: Vec<PrefixStepID>,- adjacent_successors: Vec<PrefixStepID>,- following_successors: Vec<PrefixStepID>,- terminals: Vec<EntryID>,-}--#[derive(Clone, Copy)]-#[repr(u8)]-enum PrefixOutputKind {- UniqueTerminal,- SharedTerminal,- Child,- Descendant,- NextSibling,- FollowingSibling,-}--#[derive(Clone, Copy)]-struct PrefixOutput {- target: u32,- kind: PrefixOutputKind,-}--#[derive(Clone)]-struct PrefixEntryPath {- terminal: EntryID,- steps: std::ops::Range<u32>,-}--// Keep the common empty and single-root buckets inline; the large variant stays thin.-#[allow(clippy::box_collection)]-#[derive(Clone, Default)]-enum PrefixRootSteps {- #[default]- Empty,- One(PrefixStepID),- Many(Box<Vec<PrefixStepID>>),-}--impl PrefixRootSteps {- fn push(&mut self, step: PrefixStepID) {- match self {- Self::Empty => *self = Self::One(step),- Self::One(first) => *self = Self::Many(Box::new(vec![*first, step])),- Self::Many(steps) => steps.push(step),- }- }-- fn as_slice(&self) -> &[PrefixStepID] {- match self {- Self::Empty => &[],- Self::One(step) => std::slice::from_ref(step),- Self::Many(steps) => steps.as_slice(),- }- }-- fn as_mut_slice(&mut self) -> &mut [PrefixStepID] {- match self {- Self::Empty => &mut [],- Self::One(step) => std::slice::from_mut(step),- Self::Many(steps) => steps.as_mut_slice(),- }- }-}--#[derive(Clone, Default)]-struct PrefixDispatchBucket {- root_steps: PrefixRootSteps,- first_step: u32,- end_step: u32,-}--/// The pools for finished prefix automata.-#[derive(Default)]-pub(super) struct PrefixPools {- compounds: SharedVectorPool<PrefixCompound>,- features: SharedVectorPool<PrefixFeature>,-}--/// Immutable prefix program attached to one selector dispatch.-#[derive(Clone, Default)]-pub(super) struct PrefixAutomaton {- relation_program: std::sync::OnceLock<std::sync::Arc<relation::PrefixRelationProgram>>,- compounds: PagedSharedVector<PrefixCompound>,- compound_ids: HashMap<PrefixPredicateKey, PrefixCompoundID>,- features: PagedSharedVector<PrefixFeature>,- tag_tests: Vec<TagTest>,- attribute_tests: Vec<AttributeTest>,- steps: Vec<PrefixStep>,- step_output_builders: Vec<PrefixStepOutputBuilder>,- outputs: Vec<PrefixOutput>,- step_ids: HashMap<PrefixStepKey, PrefixStepID>,- buckets: HashMap<DispatchKey, PrefixDispatchBucket>,- /// Runtime lookup is a packed immutable table sorted by selector entry.- entry_paths: Vec<PrefixEntryPath>,- entry_path_steps: Vec<PrefixStepID>,- /// Builder-only duplicate detection, discarded when the table is finished.- entry_path_keys: HashSet<EntryID>,- entry_paths_finished: bool,- /// The producer of each non-root step, retained in the storage formerly used by the finished- /// dispatch-order builder so warm removal edits can find shadowing local output in O(1).- step_predecessors: Vec<u32>,- /// Whether any registered chain uses a sibling combinator. Transitions of a sibling-free- /// automaton never read the previous sibling, so the down-only walk stays as cheap as it was.- has_sibling_steps: bool,- /// The deduplicated structural tests carried by registered chains, in registration order.- /// Their per-node answers form the positional bits of every transition and completion key.- positional_tests: Vec<(SelectorProgramID, PrefixStructuralTest)>,- local_fact_dependencies: PrefixFactDependencies,-}--/// The part of an immutable prefix automaton that one transaction can change.-pub(super) struct PrefixSelection {- steps: Box<[bool]>,- terminals: Box<[bool]>,-}--impl PrefixAutomaton {- /// Restore the builder indices and output lists discarded when this automaton was frozen.- /// The caller owns a deep clone, so extending it cannot mutate the retained template.- pub(super) fn prepare_to_extend(&mut self) {- self.relation_program.take();- assert!(- self.entry_paths_finished,- "only a finished prefix automaton can be extended"- );- self.compound_ids = self- .compounds- .iter()- .enumerate()- .map(|(index, compound)| {- let key = match &compound.predicate {- PrefixPredicate::Features {- feature_start,- feature_len,- required_positional_bits,- } => PrefixPredicateKey::Features {- features: self.features_for(*feature_start, *feature_len).collect(),- required_positional_bits: *required_positional_bits,- },- PrefixPredicate::Program { identity, .. } => PrefixPredicateKey::Program(Arc::clone(identity)),- };- (- key,- PrefixCompoundID(u32::try_from(index).expect("selector prefix compound space exhausted")),- )- })- .collect();- self.step_output_builders = self- .steps- .iter()- .map(|step| {- let mut builder = PrefixStepOutputBuilder::default();- for output in self.outputs_for(step) {- match output.kind {- PrefixOutputKind::UniqueTerminal | PrefixOutputKind::SharedTerminal => {- builder.terminals.push(EntryID(output.target));- }- PrefixOutputKind::Child => builder.child_successors.push(PrefixStepID(output.target)),- PrefixOutputKind::Descendant => builder.descendant_successors.push(PrefixStepID(output.target)),- PrefixOutputKind::NextSibling => builder.adjacent_successors.push(PrefixStepID(output.target)),- PrefixOutputKind::FollowingSibling => {- builder.following_successors.push(PrefixStepID(output.target));- }- }- }- builder- })- .collect();- self.step_ids.clear();- for (index, step) in self.steps.iter().enumerate() {- let predecessor = self.step_predecessors[index];- let predecessor = (predecessor != u32::MAX).then_some(PrefixStepID(predecessor));- let id = PrefixStepID(u32::try_from(index).expect("selector prefix step space exhausted"));- let axis = predecessor.map_or(SelectorPrefixAxis::Root, |predecessor| {- let outputs = &self.step_output_builders[predecessor.0 as usize];- if outputs.child_successors.contains(&id) {- SelectorPrefixAxis::Child- } else if outputs.descendant_successors.contains(&id) {- SelectorPrefixAxis::Descendant- } else if outputs.adjacent_successors.contains(&id) {- SelectorPrefixAxis::NextSibling- } else if outputs.following_successors.contains(&id) {- SelectorPrefixAxis::FollowingSibling- } else {- unreachable!("a non-root prefix step must be an output of its predecessor")- }- });- self.step_ids.insert(- PrefixStepKey {- compound: step.compound,- predecessor,- axis,- },- id,- );- }- self.entry_path_keys = self.entry_paths.iter().map(|path| path.terminal).collect();- for bucket in self.buckets.values_mut() {- bucket.first_step = 0;- bucket.end_step = 0;- }- self.outputs.clear();- self.entry_paths_finished = false;- }-- pub(super) fn add_entry(- &mut self,- programs: &SelectorPrograms,- program_id: SelectorProgramID,- chain: &[SelectorPrefixStep],- entry: EntryID,- structural_tests_admissible: bool,- ) -> bool {- assert!(!self.entry_paths_finished, "cannot add to a finished prefix automaton");- let program = programs.get(program_id);- // Every transition and completion key carries one truth bit per registered structural- // test, so an automaton holds at most 32 of them. Pre-scan the chain's tests before- // mutating anything: a chain that would overflow the bit space is refused whole and- // stays with its routes, and a chain whose caller does not admit structural tests at- // all is refused the same way. Canonical structural tests never reference their- // registering program, so deduplication is by test value across programs.- let mut needs_structural_tests = false;- let mut new_positional_tests: Vec<PrefixStructuralTest> = Vec::new();- let canonical_steps: Vec<_> = chain- .iter()- .map(|step| program.canonical_prefix_features_and_position(step.local))- .collect();- for (_, tests) in canonical_steps.iter().flatten() {- for &test in tests {- needs_structural_tests = true;- if !self.positional_tests.iter().any(|&(_, existing)| existing == test)- && !new_positional_tests.contains(&test)- {- new_positional_tests.push(test);- }- }- }- if needs_structural_tests && !structural_tests_admissible {- return false;- }- if self.positional_tests.len() + new_positional_tests.len() > 32 {- return false;- }- if !self.entry_path_keys.insert(entry) {- return true;- }- if chain.iter().any(|step| {- matches!(- step.axis,- SelectorPrefixAxis::NextSibling | SelectorPrefixAxis::FollowingSibling- )- }) {- self.has_sibling_steps = true;- }- let mut predecessor = None;- let path_start = u32::try_from(self.entry_path_steps.len()).expect("selector prefix path space exhausted");- let path_end = path_start- .checked_add(u32::try_from(chain.len()).expect("selector prefix path space exhausted"))- .expect("selector prefix path space exhausted");- self.entry_path_steps.reserve(chain.len());- for (&chain_step, canonical) in chain.iter().zip(canonical_steps) {- program.visit_prefix_local_features(chain_step.local, &mut |feature| {- self.local_fact_dependencies.add(feature);- });- let predicate = match canonical {- Some((features, tests)) => {- let mut required_positional_bits = 0_u32;- for test in tests {- let index = match self.positional_tests.iter().position(|&(_, existing)| existing == test) {- Some(index) => index,- None => {- self.positional_tests.push((program_id, test));- self.positional_tests.len() - 1- }- };- required_positional_bits |= 1_u32 << index;- }- PrefixPredicateKey::Features {- features: features.into_boxed_slice(),- required_positional_bits,- }- }- None => PrefixPredicateKey::Program(Arc::new(program.prefix_local_predicate(chain_step.local))),- };- let compound = match self.compound_ids.entry(predicate) {- Entry::Occupied(entry) => *entry.get(),- Entry::Vacant(entry) => {- let compound = PrefixCompoundID(- u32::try_from(self.compounds.len()).expect("selector prefix compound space exhausted"),- );- let dispatch_key = program.prefix_dispatch_key(chain_step.local);- let runtime_predicate = match entry.key() {- PrefixPredicateKey::Features {- features,- required_positional_bits,- } => {- let feature_start =- u32::try_from(self.features.len()).expect("selector prefix feature space exhausted");- self.features.extend(features.iter().map(|&feature| {- PrefixFeature::new(feature, &mut self.tag_tests, &mut self.attribute_tests)- }));- PrefixPredicate::Features {- feature_start,- feature_len: u32::try_from(features.len())- .expect("selector prefix feature space exhausted"),- required_positional_bits: *required_positional_bits,- }- }- PrefixPredicateKey::Program(identity) => PrefixPredicate::Program {- program: program_id,- local: chain_step.local,- identity: Arc::clone(identity),- },- };- self.compounds.push(PrefixCompound {- predicate: runtime_predicate,- dispatch_key,- });- self.buckets.entry(dispatch_key).or_default();- entry.insert(compound);- compound- }- };- let key = PrefixStepKey {- compound,- predecessor,- axis: chain_step.axis,- };- let step = match self.step_ids.entry(key) {- Entry::Occupied(entry) => *entry.get(),- Entry::Vacant(entry) => {- let step =- PrefixStepID(u32::try_from(self.steps.len()).expect("selector prefix step space exhausted"));- self.steps.push(PrefixStep {- compound,- output_start: 0,- output_len: 0,- });- self.step_predecessors.push(predecessor.map_or(u32::MAX, |step| step.0));- self.step_output_builders.push(PrefixStepOutputBuilder::default());- entry.insert(step);- // Only root steps dispatch through buckets: a continuation step is reachable- // exactly when its predecessor put it in the parent state, so transitions find- // it by walking the (small) active set and asking whether the row carries its- // key, instead of scanning every bucket member for the few enabled ones.- if chain_step.axis == SelectorPrefixAxis::Root {- self.buckets- .entry(self.compounds[compound.0 as usize].dispatch_key)- .or_default()- .root_steps- .push(step);- }- if let Some(predecessor) = predecessor {- let predecessor = &mut self.step_output_builders[predecessor.0 as usize];- match chain_step.axis {- SelectorPrefixAxis::Child => predecessor.child_successors.push(step),- SelectorPrefixAxis::Descendant => predecessor.descendant_successors.push(step),- SelectorPrefixAxis::NextSibling => predecessor.adjacent_successors.push(step),- SelectorPrefixAxis::FollowingSibling => predecessor.following_successors.push(step),- SelectorPrefixAxis::Root => {- unreachable!("only the first selector prefix is a root")- }- }- }- step- }- };- predecessor = Some(step);- self.entry_path_steps.push(step);- }- let terminal_step = predecessor.expect("a selector chain is not empty");- self.step_output_builders[terminal_step.0 as usize]- .terminals- .push(entry);- self.entry_paths.push(PrefixEntryPath {- terminal: entry,- steps: path_start..path_end,- });- true- }-- pub(super) fn finish(&mut self, pools: &mut PrefixPools) {- assert!(!self.entry_paths_finished, "cannot finish a prefix automaton twice");- if !self.entry_paths.is_sorted_by_key(|path| path.terminal) {- self.entry_paths.sort_unstable_by_key(|path| path.terminal);- }- // The terminal set answers membership questions the packed table would need a binary- // search for, so keep it instead of rebuilding it when the automaton is extended.- self.entry_path_keys.shrink_to_fit();- self.compound_ids = HashMap::default();- self.step_ids = HashMap::default();- let mut step_by_dispatch_order: Vec<_> = (0..self.steps.len())- .map(|step| PrefixStepID(u32::try_from(step).expect("selector prefix step space exhausted")))- .collect();- step_by_dispatch_order.sort_unstable_by_key(|step| {- let compound = self.steps[step.0 as usize].compound;- (self.compounds[compound.0 as usize].dispatch_key, *step)- });- // Number immutable steps in dispatch order so every retained state payload is directly- // searchable by bucket range. Remap all builder references once here instead of loading a- // separate rank through the step table for every runtime state search and sort.- let mut remap = vec![0_u32; self.steps.len()];- for (order, &step) in step_by_dispatch_order.iter().enumerate() {- remap[step.0 as usize] = u32::try_from(order).expect("selector prefix step space exhausted");- }- // Apply each permutation cycle to the parallel arrays in place. Replacing a visited- // source with its own index makes the cycle a no-op when reached again.- for start in 0..step_by_dispatch_order.len() {- let mut current = start;- loop {- let next = step_by_dispatch_order[current].0 as usize;- step_by_dispatch_order[current] =- PrefixStepID(u32::try_from(current).expect("selector prefix step space exhausted"));- if next == start {- break;- }- self.steps.swap(current, next);- self.step_output_builders.swap(current, next);- self.step_predecessors.swap(current, next);- current = next;- }- }- for predecessor in &mut self.step_predecessors {- if *predecessor != u32::MAX {- *predecessor = remap[*predecessor as usize];- }- }- self.steps.shrink_to_fit();- self.step_predecessors.shrink_to_fit();- let remap_steps = |steps: &mut [PrefixStepID]| {- for step in steps {- step.0 = remap[step.0 as usize];- }- };- for builder in &mut self.step_output_builders {- remap_steps(&mut builder.child_successors);- remap_steps(&mut builder.descendant_successors);- remap_steps(&mut builder.adjacent_successors);- remap_steps(&mut builder.following_successors);- }- for bucket in self.buckets.values_mut() {- remap_steps(bucket.root_steps.as_mut_slice());- }- for step in &mut self.entry_path_steps {- step.0 = remap[step.0 as usize];- }- for (order, step) in self.steps.iter_mut().enumerate() {- let order = u32::try_from(order).expect("selector prefix step space exhausted");- let compound = step.compound;- let bucket = self- .buckets- .get_mut(&self.compounds[compound.0 as usize].dispatch_key)- .expect("every prefix compound has a dispatch bucket");- if bucket.end_step == 0 {- bucket.first_step = order;- }- bucket.end_step = order + 1;- }- assert_eq!(self.steps.len(), self.step_output_builders.len());- let mut terminal_producers = HashMap::<EntryID, u32>::default();- for (step_index, builder) in self.step_output_builders.iter().enumerate() {- let step_index = u32::try_from(step_index).expect("selector prefix step space exhausted");- for &terminal in &builder.terminals {- match terminal_producers.get_mut(&terminal) {- Some(producer) if *producer != step_index => *producer = u32::MAX,- Some(_) => {}- None => {- terminal_producers.insert(terminal, step_index);- }- }- }- }- for (step_index, (step, builder)) in self- .steps- .iter_mut()- .zip(std::mem::take(&mut self.step_output_builders))- .enumerate()- {- let step_index = u32::try_from(step_index).expect("selector prefix step space exhausted");- step.output_start = u32::try_from(self.outputs.len()).expect("selector prefix output space exhausted");- self.outputs- .extend(builder.terminals.into_iter().map(|terminal| PrefixOutput {- target: terminal.0,- kind: match terminal_producers[&terminal] == step_index {- true => PrefixOutputKind::UniqueTerminal,- false => PrefixOutputKind::SharedTerminal,- },- }));- self.outputs- .extend(builder.child_successors.into_iter().map(|step| PrefixOutput {- target: step.0,- kind: PrefixOutputKind::Child,- }));- self.outputs- .extend(builder.descendant_successors.into_iter().map(|step| PrefixOutput {- target: step.0,- kind: PrefixOutputKind::Descendant,- }));- self.outputs- .extend(builder.adjacent_successors.into_iter().map(|step| PrefixOutput {- target: step.0,- kind: PrefixOutputKind::NextSibling,- }));- self.outputs- .extend(builder.following_successors.into_iter().map(|step| PrefixOutput {- target: step.0,- kind: PrefixOutputKind::FollowingSibling,- }));- step.output_len =- u32::try_from(self.outputs.len()).expect("selector prefix output space exhausted") - step.output_start;- }- // Extending a finished automaton starts from a deep clone, whose vectors already- // have exact capacity. Spare builder capacity in the retained template is unused.- self.compounds.shrink_to_fit();- self.features.shrink_to_fit();- self.compounds.share(&mut pools.compounds);- self.features.share(&mut pools.features);- self.tag_tests.shrink_to_fit();- self.attribute_tests.shrink_to_fit();- self.outputs.shrink_to_fit();- self.entry_paths.shrink_to_fit();- self.entry_path_steps.shrink_to_fit();- self.entry_paths_finished = true;- }-- fn sort_steps_by_dispatch_order(&self, steps: &mut [PrefixStepID]) {- if !steps.is_sorted() {- steps.sort_unstable();- }- }-- #[must_use]- pub(super) fn is_empty(&self) -> bool {- self.steps.is_empty()- }-- #[must_use]- pub(super) fn has_sibling_steps(&self) -> bool {- self.has_sibling_steps- }-- #[must_use]- pub(super) fn positional_tests(&self) -> &[(SelectorProgramID, PrefixStructuralTest)] {- &self.positional_tests- }-- fn bucket(&self, key: DispatchKey) -> Option<&PrefixDispatchBucket> {- self.buckets.get(&key)- }-- fn outputs_for(&self, step: &PrefixStep) -> &[PrefixOutput] {- let start = step.output_start as usize;- &self.outputs[start..start + step.output_len as usize]- }-- fn predecessor_of(&self, step: PrefixStepID) -> Option<PrefixStepID> {- let predecessor = self.step_predecessors[step.0 as usize];- (predecessor != u32::MAX).then_some(PrefixStepID(predecessor))- }-- fn features_for(&self, start: u32, len: u32) -> impl Iterator<Item = FeatureTest> + '_ {- let start = start as usize;- self.features- .range(start..start + len as usize)- .map(|feature| feature.feature(&self.tag_tests, &self.attribute_tests))- }-- fn path_for(&self, key: EntryID) -> Option<&[PrefixStepID]> {- assert!(self.entry_paths_finished, "cannot query an unfinished prefix automaton");- let index = self.entry_paths.binary_search_by_key(&key, |path| path.terminal).ok()?;- let path = &self.entry_paths[index];- Some(&self.entry_path_steps[path.steps.start as usize..path.steps.end as usize])- }-- pub(super) fn contains_entry(&self, entry: EntryID) -> bool {- debug_assert!(self.entry_paths_finished, "cannot query an unfinished prefix automaton");- debug_assert_eq!(self.entry_path_keys.contains(&entry), self.path_for(entry).is_some());- self.entry_path_keys.contains(&entry)- }-- pub(super) fn select_entries(- &self,- entries: impl IntoIterator<Item = EntryID>,- terminal_count: usize,- ) -> PrefixSelection {- let mut selection = PrefixSelection {- steps: vec![false; self.steps.len()].into_boxed_slice(),- terminals: vec![false; terminal_count].into_boxed_slice(),- };- for entry in entries {- let Some(path) = self.path_for(entry) else {- continue;- };- selection.terminals[entry.0 as usize] = true;- for step in path {- if !selection.steps[step.0 as usize] {- selection.steps[step.0 as usize] = true;- }- }- }- selection- }-- /// The producer step a route reaches at `inverse_path_length` steps from the entry's end.- /// Each entry stores exactly one prefix path, so this is a read of finished program data:- /// routing borrows it and no per-transaction producer cache exists.- pub(super) fn route_producer(&self, entry: EntryID, inverse_path_length: usize) -> Option<PrefixProducer> {- let path = self.path_for(entry)?;- let index = path.len().checked_sub(inverse_path_length.saturating_add(1))?;- Some(PrefixProducer {- step: *path.get(index)?,- })- }-}--impl PrefixSelection {- fn contains_step(&self, step: PrefixStepID) -> bool {- self.steps[step.0 as usize]- }-- fn contains_terminal(&self, terminal: EntryID) -> bool {- self.terminals[terminal.0 as usize]- }-}--/// One interned set of active continuation steps, partitioned into a persisting part and an-/// expiring part, stored as a delta over the state it extends.-///-/// A transition constructs every output state as its entering state plus a handful of new-/// admissions, and rightward states are position-unique unions that defeat content-/// deduplication, so the representation IS the construction: the persisting set is the base's-/// persisting set plus this state's sorted additions, and only the additions and the (one-edge)-/// expiring steps are stored. Enumerating a state walks its base chain; each level's additions-/// are disjoint from every deeper level's by construction, so the chain is at most one level-/// per persisting step.-///-/// A downward state's persisting part holds descendant steps and its expiring part holds child-/// steps; a rightward state holds following-sibling and adjacent steps. Both share this-/// representation because their algebra is identical, so the field names read "descendant" for-/// the persisting partition even when a state travels right.-#[derive(Default)]-struct PrefixState {- /// The state whose persisting set this one extends; the empty state extends itself.- base: u32,- /// The delta payload in `delta_steps`: the dispatch-ordered persisting additions, all- /// genuinely new relative to the base's persisting set, followed by the dispatch-ordered- /// expiring steps.- payload_start: u32,- additions_len: u32,- expiring_len: u32,- /// The total persisting step count: the base's plus this state's additions.- descendant_len: u32,- /// Order-independent sum of the persisting steps' mixed hashes over the whole chain. A- /// transition that adds no persisting step inherits it; one that does extends it in- /// O(additions).- descendant_hash: u64,- /// Order-independent digest of the one-edge expiring steps.- expiring_hash: u32,-}--fn step_hash(step: PrefixStepID) -> u64 {- (u64::from(step.0) ^ 0x9E37_79B9_7F4A_7C15).wrapping_mul(0x2545_F491_4F6C_DD1D)-}--/// Content identity of a prefix state. The two digests are fast lookup keys only; interning still-/// compares the complete persisting and expiring sets on a hit.-fn state_content_key(- descendant_len: u32,- descendant_hash: u64,- expiring_len: u32,- expiring_hash: u32,-) -> (u32, u64, u32, u32) {- (descendant_len, descendant_hash, expiring_len, expiring_hash)-}--#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]-pub(super) struct PrefixTransitionKey {- pub parent: u32,- /// The previous sibling's rightward output state; always zero in a sibling-free automaton.- pub previous: u32,- pub local_facts: u32,- pub is_document_root: bool,- /// One answer bit per automaton positional test; always zero when the automaton has none.- /// Positional truth is per index, not per fact cohort, so it must split the memo identity.- pub positional_bits: u32,-}--/// The two interned states a transition starts from.-#[derive(Clone, Copy)]-struct EnteringStates {- /// The parent's downward output state.- parent: u32,- /// The previous sibling's rightward output state; zero in a sibling-free automaton.- previous: u32,-}--const UNKNOWN_ENTERING_STATES: EnteringStates = EnteringStates {- parent: UNKNOWN_STATE,- previous: 0,-};--impl Default for EnteringStates {- fn default() -> Self {- UNKNOWN_ENTERING_STATES- }-}--#[derive(Clone, Copy)]-struct TransitionInputs {- entering: EnteringStates,- local_facts: u32,- positional_bits: u32,-}--#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]-struct PrefixTransition {- /// The downward output state, entering the node's children.- state: u32,- /// The rightward output state, entering the node's next sibling.- right: u32,- result: PrefixResultID,-}--const UNKNOWN_STATE: u32 = u32::MAX;--/// Hand out one identity per arena of interned prefix states.-fn next_prefix_states_identity() -> u64 {- use std::sync::atomic::{AtomicU64, Ordering};-- static NEXT: AtomicU64 = AtomicU64::new(1);- NEXT.fetch_add(1, Ordering::Relaxed)-}--const UNKNOWN_TRANSITION: PrefixTransition = PrefixTransition {- state: UNKNOWN_STATE,- right: 0,- result: PrefixResultID(0),-};--define_id! { struct PrefixStateID(); }--struct PrefixStateCandidates {- first: PrefixStateID,- collisions: Vec<PrefixStateID>,-}--impl super::intern_table::InternIdentity for PrefixStateID {- fn index(self) -> usize {- self.0 as usize - 1- }-}--define_id! { struct LocalFactSlot(); }--impl super::intern_table::InternIdentity for LocalFactSlot {- fn index(self) -> usize {- self.0 as usize- }-}--// Prefix answers depend on the selector's observations, not every fact stored on a node.-// Keep names read by any local predicate, and collapse values no exact test distinguishes.-// Text comparisons retain their complete inputs, including namespace and case-folded names.-#[derive(Clone, Default)]-struct PrefixFactDependencies {- ids: HashSet<StyleAtomID>,- classes: HashSet<StyleAtomID>,- attribute_names: HashSet<StyleAtomID>,- attribute_values: HashSet<StyleAtomID>,- attribute_text_names: HashSet<StyleAtomID>,-}--impl PrefixFactDependencies {- fn add(&mut self, feature: FeatureTest) {- match feature {- FeatureTest::Id(id) => {- self.ids.insert(id);- }- FeatureTest::Class(class) => {- self.classes.insert(class);- }- FeatureTest::Attribute(test) => {- self.attribute_names.insert(test.name);- self.attribute_names.insert(test.folded);- match test.operator {- AttributeOperator::Presence => {}- AttributeOperator::Exact- if test.case == super::selector::AttributeCase::Sensitive && !test.value_atom.is_none() =>- {- self.attribute_values.insert(test.value_atom);- }- _ => {- self.attribute_text_names.insert(test.name);- self.attribute_text_names.insert(test.folded);- }- }- }- _ => {}- }- }-- fn id_of(&self, facts: &StyleNodeFacts, row: u32) -> StyleAtomID {- let id = facts.id_of(row);- if self.ids.contains(&id) { id } else { StyleAtomID::NONE }- }-- fn reads_attribute(&self, facts: &StyleNodeFacts, attribute: &AttributeFact) -> bool {- Self::name_is_read(&self.attribute_names, facts, attribute)- }-- fn name_is_read(names: &HashSet<StyleAtomID>, facts: &StyleNodeFacts, attribute: &AttributeFact) -> bool {- if names.is_empty() {- return false;- }- if names.contains(&attribute.name) {- return true;- }- let forms = facts.attribute_name_forms(attribute.name);- [forms.local, forms.folded_name, forms.folded_local]- .iter()- .any(|name| names.contains(name))- }-- fn attribute_value<'a>(- &self,- facts: &'a StyleNodeFacts,- attribute: AttributeFact,- ) -> (StyleAtomID, Option<&'a [u16]>) {- if Self::name_is_read(&self.attribute_text_names, facts, &attribute) {- return (attribute.value, facts.text_of(attribute));- }- let value = if self.attribute_values.contains(&attribute.value) {- attribute.value- } else {- StyleAtomID::NONE- };- (value, None)- }-}--struct LocalFactInterner {- next_identity: u32,-}--impl LocalFactInterner {- fn new() -> Self {- Self { next_identity: 1 }- }-- fn intern(- &mut self,- identities: &mut super::intern_table::InternTable<LocalFactSlot, (u32, u32)>,- facts: &StyleNodeFacts,- row: u32,- dependencies: &PrefixFactDependencies,- counters: &Counters,- ) -> u32 {- let hash = hash_local_facts(facts, row, dependencies);- if let Some(slot) = identities.find(hash, |_slot, &(_identity, representative)| {- rows_have_equal_local_facts_between(facts, row, facts, representative, dependencies)- }) {- counters.bump(Counter::PrefixLocalFactIdentityHits);- return identities[slot].0;- }- counters.bump(Counter::PrefixLocalFactIdentityMisses);- let identity = self.mint_identity();- let slot = LocalFactSlot(u32::try_from(identities.len()).expect("local fact table exceeds u32 indexing"));- identities.insert(hash, slot, (identity, row));- identity- }-- fn mint_identity(&mut self) -> u32 {- let identity = self.next_identity;- self.next_identity = self- .next_identity- .checked_add(1)- .expect("local fact identity space exhausted");- identity- }-}--/// Retained prefix states for one immutable selector dispatch.-pub(super) struct PrefixStates {- /// Which arena this is. Transitions name states and results by index, so answers memoized- /// outside the arena mean nothing once a released cache has rebuilt it.- identity: u64,- pub(super) relation: Option<Box<PrefixRelation>>,- relation_answers: Column<Option<PrefixMatchSetID>>,- states: Vec<PrefixState>,- /// Every state's delta payload: its persisting additions followed by its expiring steps.- delta_steps: Vec<std::mem::MaybeUninit<PrefixStepID>>,- states_by_hash: HashMap<(u32, u64, u32, u32), PrefixStateCandidates>,- states_by_hash_collision_bytes: u64,- match_offsets: Vec<u32>,- match_entries: Vec<EntryID>,- truth_offsets: Vec<u32>,- truth_steps: Vec<PrefixStepID>,- truth_sets_by_hash: super::intern_table::InternTable<PrefixTruthSetID, ()>,- results: Vec<PrefixResult>,- result_ids: super::intern_table::InternTable<PrefixResultID, PrefixResult>,- match_sets_by_hash: super::intern_table::InternTable<PrefixMatchSetID, ()>,- local_fact_interner: LocalFactInterner,- transition_by_element: Column<PrefixTransition>,- entering_by_element: Column<EnteringStates>,- local_facts_by_element: Column<u32>,- /// Per-element positional truth retained only for automata that test it.- positional_bits_by_element: Column<u32>,- candidate_epoch: EpochColumn,- comparison_epoch: u32,- comparison_marks: EpochColumn,- compound_epoch: EpochColumn,- compound_answer: Vec<bool>,- output_epoch: EpochColumn,- match_epoch: EpochColumn,- /// Per step, the epoch in which the current transition's entering parent state held it as- /// persisting; admissions already persisting there are dropped instead of stored again.- parent_persisting_epoch: EpochColumn,- /// The same membership marks for the entering previous-sibling state's persisting part.- previous_persisting_epoch: EpochColumn,- candidates: Vec<PrefixStepID>,- compare_left: Vec<PrefixStepID>,- compare_right: Vec<PrefixStepID>,- output_matches: Vec<EntryID>,- output_matched_steps: Vec<PrefixStepID>,- new_descendant: Vec<PrefixStepID>,- new_child: Vec<PrefixStepID>,- new_following: Vec<PrefixStepID>,- new_adjacent: Vec<PrefixStepID>,- new_descendant_hash: u64,- new_child_hash: u32,- new_following_hash: u64,- new_adjacent_hash: u32,- /// Per state, the interned state holding exactly its persisting part; the state itself when- /// it has no expiring steps, lazily interned otherwise. This is the no-admission fast path,- /// shared by downward and rightward states.- descendant_only: Vec<u32>,- epoch: u32,- complete: bool,- automaton_step_count: usize,- automaton_statistics_recorded: bool,- last_compacted_working_bytes: u64,-}--/// Private memo and row domain for one prefix evaluation context.-#[derive(Clone, Default)]-pub(super) struct PrefixTransitionScratch {- facts_generation: u64,- /// The `PrefixStates` every answer below names by index; see `PrefixStates::identity`.- states_identity: u64,- memo: HashMap<PrefixTransitionKey, PrefixTransition>,- by_node: HashMap<StyleNodeID, PrefixTransition>,- local_facts_by_row: HashMap<u32, u32>,- // Composite views cannot intern their base rows as if they were the overlaid facts.- composite_local_fact_changes: Option<Vec<StyleNodeID>>,- // Representatives name rows in this context's facts domain. Nested evaluations own- // separate tables, while identities are allocated by the shared prefix-state arena.- local_fact_representatives: super::intern_table::InternTable<LocalFactSlot, (u32, u32)>,- ancestor_chain: Vec<StyleNodeID>,-}--#[derive(Clone, Default)]-pub(super) struct PrefixEffects {- writes: Vec<PrefixNodeWrite>,-}--#[derive(Clone)]--struct PrefixNodeWrite {- node: StyleNodeID,- transition: PrefixTransition,- entering: EnteringStates,- positional_bits: Option<u32>,- local_facts: Option<u32>,-}--#[derive(Clone, Default)]-pub(super) struct PrefixTransitionContext {- pub(super) scratch: PrefixTransitionScratch,- pub(super) effects: PrefixEffects,-}--impl PrefixTransitionContext {- pub(super) fn new(states: &mut PrefixStates, facts: &StyleNodeFacts) -> Self {- let mut context = Self::default();- context.prepare(states, facts);- context- }-- pub(super) fn prepare(&mut self, states: &mut PrefixStates, facts: &StyleNodeFacts) {- // Memoized transitions, per-row answers and local-fact representatives all name one- // arena. A cache release rebuilds those arenas under whoever still owns a context, so- // nothing prepared against the previous one survives into this preparation.- if self.scratch.states_identity != states.identity {- *self = Self::default();- self.scratch.states_identity = states.identity;- }- self.scratch.prepare_rows(facts.generation());- self.scratch.composite_local_fact_changes = None;- }-- pub(super) fn new_composite(states: &mut PrefixStates, facts: &StyleNodeFacts, changed: &[StyleNodeID]) -> Self {- let mut context = Self::default();- context.scratch.states_identity = states.identity;- context.scratch.prepare_rows(facts.generation());- context.scratch.composite_local_fact_changes = Some(changed.to_vec());- context- }-}--#[derive(Clone, Default)]-pub(super) struct PrefixTransitionContexts {- by_program: Column<Option<PrefixTransitionContext>>,-}--impl PrefixTransitionContexts {- pub(super) fn prepare(&mut self, program: ScopeProgramID, states: &mut PrefixStates, facts: &StyleNodeFacts) {- self.by_program- .entry(program.0 as usize)- .get_or_insert_with(PrefixTransitionContext::default)- .prepare(states, facts);- }-- /// Prepare one program's context again when the arena it was prepared against was replaced.- ///- /// A traversal owns its contexts for as long as it runs, while the states they name can be- /// released and rebuilt under it whenever the cache is released. Every pairing of a- /// context with an arena therefore revalidates before reading memoized answers.- pub(super) fn rebind(&mut self, program: ScopeProgramID, states: &mut PrefixStates, facts: &StyleNodeFacts) {- let context = self- .by_program- .entry(program.0 as usize)- .get_or_insert_with(PrefixTransitionContext::default);- if context.scratch.states_identity == states.identity {- return;- }- context.prepare(states, facts);- }-- pub(super) fn get_mut(&mut self, program: ScopeProgramID) -> &mut PrefixTransitionContext {- self.by_program- .get_mut(program.0 as usize)- .and_then(Option::as_mut)- .expect("prefix context prepared")- }-- pub(super) fn install(&mut self, states: &mut PrefixStateCache) {- for (program, context) in self.by_program.iter_mut().enumerate() {- if let Some(context) = context- && !context.effects.writes.is_empty()- && let Lookup::Known(states) = states.lookup_mut(ScopeProgramID(- u32::try_from(program).expect("scope program space exhausted"),- ))- {- states.install_prefix_effects(&mut context.effects);- }- }- }-}--struct PrefixTransitionSurface<'a> {- states: &'a mut PrefixStates,- scratch: &'a mut PrefixTransitionScratch,- effects: &'a mut PrefixEffects,-}--#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub(super) struct PrefixDifference {- pub continuation_changed: bool,- /// Whether the rightward output entering the next sibling differs; always false in a- /// sibling-free automaton.- pub right_changed: bool,- pub matches_changed: bool,- pub arrived: bool,- /// The interned match sets on either side, so a consumer can name exactly which entries- /// moved instead of treating the node as opaquely changed.- pub old_matches: PrefixMatchSetID,- pub new_matches: PrefixMatchSetID,- pub continuation_delta: Option<PrefixStateDeltaID>,- /// The old and new downward output states, for a consumer rebasing across the delta.- pub continuation_endpoints: (u32, u32),- pub right_delta: Option<PrefixStateDeltaID>,-}--#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub(super) enum PrefixTransitionGap {- MissingTransition(StyleNodeID),- Incomplete(Incomplete),-}--pub(super) enum PrefixTransitionLookup<T> {- Known(T),- Missing(PrefixTransitionGap),-}--#[derive(Clone, Copy, Debug, PartialEq, Eq)]-enum PrefixTransitionOrigin {- Computed,- Memoized,-}--pub(super) struct PrefixEvaluation<'a, 'b> {- automaton: &'a PrefixAutomaton,- tree: &'a StyleNodeTree,- facts: &'a StyleNodeFacts,- programs: &'a SelectorPrograms,- evaluator: &'a mut MatchEvaluator<'b>,- shadow_root: Option<StyleNodeID>,- selection: Option<&'a PrefixSelection>,-}--#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]-struct PrefixStepSpan {- start: u32,- len: u32,-}--#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]-struct PrefixMatchSpan {- start: u32,- len: u32,-}--#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]-struct PrefixMatchDelta {- additions: PrefixMatchSpan,- removals: PrefixMatchSpan,-}--#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]-pub(super) struct PrefixStateDelta {- persisting_additions: PrefixStepSpan,- persisting_removals: PrefixStepSpan,- expiring_additions: PrefixStepSpan,- expiring_removals: PrefixStepSpan,-}--#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub(super) struct PrefixStateDeltaID(NonZeroU32);--#[derive(Clone, Copy)]-pub(super) struct PrefixEnteringDeltas {- pub parent: Option<PrefixStateDeltaID>,- pub previous: Option<PrefixStateDeltaID>,- /// The parent's old and new downward output states when `parent` is their exact signed- /// difference; `UNKNOWN_STATE` on both sides otherwise.- pub parent_endpoints: (u32, u32),-}--impl Default for PrefixEnteringDeltas {- fn default() -> Self {- Self {- parent: None,- previous: None,- parent_endpoints: (UNKNOWN_STATE, UNKNOWN_STATE),- }- }-}--#[derive(Clone, Copy)]-struct PrefixLocalOutputDeltas {- continuation: PrefixStateDeltaID,- right: PrefixStateDeltaID,- matches: PrefixMatchDelta,- outputs_changed: bool,- result_changed: bool,- result_delta_complete: bool,-}--/// The dispatch key of every step one delta carries, sorted by key.-type DeltaKeyTable = Box<[(DispatchKey, PrefixStepID)]>;--#[derive(Default)]-pub(super) struct PrefixDeltaArena {- steps: Vec<PrefixStepID>,- deltas: Vec<PrefixStateDelta>,- /// Per delta, on demand: the dispatch key of every step it carries - and of every removed- /// step's predecessor - sorted by key, so a node's own few keys find the steps that could- /// match it without touching the rest.- key_tables: Vec<Option<DeltaKeyTable>>,- /// The bytes of every materialized key table, kept current because the walk reconciles the- /// arena's capacity after each node it visits.- key_table_bytes: usize,- matches: Vec<EntryID>,- scratch: [Vec<PrefixStepID>; 8],- match_scratch: [Vec<EntryID>; 2],- signed_scratch: Vec<(PrefixStepID, i8)>,-}--impl PrefixDeltaArena {- fn append(&mut self, steps: &[PrefixStepID]) -> PrefixStepSpan {- let start = u32::try_from(self.steps.len()).expect("selector prefix delta arena overflow");- self.steps.extend_from_slice(steps);- PrefixStepSpan {- start,- len: u32::try_from(steps.len()).expect("selector prefix delta arena overflow"),- }- }-- fn get(&self, span: PrefixStepSpan) -> &[PrefixStepID] {- let start = span.start as usize;- &self.steps[start..start + span.len as usize]- }-- fn append_matches(&mut self, matches: &[EntryID]) -> PrefixMatchSpan {- let start = u32::try_from(self.matches.len()).expect("selector prefix match delta arena overflow");- self.matches.extend_from_slice(matches);- PrefixMatchSpan {- start,- len: u32::try_from(matches.len()).expect("selector prefix match delta arena overflow"),- }- }-- fn get_matches(&self, span: PrefixMatchSpan) -> &[EntryID] {- let start = span.start as usize;- &self.matches[start..start + span.len as usize]- }-- fn append_match_delta(&mut self) -> PrefixMatchDelta {- let additions = std::mem::take(&mut self.match_scratch[0]);- let removals = std::mem::take(&mut self.match_scratch[1]);- let delta = PrefixMatchDelta {- additions: self.append_matches(&additions),- removals: self.append_matches(&removals),- };- self.match_scratch[0] = additions;- self.match_scratch[1] = removals;- delta- }-- fn push_delta(&mut self, delta: PrefixStateDelta) -> PrefixStateDeltaID {- self.deltas.push(delta);- self.key_tables.push(None);- PrefixStateDeltaID(- NonZeroU32::new(u32::try_from(self.deltas.len()).expect("selector prefix delta arena overflow")).unwrap(),- )- }-- fn delta(&self, id: PrefixStateDeltaID) -> PrefixStateDelta {- self.deltas[id.0.get() as usize - 1]- }-- fn key_table(&mut self, id: PrefixStateDeltaID, automaton: &PrefixAutomaton) -> &[(DispatchKey, PrefixStepID)] {- let index = id.0.get() as usize - 1;- if self.key_tables[index].is_none() {- let delta = self.deltas[index];- let key_of = |step: PrefixStepID| {- automaton.compounds[automaton.steps[step.0 as usize].compound.0 as usize].dispatch_key- };- let mut table = Vec::new();- for span in [delta.persisting_additions, delta.expiring_additions] {- for &step in self.get(span) {- table.push((key_of(step), step));- }- }- for span in [delta.persisting_removals, delta.expiring_removals] {- for &step in self.get(span) {- table.push((key_of(step), step));- if let Some(predecessor) = automaton.predecessor_of(step) {- table.push((key_of(predecessor), predecessor));- }- }- }- table.sort_unstable();- table.dedup();- self.key_table_bytes += table.len() * size_of::<(DispatchKey, PrefixStepID)>();- self.key_tables[index] = Some(table.into_boxed_slice());- }- self.key_tables[index].as_deref().unwrap()- }-- fn has_expiring_part(&self, id: PrefixStateDeltaID) -> bool {- let delta = self.delta(id);- delta.expiring_additions.len != 0 || delta.expiring_removals.len != 0- }-- fn sign_in_spans(&self, additions: PrefixStepSpan, removals: PrefixStepSpan, step: PrefixStepID) -> i8 {- if self.get(additions).binary_search(&step).is_ok() {- 1- } else if self.get(removals).binary_search(&step).is_ok() {- -1- } else {- 0- }- }-- fn persisting_sign(&self, delta: Option<PrefixStateDeltaID>, step: PrefixStepID) -> i8 {- let Some(delta) = delta.map(|id| self.delta(id)) else {- return 0;- };- self.sign_in_spans(delta.persisting_additions, delta.persisting_removals, step)- }-- fn state_sign(&self, delta: Option<PrefixStateDeltaID>, step: PrefixStepID) -> i8 {- let Some(delta) = delta.map(|id| self.delta(id)) else {- return 0;- };- let persisting = self.sign_in_spans(delta.persisting_additions, delta.persisting_removals, step);- let expiring = self.sign_in_spans(delta.expiring_additions, delta.expiring_removals, step);- persisting + expiring- }-- /// Whether an exact signed delta changes the active state viewed through `selection`.- ///- /// A step can occur in both delta partitions while moving between them, so test its combined- /// state sign instead of treating every non-empty span as a semantic change.- fn changes_selected_state(&self, id: PrefixStateDeltaID, selection: &PrefixSelection) -> bool {- let delta = self.delta(id);- [- delta.persisting_additions,- delta.persisting_removals,- delta.expiring_additions,- delta.expiring_removals,- ]- .into_iter()- .flat_map(|span| self.get(span))- .any(|&step| selection.contains_step(step) && self.state_sign(Some(id), step) != 0)- }-- fn persisting_only(&mut self, id: Option<PrefixStateDeltaID>) -> PrefixStateDeltaID {- let delta = id.map(|id| self.delta(id)).unwrap_or_default();- self.push_delta(PrefixStateDelta {- persisting_additions: delta.persisting_additions,- persisting_removals: delta.persisting_removals,- ..PrefixStateDelta::default()- })- }-- fn append_scratch_delta(&mut self, offset: usize) -> PrefixStateDeltaID {- let persisting_additions = std::mem::take(&mut self.scratch[offset]);- let persisting_removals = std::mem::take(&mut self.scratch[offset + 1]);- let expiring_additions = std::mem::take(&mut self.scratch[offset + 2]);- let expiring_removals = std::mem::take(&mut self.scratch[offset + 3]);- let delta = PrefixStateDelta {- persisting_additions: self.append(&persisting_additions),- persisting_removals: self.append(&persisting_removals),- expiring_additions: self.append(&expiring_additions),- expiring_removals: self.append(&expiring_removals),- };- self.scratch[offset] = persisting_additions;- self.scratch[offset + 1] = persisting_removals;- self.scratch[offset + 2] = expiring_additions;- self.scratch[offset + 3] = expiring_removals;- self.push_delta(delta)- }-- fn combine(&mut self, base: Option<PrefixStateDeltaID>, local: PrefixStateDeltaID) -> PrefixStateDeltaID {- for scratch in &mut self.scratch[..4] {- scratch.clear();- }- let base = base.map(|id| self.delta(id));- let local = self.delta(local);- for (index, (base_additions, base_removals, local_additions, local_removals)) in [- (- base.map(|delta| delta.persisting_additions),- base.map(|delta| delta.persisting_removals),- local.persisting_additions,- local.persisting_removals,- ),- (None, None, local.expiring_additions, local.expiring_removals),- ]- .into_iter()- .enumerate()- {- self.signed_scratch.clear();- for span in base_additions.into_iter().chain([local_additions]) {- let start = span.start as usize;- for index in start..start + span.len as usize {- self.signed_scratch.push((self.steps[index], 1));- }- }- for span in base_removals.into_iter().chain([local_removals]) {- let start = span.start as usize;- for index in start..start + span.len as usize {- self.signed_scratch.push((self.steps[index], -1));- }- }- self.signed_scratch.sort_unstable_by_key(|&(step, _)| step);- let mut cursor = 0;- while cursor < self.signed_scratch.len() {- let step = self.signed_scratch[cursor].0;- let mut sign = 0_i32;- while cursor < self.signed_scratch.len() && self.signed_scratch[cursor].0 == step {- sign += i32::from(self.signed_scratch[cursor].1);- cursor += 1;- }- if sign > 0 {- self.scratch[index * 2].push(step);- } else if sign < 0 {- self.scratch[index * 2 + 1].push(step);- }- }- }- self.append_scratch_delta(0)- }-}--impl<'a, 'b> PrefixEvaluation<'a, 'b> {- fn positional_test_matches(- &mut self,- node: StyleNodeID,- index: usize,- counters: &Counters,- ) -> Result<bool, Incomplete> {- let (program, test) = self.automaton.positional_tests()[index];- match test {- PrefixStructuralTest::Nth(nth) => {- self.evaluator- .matches_nth(self.programs.get(program), nth, node, counters)- }- PrefixStructuralTest::Empty => {- let row = self.row_of(node)?;- Ok(self.tree.first_element_child(node).is_none() && !row.facts.has_text_content_of(row.row))- }- }- }-- pub(super) fn step_matches_direct(- &mut self,- node: StyleNodeID,- step: PrefixStepID,- counters: &Counters,- ) -> Result<bool, Incomplete> {- let row = self.row_of(node)?;- let compound = &self.automaton.compounds[self.automaton.steps[step.0 as usize].compound.0 as usize];- match &compound.predicate {- PrefixPredicate::Features {- feature_start,- feature_len,- required_positional_bits,- } => {- let mut remaining = *required_positional_bits;- while remaining != 0 {- let index = remaining.trailing_zeros() as usize;- if !self.positional_test_matches(node, index, counters)? {- return Ok(false);- }- remaining &= remaining - 1;- }- Ok(self- .automaton- .features_for(*feature_start, *feature_len)- .all(|feature| matches_feature(row, feature)))- }- PrefixPredicate::Program { program, local, .. } => {- self.evaluator- .matches_prefix_local(*program, self.programs.get(*program), *local, node, counters)- }- }- }-- pub(super) fn step_matches(- &mut self,- node: StyleNodeID,- positional_bits: u32,- step: PrefixStepID,- counters: &Counters,- ) -> Result<bool, Incomplete> {- let row = self.row_of(node)?;- let compound = &self.automaton.compounds[self.automaton.steps[step.0 as usize].compound.0 as usize];- match &compound.predicate {- PrefixPredicate::Features {- feature_start,- feature_len,- required_positional_bits,- } => Ok(- (positional_bits & required_positional_bits) == *required_positional_bits- && self- .automaton- .features_for(*feature_start, *feature_len)- .all(|feature| matches_feature(row, feature)),- ),- PrefixPredicate::Program { program, local, .. } => {- self.evaluator- .matches_prefix_local(*program, self.programs.get(*program), *local, node, counters)- }- }- }-- /// The per-node answers of the automaton's positional tests, one bit per test. Zero for- /// automata without positional steps, so fact-cohort sharing is unchanged there.- pub(super) fn positional_bits(&mut self, node: StyleNodeID, counters: &Counters) -> Result<u32, Incomplete> {- let tests = self.automaton.positional_tests();- let mut bits = 0_u32;- for index in 0..tests.len() {- if self.positional_test_matches(node, index, counters)? {- bits |= 1 << index;- }- }- Ok(bits)- }-- pub(super) fn new(- automaton: &'a PrefixAutomaton,- tree: &'a StyleNodeTree,- facts: &'a StyleNodeFacts,- programs: &'a SelectorPrograms,- evaluator: &'a mut MatchEvaluator<'b>,- shadow_root: Option<StyleNodeID>,- selection: Option<&'a PrefixSelection>,- ) -> Self {- Self {- automaton,- tree,- facts,- programs,- evaluator,- shadow_root,- selection,- }- }-- fn row_of(&self, node: StyleNodeID) -> Result<MatchFactRow<'b>, Incomplete> {- self.evaluator.row_of(node)- }-- fn facts_are_composite(&self) -> bool {- !self.evaluator.serves_only_resident_rows()- }-}--impl PrefixStates {- #[must_use]- pub(super) fn new() -> Self {- Self {- identity: next_prefix_states_identity(),- relation_answers: Column::default(),- relation: None,- states: vec![PrefixState::default()],- delta_steps: Vec::new(),- states_by_hash: HashMap::default(),- states_by_hash_collision_bytes: 0,- match_offsets: vec![0, 0],- match_entries: Vec::new(),- truth_offsets: vec![0, 0],- truth_steps: Vec::new(),- truth_sets_by_hash: super::intern_table::InternTable::default(),- results: vec![PrefixResult {- matches: PrefixMatchSetID(0),- truth: PrefixTruthSetID(0),- }],- result_ids: super::intern_table::InternTable::default(),- match_sets_by_hash: super::intern_table::InternTable::default(),- local_fact_interner: LocalFactInterner::new(),- transition_by_element: Column::new(|| UNKNOWN_TRANSITION),- entering_by_element: Column::new(|| UNKNOWN_ENTERING_STATES),- local_facts_by_element: Column::default(),- positional_bits_by_element: Column::default(),- candidate_epoch: EpochColumn::default(),- comparison_epoch: 0,- comparison_marks: EpochColumn::default(),- compound_epoch: EpochColumn::default(),- compound_answer: Vec::new(),- output_epoch: EpochColumn::default(),- match_epoch: EpochColumn::default(),- parent_persisting_epoch: EpochColumn::default(),- previous_persisting_epoch: EpochColumn::default(),- candidates: Vec::new(),- compare_left: Vec::new(),- compare_right: Vec::new(),- output_matches: Vec::new(),- output_matched_steps: Vec::new(),- new_descendant: Vec::new(),- new_child: Vec::new(),- new_following: Vec::new(),- new_adjacent: Vec::new(),- new_descendant_hash: 0,- new_child_hash: 0,- new_following_hash: 0,- new_adjacent_hash: 0,- descendant_only: vec![0],- epoch: 0,- complete: false,- automaton_step_count: 0,- automaton_statistics_recorded: false,- last_compacted_working_bytes: 0,- }- }-- pub(super) fn match_set_for(- &mut self,- scratch: &mut PrefixTransitionScratch,- effects: &mut PrefixEffects,- evaluation: &mut PrefixEvaluation<'_, '_>,- node: StyleNodeID,- counters: &Counters,- ) -> PrefixTransitionLookup<PrefixMatchSetID> {- if let Some(matches) = self.relation_answer(node) {- return PrefixTransitionLookup::Known(matches);- }- match scratch- .by_node- .get(&node)- .copied()- .map_or_else(|| self.transition_of(node), PrefixTransitionLookup::Known)- {- PrefixTransitionLookup::Known(transition) => {- counters.bump(Counter::PrefixTransitionCacheMatchHits);- return PrefixTransitionLookup::Known(self.matches_of(transition));- }- PrefixTransitionLookup::Missing(_) => {}- }- counters.bump(Counter::PrefixTransitionCacheMatchMisses);- match self.transition_for(scratch, effects, evaluation, node, counters) {- PrefixTransitionLookup::Known(transition) => PrefixTransitionLookup::Known(self.matches_of(transition)),- PrefixTransitionLookup::Missing(gap) => PrefixTransitionLookup::Missing(gap),- }- }-- pub(super) fn matches_in(&self, matches: PrefixMatchSetID) -> &[EntryID] {- let index = matches.0 as usize;- &self.match_entries[self.match_offsets[index] as usize..self.match_offsets[index + 1] as usize]- }-- /// Read the exact terminal matches already retained for one element without extending the- /// prefix relation. A missing transition is not an empty answer.- pub(super) fn retained_matches_for(&self, node: StyleNodeID) -> Option<&[EntryID]> {- if let Some(matches) = self.relation_answer(node) {- return Some(self.matches_in(matches));- }- match self.transition_of(node) {- PrefixTransitionLookup::Known(transition) => Some(self.matches_in(self.matches_of(transition))),- PrefixTransitionLookup::Missing(_) => None,- }- }-- fn relation_answer(&self, node: StyleNodeID) -> Option<PrefixMatchSetID> {- node.element_index()- .and_then(|index| self.relation_answers.get(index as usize))- .copied()- .flatten()- }-- fn install_relation_answer(&mut self, node: StyleNodeID, entries: &[EntryID]) {- self.output_matches.clear();- self.output_matches.extend_from_slice(entries);- let matches = self.intern_output_matches();- self.relation_answers- .insert(node.element_index().unwrap() as usize, Some(matches));- }-- fn matches_of(&self, transition: PrefixTransition) -> PrefixMatchSetID {- let result = self.results[transition.result.0 as usize];- debug_assert!((result.truth.0 as usize) + 1 < self.truth_offsets.len());- result.matches- }-- fn truth_in(&self, truth: PrefixTruthSetID) -> &[PrefixStepID] {- let index = truth.0 as usize;- &self.truth_steps[self.truth_offsets[index] as usize..self.truth_offsets[index + 1] as usize]- }-- fn additions_in(&self, state: u32) -> &[PrefixStepID] {- let state = &self.states[state as usize];- let start = state.payload_start as usize;- // SAFETY: Every referenced state range is initialized. Sparse rebases can leave- // unreferenced holes in the arena, but never point a state at one.- unsafe {- ak::slice_from_raw_parts(- self.delta_steps.as_ptr().add(start).cast::<PrefixStepID>(),- state.additions_len as usize,- )- }- }-- fn expiring_in(&self, state: u32) -> &[PrefixStepID] {- let state = &self.states[state as usize];- let start = state.payload_start as usize + state.additions_len as usize;- // SAFETY: See `additions_in`; this is the initialized suffix of the same payload.- unsafe {- ak::slice_from_raw_parts(- self.delta_steps.as_ptr().add(start).cast::<PrefixStepID>(),- state.expiring_len as usize,- )- }- }-- /// Collect one state's persisting steps into `into` by walking its base chain. The levels'- /// additions are mutually disjoint by construction, so the result is the exact persisting- /// set, unsorted.- fn collect_persisting(&self, state: u32, into: &mut Vec<PrefixStepID>) {- let mut current = state;- loop {- into.extend_from_slice(self.additions_in(current));- let base = self.states[current as usize].base;- if base == current {- break;- }- current = base;- }- }-- fn collect_active(&self, state: u32, into: &mut Vec<PrefixStepID>) {- into.extend_from_slice(self.expiring_in(state));- self.collect_persisting(state, into);- }-- /// Whether two states hold the same active steps, viewed through an optional selection.- ///- /// A selection can make states with different complete contents equal, so identity is only a- /// fast positive here. The persisting hash is a fast negative when no selection filters the- /// view; the full check compares both persisting sets through dense epoch marks, with the- /// expiring parts compared directly.- fn selected_states_equal(&mut self, left: u32, right: u32, selection: Option<&PrefixSelection>) -> bool {- if left == right {- return true;- }- let left_contents = &self.states[left as usize];- let right_contents = &self.states[right as usize];- if selection.is_none()- && (left_contents.descendant_len != right_contents.descendant_len- || left_contents.descendant_hash != right_contents.descendant_hash)- {- return false;- }- advance_epoch(&mut self.comparison_epoch, 2, &mut [&mut self.comparison_marks]);- let left_epoch = self.comparison_epoch - 1;- let right_epoch = self.comparison_epoch;- let mut compare_epoch = std::mem::take(&mut self.comparison_marks);- compare_epoch.ensure_len(self.automaton_step_count);- let mut left_count = 0;- let mut current = left;- loop {- for &step in self.additions_in(current) {- if selection.is_some_and(|selection| !selection.contains_step(step)) {- continue;- }- let mark = &mut compare_epoch[step.0 as usize];- if *mark != left_epoch {- *mark = left_epoch;- left_count += 1;- }- }- let base = self.states[current as usize].base;- if base == current {- break;- }- current = base;- }- let mut right_count = 0;- let mut equal = true;- current = right;- 'right: loop {- for &step in self.additions_in(current) {- if selection.is_some_and(|selection| !selection.contains_step(step)) {- continue;- }- let mark = &mut compare_epoch[step.0 as usize];- if *mark == right_epoch {- continue;- }- if *mark != left_epoch {- equal = false;- break 'right;- }- *mark = right_epoch;- right_count += 1;- }- let base = self.states[current as usize].base;- if base == current {- break;- }- current = base;- }- equal &= left_count == right_count;- if equal {- let left_expiring = self.expiring_in(left).iter().copied();- let right_expiring = self.expiring_in(right).iter().copied();- equal = match selection {- Some(selection) => left_expiring- .filter(|&step| selection.contains_step(step))- .eq(right_expiring.filter(|&step| selection.contains_step(step))),- None => left_expiring.eq(right_expiring),- };- }- self.comparison_marks = compare_epoch;- equal- }-- /// Find the canonical state with `probe`'s complete contents. Copy each candidate identity out- /// before comparison because the equality check borrows the state scratch mutably.- fn find_equal_state(&mut self, key: (u32, u64, u32, u32), probe: u32) -> Option<u32> {- let first = self.states_by_hash.get(&key)?.first.0;- if self.states_have_equal_contents(first, probe) {- return Some(first);- }- let collision_count = self.states_by_hash[&key].collisions.len();- for index in 0..collision_count {- let candidate = self.states_by_hash[&key].collisions[index].0;- if self.states_have_equal_contents(candidate, probe) {- return Some(candidate);- }- }- None- }-- fn states_have_equal_contents(&mut self, left: u32, right: u32) -> bool {- let left_contents = &self.states[left as usize];- let right_contents = &self.states[right as usize];- if left_contents.base == right_contents.base- && self.additions_in(left) == self.additions_in(right)- && self.expiring_in(left) == self.expiring_in(right)- {- return true;- }- self.selected_states_equal(left, right, None)- }-- fn remember_state(&mut self, key: (u32, u64, u32, u32), state: u32) {- match self.states_by_hash.entry(key) {- std::collections::hash_map::Entry::Vacant(entry) => {- entry.insert(PrefixStateCandidates {- first: PrefixStateID(state),- collisions: Vec::new(),- });- }- std::collections::hash_map::Entry::Occupied(mut entry) => {- let collisions = &mut entry.get_mut().collisions;- let old_capacity = collisions.capacity();- collisions.push(PrefixStateID(state));- self.states_by_hash_collision_bytes +=- ((collisions.capacity() - old_capacity) * size_of::<PrefixStateID>()) as u64;- }- }- }-- fn transition_of(&self, node: StyleNodeID) -> PrefixTransitionLookup<PrefixTransition> {- let Some(index) = node.element_index().map(|index| index as usize) else {- return PrefixTransitionLookup::Missing(PrefixTransitionGap::MissingTransition(node));- };- match self- .transition_by_element- .get(index)- .copied()- .filter(|transition| transition.state != UNKNOWN_STATE)- {- Some(transition) => PrefixTransitionLookup::Known(transition),- None => PrefixTransitionLookup::Missing(PrefixTransitionGap::MissingTransition(node)),- }- }-- #[must_use]- pub(super) fn has_transition(&self, node: StyleNodeID) -> bool {- matches!(self.transition_of(node), PrefixTransitionLookup::Known(_))- }-- fn set_transition(&mut self, node: StyleNodeID, transition: PrefixTransition) {- let Some(index) = node.element_index().map(|index| index as usize) else {- return;- };- self.transition_by_element.insert(index, transition);- }-- fn set_entering(&mut self, node: StyleNodeID, entering: EnteringStates) {- let Some(index) = node.element_index().map(|index| index as usize) else {- return;- };- self.entering_by_element.insert(index, entering);- }-- fn entering_of(&self, node: StyleNodeID) -> Option<EnteringStates> {- let index = node.element_index()? as usize;- self.entering_by_element- .get(index)- .copied()- .filter(|entering| entering.parent != UNKNOWN_STATE)- }-- fn local_facts_of(&self, node: StyleNodeID) -> Option<u32> {- let index = node.element_index()? as usize;- self.local_facts_by_element- .get(index)- .copied()- .filter(|&identity| identity != 0)- }-- fn set_local_facts(&mut self, node: StyleNodeID, identity: u32) {- let Some(index) = node.element_index().map(|index| index as usize) else {- return;- };- self.local_facts_by_element.insert(index, identity);- }-- fn set_positional_bits(&mut self, node: StyleNodeID, bits: u32) {- let Some(index) = node.element_index().map(|index| index as usize) else {- return;- };- self.positional_bits_by_element.insert(index, bits);- }-- fn positional_bits_of(&self, node: StyleNodeID) -> u32 {- node.element_index()- .and_then(|index| self.positional_bits_by_element.get(index as usize))- .copied()- .unwrap_or(0)- }-- pub(super) fn forget_transition(&mut self, node: StyleNodeID) {- let Some(index) = node.element_index().map(|index| index as usize) else {- return;- };- if let Some(answer) = self.relation_answers.get_mut(index) {- *answer = None;- }- let Some(transition) = self.transition_by_element.get_mut(index) else {- return;- };- *transition = UNKNOWN_TRANSITION;- if let Some(entering) = self.entering_by_element.get_mut(index) {- *entering = UNKNOWN_ENTERING_STATES;- }- if let Some(local_facts) = self.local_facts_by_element.get_mut(index) {- *local_facts = 0;- }- if let Some(positional_bits) = self.positional_bits_by_element.get_mut(index) {- *positional_bits = 0;- }- }-- fn persisting_state_contains_step(&self, state: u32, step: PrefixStepID) -> bool {- let step_index = step.0;- let mut current = state;- loop {- if self- .additions_in(current)- .binary_search_by_key(&step_index, |candidate| candidate.0)- .is_ok()- {- return true;- }- let base = self.states[current as usize].base;- if base == current {- return false;- }- current = base;- }- }-- fn state_contains_step(&self, state: u32, step: PrefixStepID) -> bool {- let step_index = step.0;- self.expiring_in(state)- .binary_search_by_key(&step_index, |candidate| candidate.0)- .is_ok()- || self.persisting_state_contains_step(state, step)- }-- pub(super) fn producer_is_active(- &self,- automaton: &PrefixAutomaton,- node: StyleNodeID,- producer: PrefixProducer,- ) -> bool {- let Some(entering) = self.entering_of(node) else {- return false;- };- automaton.predecessor_of(producer.step).is_none()- || self.state_contains_step(entering.parent, producer.step)- || self.state_contains_step(entering.previous, producer.step)- }-- fn state_membership_across_delta(- &self,- old_state: u32,- new_state: u32,- delta: Option<PrefixStateDeltaID>,- arena: &PrefixDeltaArena,- step: PrefixStepID,- ) -> (bool, bool) {- match arena.state_sign(delta, step) {- 1 => (false, true),- -1 => (true, false),- 0 => {- let old_contains = self.state_contains_step(old_state, step);- let new_contains = if delta.is_some() || old_state == new_state {- old_contains- } else {- self.state_contains_step(new_state, step)- };- (old_contains, new_contains)- }- _ => unreachable!("prefix state delta is signed"),- }- }-- fn persisting_membership_across_delta(- &self,- old_state: u32,- new_state: u32,- delta: Option<PrefixStateDeltaID>,- arena: &PrefixDeltaArena,- step: PrefixStepID,- ) -> (bool, bool) {- match arena.persisting_sign(delta, step) {- 1 => (false, true),- -1 => (true, false),- 0 => {- let old_contains = self.persisting_state_contains_step(old_state, step);- let new_contains = if delta.is_some() || old_state == new_state {- old_contains- } else {- self.persisting_state_contains_step(new_state, step)- };- (old_contains, new_contains)- }- _ => unreachable!("prefix persisting delta is signed"),- }- }-- fn collect_delta_steps(&self, delta: PrefixStateDeltaID, arena: &PrefixDeltaArena, into: &mut Vec<PrefixStepID>) {- let delta = arena.delta(delta);- for span in [- delta.persisting_additions,- delta.persisting_removals,- delta.expiring_additions,- delta.expiring_removals,- ] {- into.extend_from_slice(arena.get(span));- }- }-- #[allow(clippy::too_many_arguments)]- fn emit_local_output_deltas(- &self,- evaluation: &mut PrefixEvaluation<'_, '_>,- old_evaluation: &mut PrefixEvaluation<'_, '_>,- node: StyleNodeID,- old: PrefixTransition,- old_entering: EnteringStates,- entering: EnteringStates,- entering_deltas: PrefixEnteringDeltas,- positional_bits: u32,- affected: &[PrefixStepID],- local_producers: Option<&[PrefixProducer]>,- use_admitted_new_truth: bool,- arena: &mut PrefixDeltaArena,- counters: &Counters,- ) -> Result<PrefixLocalOutputDeltas, Incomplete> {- for scratch in &mut arena.scratch {- scratch.clear();- }- for scratch in &mut arena.match_scratch {- scratch.clear();- }- let old_truth = self.results[old.result.0 as usize].truth;- let old_positional_bits = self.positional_bits_of(node);- let mut outputs_changed = false;- let mut result_changed = false;- let mut result_delta_complete = true;- for &step in affected {- let producer = local_producers.and_then(|producers| {- producers- .binary_search_by_key(&step, |producer| producer.step)- .ok()- .map(|index| producers[index])- });- let is_root = evaluation.automaton.predecessor_of(step).is_none();- let (old_parent, new_parent) = self.state_membership_across_delta(- old_entering.parent,- entering.parent,- entering_deltas.parent,- arena,- step,- );- let (old_previous, new_previous) = self.state_membership_across_delta(- old_entering.previous,- entering.previous,- entering_deltas.previous,- arena,- step,- );- let was_active = is_root || old_parent || old_previous;- let is_active = is_root || new_parent || new_previous;- if !was_active && !is_active {- continue;- }- let compound =- &evaluation.automaton.compounds[evaluation.automaton.steps[step.0 as usize].compound.0 as usize];- let (old_predicate_matches, new_predicate_matches) = match producer {- Some(producer) => {- let old_matches = match &compound.predicate {- PrefixPredicate::Program { .. } => self.truth_in(old_truth).binary_search(&step).is_ok(),- PrefixPredicate::Features { .. } => {- old_evaluation.step_matches_direct(node, producer.step, counters)?- }- };- let new_matches = if use_admitted_new_truth {- let compound_index = evaluation.automaton.steps[step.0 as usize].compound.0 as usize;- self.compound_epoch[compound_index] == self.epoch && self.compound_answer[compound_index]- } else {- evaluation.step_matches_direct(node, producer.step, counters)?- };- (old_matches, new_matches)- }- None => match &compound.predicate {- PrefixPredicate::Program { .. } => (- self.truth_in(old_truth).binary_search(&step).is_ok(),- evaluation.step_matches(node, positional_bits, step, counters)?,- ),- PrefixPredicate::Features { .. } => (- old_evaluation.step_matches(node, old_positional_bits, step, counters)?,- evaluation.step_matches(node, positional_bits, step, counters)?,- ),- },- };- let old_matches = was_active && old_predicate_matches;- let new_matches = is_active && new_predicate_matches;- let local_changed = old_matches != new_matches;- if local_changed && matches!(compound.predicate, PrefixPredicate::Program { .. }) {- outputs_changed = true;- result_changed = true;- result_delta_complete = false;- }- for output in evaluation- .automaton- .outputs_for(&evaluation.automaton.steps[step.0 as usize])- {- if local_changed {- outputs_changed = true;- match output.kind {- PrefixOutputKind::UniqueTerminal => {- let terminal = EntryID(output.target);- if evaluation- .selection- .is_none_or(|selection| selection.contains_terminal(terminal))- {- result_changed = true;- arena.match_scratch[usize::from(!new_matches)].push(terminal);- }- }- PrefixOutputKind::SharedTerminal => {- let terminal = EntryID(output.target);- if evaluation- .selection- .is_none_or(|selection| selection.contains_terminal(terminal))- {- result_changed = true;- result_delta_complete = false;- }- }- _ => {}- }- }- let target = PrefixStepID(output.target);- let correction = match output.kind {- PrefixOutputKind::Descendant => {- let (inherited_old, inherited_new) = self.persisting_membership_across_delta(- old_entering.parent,- entering.parent,- entering_deltas.parent,- arena,- target,- );- i8::from(inherited_new || new_matches)- - i8::from(inherited_old || old_matches)- - (i8::from(inherited_new) - i8::from(inherited_old))- }- PrefixOutputKind::FollowingSibling => {- let (inherited_old, inherited_new) = self.persisting_membership_across_delta(- old_entering.previous,- entering.previous,- entering_deltas.previous,- arena,- target,- );- i8::from(inherited_new || new_matches)- - i8::from(inherited_old || old_matches)- - (i8::from(inherited_new) - i8::from(inherited_old))- }- PrefixOutputKind::Child | PrefixOutputKind::NextSibling => {- i8::from(new_matches) - i8::from(old_matches)- }- PrefixOutputKind::UniqueTerminal | PrefixOutputKind::SharedTerminal => continue,- };- if correction != 0 {- outputs_changed = true;- }- let index = match (output.kind, correction) {- (PrefixOutputKind::Descendant, 1) => 0,- (PrefixOutputKind::Descendant, -1) => 1,- (PrefixOutputKind::Child, 1) => 2,- (PrefixOutputKind::Child, -1) => 3,- (PrefixOutputKind::FollowingSibling, 1) => 4,- (PrefixOutputKind::FollowingSibling, -1) => 5,- (PrefixOutputKind::NextSibling, 1) => 6,- (PrefixOutputKind::NextSibling, -1) => 7,- (_, 0) => continue,- (_, _) => unreachable!("prefix output correction is a signed set delta"),- };- arena.scratch[index].push(target);- }- }- for scratch in &mut arena.scratch {- scratch.sort_unstable();- scratch.dedup();- }- for scratch in &mut arena.match_scratch {- scratch.sort_unstable();- scratch.dedup();- }- Ok(PrefixLocalOutputDeltas {- continuation: arena.append_scratch_delta(0),- right: arena.append_scratch_delta(4),- matches: arena.append_match_delta(),- outputs_changed,- result_changed,- result_delta_complete,- })- }-- #[allow(clippy::too_many_arguments)]- fn rebase_payload_with_local_delta(- &mut self,- source_state: u32,- old_base_state: u32,- new_base_state: u32,- delta: PrefixStateDeltaID,- arena: &PrefixDeltaArena,- downward: bool,- counters: &Counters,- ) -> Option<u32> {- let mut additions = match downward {- true => std::mem::take(&mut self.new_descendant),- false => std::mem::take(&mut self.new_following),- };- let mut expiring = match downward {- true => std::mem::take(&mut self.new_child),- false => std::mem::take(&mut self.new_adjacent),- };- additions.clear();- expiring.clear();- if source_state != old_base_state {- let source = &self.states[source_state as usize];- if source.base != old_base_state {- match downward {- true => {- self.new_descendant = additions;- self.new_child = expiring;- }- false => {- self.new_following = additions;- self.new_adjacent = expiring;- }- }- return None;- }- additions.extend_from_slice(self.additions_in(source_state));- expiring.extend_from_slice(self.expiring_in(source_state));- }- let delta = arena.delta(delta);- let removals = arena.get(delta.persisting_removals);- if !removals.is_empty() {- additions.retain(|step| removals.binary_search(step).is_err());- }- additions.extend_from_slice(arena.get(delta.persisting_additions));- additions.retain(|&step| !self.persisting_state_contains_step(new_base_state, step));- additions.sort_unstable();- additions.dedup();- let removals = arena.get(delta.expiring_removals);- if !removals.is_empty() {- expiring.retain(|step| removals.binary_search(step).is_err());- }- expiring.extend_from_slice(arena.get(delta.expiring_additions));- expiring.sort_unstable();- expiring.dedup();- let additions_hash = additions- .iter()- .fold(0_u64, |hash, &step| hash.wrapping_add(step_hash(step)));- let expiring_hash = expiring- .iter()- .fold(0_u32, |hash, &step| hash.wrapping_add(step_hash(step) as u32));- let state = self.intern_extended_state(- new_base_state,- &additions,- additions_hash,- &expiring,- expiring_hash,- counters,- );- match downward {- true => {- self.new_descendant = additions;- self.new_child = expiring;- }- false => {- self.new_following = additions;- self.new_adjacent = expiring;- }- }- Some(state)- }-- fn apply_local_match_delta(- &mut self,- old_result: PrefixResultID,- delta: PrefixMatchDelta,- arena: &PrefixDeltaArena,- ) -> PrefixResultID {- if delta.additions.len == 0 && delta.removals.len == 0 {- return old_result;- }- let old_result_value = self.results[old_result.0 as usize];- let mut matches = std::mem::take(&mut self.output_matches);- matches.clear();- matches.extend_from_slice(self.matches_in(old_result_value.matches));- let removals = arena.get_matches(delta.removals);- matches.retain(|entry| removals.binary_search(entry).is_err());- matches.extend_from_slice(arena.get_matches(delta.additions));- matches.sort_unstable();- matches.dedup();- self.output_matches = matches;- let matches = self.intern_output_matches();- self.intern_result(matches, old_result_value.truth)- }-- #[allow(clippy::too_many_arguments)]- fn try_sparse_retained_local_transition(- &mut self,- scratch: &mut PrefixTransitionScratch,- effects: &mut PrefixEffects,- evaluation: &mut PrefixEvaluation<'_, '_>,- node: StyleNodeID,- old: PrefixTransition,- entering: EnteringStates,- entering_deltas: PrefixEnteringDeltas,- local_facts: u32,- positional_bits: u32,- local_output_deltas: PrefixLocalOutputDeltas,- delta_arena: &PrefixDeltaArena,- counters: &Counters,- ) -> Option<PrefixTransition> {- let old_entering = self.entering_of(node)?;- if entering_deltas.parent.is_none() && entering_deltas.previous.is_none() {- return None;- }- if self.local_facts_of(node) != Some(local_facts) || self.positional_bits_of(node) != positional_bits {- return None;- }- if local_output_deltas.result_changed && !local_output_deltas.result_delta_complete {- return None;- }- let (state, right) = if local_output_deltas.outputs_changed {- (- self.rebase_payload_with_local_delta(- old.state,- old_entering.parent,- entering.parent,- local_output_deltas.continuation,- delta_arena,- true,- counters,- )?,- self.rebase_payload_with_local_delta(- old.right,- old_entering.previous,- entering.previous,- local_output_deltas.right,- delta_arena,- false,- counters,- )?,- )- } else {- (- self.rebase_unchanged_local_payload(old.state, old_entering.parent, entering.parent, counters)?,- self.rebase_unchanged_local_payload(old.right, old_entering.previous, entering.previous, counters)?,- )- };- let result = match local_output_deltas.result_changed {- true => self.apply_local_match_delta(old.result, local_output_deltas.matches, delta_arena),- false => old.result,- };- let transition = PrefixTransition { state, right, result };- scratch.memo.insert(- PrefixTransitionKey {- parent: entering.parent,- previous: entering.previous,- local_facts,- is_document_root: evaluation.tree.parent(node).is_none(),- positional_bits,- },- transition,- );- let mut surface = PrefixTransitionSurface {- states: self,- scratch,- effects,- };- surface.remember_inputs(- evaluation,- node,- transition,- TransitionInputs {- entering,- local_facts,- positional_bits,- },- );- surface.remember_transition(node, transition);- Some(transition)- }-- /// Compare one node's transition against the retained one and update the cache.- ///- /// `selection` narrows difference detection to the rules the flush routed; a topology flush- /// passes `None` because a tree change can move matches no route named.- #[allow(clippy::too_many_arguments)]- pub(super) fn compare_and_update(- &mut self,- scratch: &mut PrefixTransitionScratch,- effects: &mut PrefixEffects,- evaluation: &mut PrefixEvaluation<'_, '_>,- old_evaluation: &mut PrefixEvaluation<'_, '_>,- selection: Option<&PrefixSelection>,- node: StyleNodeID,- local_facts_changed: bool,- local_affected_candidates: Option<&[PrefixProducer]>,- entering_deltas: PrefixEnteringDeltas,- positional_truth_stable: bool,- delta_arena: &mut PrefixDeltaArena,- counters: &Counters,- ) -> PrefixTransitionLookup<PrefixDifference> {- let row = match evaluation.row_of(node) {- Ok(row) => row,- Err(incomplete) => {- return PrefixTransitionLookup::Missing(PrefixTransitionGap::Incomplete(incomplete));- }- };- // NB: Compare against retained inputs throughout convergence. Current parent and- // preceding-sibling outputs are read through the context scratch below.- let old = match self.transition_of(node) {- PrefixTransitionLookup::Known(transition) => Some(transition),- PrefixTransitionLookup::Missing(_) => None,- };- let parent_state = match evaluation.tree.parent(node) {- Some(parent) => match self.transition_for(scratch, effects, evaluation, parent, counters) {- PrefixTransitionLookup::Known(transition) => transition.state,- PrefixTransitionLookup::Missing(gap) => return PrefixTransitionLookup::Missing(gap),- },- None => 0,- };- let previous_state = if evaluation.automaton.has_sibling_steps() {- match evaluation.tree.previous_element_sibling(node) {- Some(previous) => match self.transition_for(scratch, effects, evaluation, previous, counters) {- PrefixTransitionLookup::Known(transition) => transition.right,- PrefixTransitionLookup::Missing(gap) => return PrefixTransitionLookup::Missing(gap),- },- None => 0,- }- } else {- 0- };- // A topology flush walks whole subtrees under a moved sibling because the steps its- // positional flip enabled or disabled persist into every descendant. A descendant that- // carries none of the features those steps test cannot match them on either side, so- // its transition is the old one rebased onto the parent's new state: no compound, no- // positional test, no match set changes hands.- if !local_facts_changed- && selection.is_none()- && positional_truth_stable- && entering_deltas.previous.is_none()- && let Some(old) = old- && let Some(old_entering) = self.entering_of(node)- && old_entering.previous == previous_state- && let Some(delta) = entering_deltas.parent- && {- let matches = entering_deltas.parent_endpoints == (old_entering.parent, parent_state);- if !matches {- counters.bump(Counter::PrefixDeadDeltaBailEndpoints);- }- matches- }- && let Some(difference) = self.derive_dead_delta_transition(- scratch,- effects,- evaluation,- node,- row,- old,- old_entering,- parent_state,- delta,- delta_arena,- counters,- )- {- return PrefixTransitionLookup::Known(difference);- }- let local_facts =- scratch.ensure_local_fact_identity(self, evaluation.automaton, evaluation.facts, node, counters);- let positional_bits = if positional_truth_stable && old.is_some() {- self.positional_bits_of(node)- } else {- match evaluation.positional_bits(node, counters) {- Ok(bits) => bits,- Err(incomplete) => return PrefixTransitionLookup::Missing(PrefixTransitionGap::Incomplete(incomplete)),- }- };- let entering = EnteringStates {- parent: parent_state,- previous: previous_state,- };- let old_entering = self.entering_of(node);- // Interner give-back can strand a node with a remapped transition but no surviving- // entering states: the entering names the parent's old state, which dies with a forgotten- // parent transition. Local output deltas replay from the old entering, so without one the- // difference has to come from comparing the interned state chains instead.- let can_derive_delta = selection.is_some()- && (entering_deltas.parent.is_some()- || entering_deltas.previous.is_some()- || local_affected_candidates.is_some())- && (!local_facts_changed || local_affected_candidates.is_some())- && old_entering.is_some();- let mut affected_candidates = std::mem::take(&mut self.candidates);- affected_candidates.clear();- for delta in [entering_deltas.parent, entering_deltas.previous].into_iter().flatten() {- self.collect_delta_steps(delta, delta_arena, &mut affected_candidates);- }- for delta in [entering_deltas.parent, entering_deltas.previous].into_iter().flatten() {- let delta = delta_arena.delta(delta);- for span in [delta.persisting_additions, delta.persisting_removals] {- for &step in delta_arena.get(span) {- if let Some(predecessor) = evaluation.automaton.predecessor_of(step) {- affected_candidates.push(predecessor);- }- }- }- }- if local_facts_changed && let Some(local_affected_candidates) = local_affected_candidates {- let mut active_candidates = std::mem::take(&mut self.compare_left);- active_candidates.clear();- for active in [- old_entering.map(|entering| entering.parent),- old_entering.map(|entering| entering.previous),- Some(entering.parent),- Some(entering.previous),- ]- .into_iter()- .flatten()- {- self.collect_active(active, &mut active_candidates);- }- let mut append_roots = |evaluation: &mut PrefixEvaluation<'_, '_>| {- let Ok(row) = evaluation.row_of(node) else {- return;- };- row.facts- .for_each_dispatch_probe(row.row, evaluation.tree.parent(node).is_none(), |key, _| {- if let Some(bucket) = evaluation.automaton.bucket(key) {- active_candidates.extend_from_slice(bucket.root_steps.as_slice());- }- });- };- append_roots(old_evaluation);- append_roots(evaluation);- active_candidates.retain(|step| {- local_affected_candidates- .binary_search_by_key(step, |producer| producer.step)- .is_ok()- });- affected_candidates.extend_from_slice(&active_candidates);- self.compare_left = active_candidates;- }- affected_candidates.sort_unstable();- affected_candidates.dedup();- let is_document_root = evaluation.tree.parent(node).is_none();- affected_candidates.retain(|&step| {- local_affected_candidates- .is_some_and(|producers| producers.binary_search_by_key(&step, |producer| producer.step).is_ok())- || row.facts.carries_dispatch_key(- row.row,- evaluation.automaton.compounds[evaluation.automaton.steps[step.0 as usize].compound.0 as usize]- .dispatch_key,- is_document_root,- )- });- let local_output_deltas = if can_derive_delta && !local_facts_changed {- old.zip(old_entering).map(|(old, old_entering)| {- self.emit_local_output_deltas(- evaluation,- old_evaluation,- node,- old,- old_entering,- entering,- entering_deltas,- positional_bits,- &affected_candidates,- local_affected_candidates,- false,- delta_arena,- counters,- )- })- } else {- None- };- let mut local_output_deltas = match local_output_deltas.transpose() {- Ok(deltas) => deltas,- Err(incomplete) => {- self.candidates = affected_candidates;- return PrefixTransitionLookup::Missing(PrefixTransitionGap::Incomplete(incomplete));- }- };- let sparse = if !local_facts_changed && selection.is_some() {- match (old, local_output_deltas) {- (Some(old), Some(local_output_deltas)) => self.try_sparse_retained_local_transition(- scratch,- effects,- evaluation,- node,- old,- entering,- entering_deltas,- local_facts,- positional_bits,- local_output_deltas,- delta_arena,- counters,- ),- _ => None,- }- } else {- None- };- let used_sparse_transition = sparse.is_some();- let (new, use_admitted_new_truth) = if let Some(transition) = sparse {- (transition, false)- } else {- let mut surface = PrefixTransitionSurface {- states: self,- scratch,- effects,- };- let (transition, origin) = match surface.transition_from_inputs(- evaluation,- node,- row,- TransitionInputs {- entering: EnteringStates {- parent: entering.parent,- previous: entering.previous,- },- local_facts,- positional_bits,- },- counters,- ) {- PrefixTransitionLookup::Known(transition) => transition,- PrefixTransitionLookup::Missing(gap) => return PrefixTransitionLookup::Missing(gap),- };- surface.remember_transition(node, transition);- (transition, origin == PrefixTransitionOrigin::Computed)- };-- let Some(old) = old else {- if evaluation.tree.children(node).next().is_some() {- self.complete = false;- }- return PrefixTransitionLookup::Known(PrefixDifference {- continuation_changed: true,- right_changed: true,- matches_changed: true,- arrived: true,- old_matches: self.matches_of(new),- new_matches: self.matches_of(new),- continuation_delta: None,- continuation_endpoints: (UNKNOWN_STATE, UNKNOWN_STATE),- right_delta: None,- });- };- if local_output_deltas.is_none()- && can_derive_delta- && let Some(old_entering) = old_entering- {- local_output_deltas = match self.emit_local_output_deltas(- evaluation,- old_evaluation,- node,- old,- old_entering,- entering,- entering_deltas,- positional_bits,- &affected_candidates,- local_affected_candidates,- use_admitted_new_truth,- delta_arena,- counters,- ) {- Ok(deltas) => Some(deltas),- Err(incomplete) => {- self.candidates = affected_candidates;- return PrefixTransitionLookup::Missing(PrefixTransitionGap::Incomplete(incomplete));- }- };- }- let sparse_has_local_output_delta = used_sparse_transition && local_output_deltas.unwrap().outputs_changed;- // An exact local delta is also an equality proof. Avoid walking both interned state- // chains after doing the more precise work needed for downstream propagation already.- let (continuation_changed, continuation_delta) = if old.state == new.state {- (false, None)- } else if can_derive_delta {- let delta = if used_sparse_transition && !sparse_has_local_output_delta {- delta_arena.persisting_only(entering_deltas.parent)- } else {- delta_arena.combine(entering_deltas.parent, local_output_deltas.unwrap().continuation)- };- let changed = delta_arena.changes_selected_state(delta, selection.unwrap());- (changed, changed.then_some(delta))- } else {- let changed = !self.selected_states_equal(old.state, new.state, selection);- // Without a routed selection nothing names the steps that moved, so name them here:- // the children can then rebase across the delta instead of recomputing under it.- let delta = (changed && selection.is_none() && evaluation.tree.first_element_child(node).is_some())- .then(|| self.state_delta_between(old.state, new.state, delta_arena));- (changed, delta)- };- let (right_changed, right_delta) = if old.right == new.right {- (false, None)- } else if can_derive_delta {- let delta = if used_sparse_transition && !sparse_has_local_output_delta {- delta_arena.persisting_only(entering_deltas.previous)- } else {- delta_arena.combine(entering_deltas.previous, local_output_deltas.unwrap().right)- };- let changed = delta_arena.changes_selected_state(delta, selection.unwrap());- (changed, changed.then_some(delta))- } else {- (!self.selected_states_equal(old.right, new.right, selection), None)- };- let old_matches = self.matches_of(old);- let new_matches = self.matches_of(new);- self.candidates = affected_candidates;- PrefixTransitionLookup::Known(PrefixDifference {- continuation_changed,- right_changed,- matches_changed: match selection {- Some(selection) => {- !selected_matches_equal(self.matches_in(old_matches), self.matches_in(new_matches), selection)- }- // Match sets are content-interned, so identity is content equality.- None => old_matches != new_matches,- },- arrived: false,- old_matches,- new_matches,- continuation_delta,- continuation_endpoints: (old.state, new.state),- right_delta,- })- }-- /// The exact signed difference between two interned states, as a delta whose endpoints name- /// both states.- fn state_delta_between(- &mut self,- old_state: u32,- new_state: u32,- arena: &mut PrefixDeltaArena,- ) -> PrefixStateDeltaID {- let mut old_steps = std::mem::take(&mut arena.scratch[4]);- let mut new_steps = std::mem::take(&mut arena.scratch[5]);- for scratch in &mut arena.scratch[..4] {- scratch.clear();- }- for (offset, collect_expiring) in [(0, false), (2, true)] {- old_steps.clear();- new_steps.clear();- match collect_expiring {- false => {- self.collect_persisting(old_state, &mut old_steps);- self.collect_persisting(new_state, &mut new_steps);- }- true => {- old_steps.extend_from_slice(self.expiring_in(old_state));- new_steps.extend_from_slice(self.expiring_in(new_state));- }- }- old_steps.sort_unstable();- new_steps.sort_unstable();- let (mut old_index, mut new_index) = (0, 0);- loop {- match (old_steps.get(old_index), new_steps.get(new_index)) {- (Some(&old), Some(&new)) if old == new => {- old_index += 1;- new_index += 1;- }- (Some(&old), Some(&new)) if old < new => {- arena.scratch[offset + 1].push(old);- old_index += 1;- }- (Some(_) | None, Some(&new)) => {- arena.scratch[offset].push(new);- new_index += 1;- }- (Some(&old), None) => {- arena.scratch[offset + 1].push(old);- old_index += 1;- }- (None, None) => break,- }- }- }- arena.scratch[4] = old_steps;- arena.scratch[5] = new_steps;- arena.append_scratch_delta(0)- }-- /// Rebase a node's retained transition across a parent-state delta none of whose steps can- /// match the node.- ///- /// A step that moved into or out of the entering state changes the node's outputs only by- /// matching there, and a removed step's predecessor matching there would re-admit it, so each- /// is evaluated against the node - by dispatch key first, then by its compound under the- /// node's retained positional bits. What remains is the old transition with the parent's new- /// state under it: the persisting additions the node made still hold, and so do its matches- /// and its rightward output.- #[allow(clippy::too_many_arguments)]- fn derive_dead_delta_transition(- &mut self,- scratch: &mut PrefixTransitionScratch,- effects: &mut PrefixEffects,- evaluation: &mut PrefixEvaluation<'_, '_>,- node: StyleNodeID,- row: MatchFactRow<'_>,- old: PrefixTransition,- old_entering: EnteringStates,- new_parent: u32,- delta: PrefixStateDeltaID,- arena: &mut PrefixDeltaArena,- counters: &Counters,- ) -> Option<PrefixDifference> {- let automaton = evaluation.automaton;- let is_document_root = evaluation.tree.parent(node).is_none();- let positional_bits = self.positional_bits_of(node);- let signed = arena.delta(delta);- let table = arena.key_table(delta, automaton);- let mut verdict: Option<bool> = Some(false);- row.facts.for_each_dispatch_probe(row.row, is_document_root, |key, _| {- if verdict != Some(false) {- return;- }- let first = table.partition_point(|&(candidate, _)| candidate < key);- for &(candidate, step) in &table[first..] {- if candidate != key {- break;- }- match evaluation.step_matches(node, positional_bits, step, counters) {- Ok(false) => {}- Ok(true) => {- verdict = Some(true);- return;- }- Err(_) => {- verdict = None;- return;- }- }- }- });- match verdict {- Some(false) => {}- Some(true) => {- counters.bump(Counter::PrefixDeadDeltaBailMatched);- return None;- }- None => return None,- }- let old_parent = old_entering.parent;- let new_state = if old.state == self.state_without_expiring(old_parent, counters) {- self.state_without_expiring(new_parent, counters)- } else {- // The node admitted steps of its own. They are exactly the persisting steps its state- // holds beyond the parent's, and they survive onto the parent's new state unless the- // delta now carries one of them from above, which only a full transition dedups.- let mut own = std::mem::take(&mut self.compare_left);- own.clear();- advance_epoch(&mut self.comparison_epoch, 1, &mut [&mut self.comparison_marks]);- let epoch = self.comparison_epoch;- let mut marks = std::mem::take(&mut self.comparison_marks);- marks.ensure_len(self.automaton_step_count);- let mut current = old_parent;- loop {- for &step in self.additions_in(current) {- marks[step.0 as usize] = epoch;- }- let base = self.states[current as usize].base;- if base == current {- break;- }- current = base;- }- current = old.state;- loop {- for &step in self.additions_in(current) {- if marks[step.0 as usize] != epoch {- own.push(step);- }- }- let base = self.states[current as usize].base;- if base == current {- break;- }- current = base;- }- self.comparison_marks = marks;- let carried_from_above = arena- .get(signed.persisting_additions)- .iter()- .any(|added| own.contains(added));- if carried_from_above {- own.clear();- self.compare_left = own;- counters.bump(Counter::PrefixDeadDeltaBailOwnAdditions);- return None;- }- automaton.sort_steps_by_dispatch_order(&mut own);- let own_hash = own.iter().fold(0_u64, |hash, &step| hash.wrapping_add(step_hash(step)));- let mut expiring = std::mem::take(&mut self.compare_right);- expiring.clear();- expiring.extend_from_slice(self.expiring_in(old.state));- let expiring_hash = self.states[old.state as usize].expiring_hash;- let state = self.intern_extended_state(new_parent, &own, own_hash, &expiring, expiring_hash, counters);- own.clear();- expiring.clear();- self.compare_left = own;- self.compare_right = expiring;- state- };- let new = PrefixTransition {- state: new_state,- right: old.right,- result: old.result,- };- let entering = EnteringStates {- parent: new_parent,- previous: old_entering.previous,- };- effects.writes.push(PrefixNodeWrite {- node,- transition: new,- entering,- positional_bits: None,- local_facts: None,- });- PrefixTransitionSurface {- states: self,- scratch,- effects,- }- .remember_transition(node, new);- if let Some(local_facts) = self.local_facts_of(node) {- scratch.memo.insert(- PrefixTransitionKey {- parent: new_parent,- previous: old_entering.previous,- local_facts,- is_document_root,- positional_bits,- },- new,- );- }- counters.bump(Counter::PrefixDeadDeltaTransitions);- let matches = self.matches_of(new);- let continuation_changed = old.state != new_state;- // The children see the same persisting delta; only its expiring part, which applied to- // this node alone, is shed.- let continuation_delta = continuation_changed.then(|| match arena.has_expiring_part(delta) {- true => arena.persisting_only(Some(delta)),- false => delta,- });- Some(PrefixDifference {- continuation_changed,- right_changed: false,- matches_changed: false,- arrived: false,- old_matches: matches,- new_matches: matches,- continuation_delta,- continuation_endpoints: (old.state, new_state),- right_delta: None,- })- }-- /// The state a node that admits nothing hands its children under `state`: the state itself- /// when it carries no expiring steps, its persisting-only form otherwise.- fn state_without_expiring(&mut self, state: u32, counters: &Counters) -> u32 {- match self.states[state as usize].expiring_len == 0 {- true => state,- false => self.descendant_only_state(state, counters),- }- }-- pub(super) fn complete_nodes_with_budget(- &mut self,- scratch: &mut PrefixTransitionScratch,- effects: &mut PrefixEffects,- evaluation: &mut PrefixEvaluation<'_, '_>,- nodes: impl Iterator<Item = StyleNodeID>,- completion_budget: usize,- counters: &Counters,- ) -> bool {- let mut completions = 0;- for node in nodes {- // A relation answer already provides the complete prefix result. Building a- // scalar transition for the same node duplicates work and retained state.- if scratch.by_node.contains_key(&node) || self.retained_matches_for(node).is_some() {- continue;- }- if completions == completion_budget {- self.complete = false;- return false;- }- match self.transition_for(scratch, effects, evaluation, node, counters) {- PrefixTransitionLookup::Known(_) => {}- PrefixTransitionLookup::Missing(_) => {- self.complete = false;- return false;- }- }- completions += 1;- }- self.complete = true;- true- }-- fn rebuild_interners(&mut self) {- if self.states.len() > 1 && self.states_by_hash.is_empty() {- for state in 1..self.states.len() {- let contents = &self.states[state];- let key = state_content_key(- contents.descendant_len,- contents.descendant_hash,- contents.expiring_len,- contents.expiring_hash,- );- self.remember_state(key, state as u32);- }- }- if self.match_offsets.len() > 2 && self.match_sets_by_hash.is_empty() {- for matches in 1..self.match_offsets.len() - 1 {- let identity = PrefixMatchSetID(matches as u32);- let hash = super::intern_table::content_hash(self.matches_in(identity));- self.match_sets_by_hash.insert_identity(hash, identity);- }- }- if self.truth_offsets.len() > 2 && self.truth_sets_by_hash.is_empty() {- for truth in 1..self.truth_offsets.len() - 1 {- let identity = PrefixTruthSetID(truth as u32);- let hash = super::intern_table::content_hash(self.truth_in(identity));- self.truth_sets_by_hash.insert_identity(hash, identity);- }- }- }-- fn transition_for(- &mut self,- scratch: &mut PrefixTransitionScratch,- effects: &mut PrefixEffects,- evaluation: &mut PrefixEvaluation<'_, '_>,- node: StyleNodeID,- counters: &Counters,- ) -> PrefixTransitionLookup<PrefixTransition> {- transition_for(- &mut PrefixTransitionSurface {- states: self,- scratch,- effects,- },- evaluation,- node,- counters,- )- }-- #[allow(clippy::too_many_arguments)]- fn transition(- &mut self,- evaluation: &mut PrefixEvaluation<'_, '_>,- entering: EnteringStates,- row: MatchFactRow<'_>,- node: StyleNodeID,- is_document_root: bool,- positional_bits: u32,- counters: &Counters,- ) -> PrefixTransitionLookup<PrefixTransition> {- let automaton = evaluation.automaton;- if !self.automaton_statistics_recorded {- self.automaton_step_count = automaton.steps.len();- self.automaton_statistics_recorded = true;- }- self.begin_transition(automaton);- self.enter_states(entering);-- row.facts.for_each_dispatch_probe(row.row, is_document_root, |key, _| {- self.offer_key(automaton, entering, key, evaluation.selection);- });-- for candidate_index in 0..self.candidates.len() {- let step_id = self.candidates[candidate_index];- let step = &automaton.steps[step_id.0 as usize];- let compound_index = step.compound.0 as usize;- let matches = if self.compound_epoch[compound_index] == self.epoch {- self.compound_answer[compound_index]- } else {- let compound = &automaton.compounds[compound_index];- let matches =- match &compound.predicate {- PrefixPredicate::Features {- feature_start,- feature_len,- required_positional_bits,- } => {- (positional_bits & required_positional_bits) == *required_positional_bits- && automaton- .features_for(*feature_start, *feature_len)- .all(|feature| matches_feature(row, feature))- }- PrefixPredicate::Program { program, local, .. } => match evaluation- .evaluator- .matches_prefix_local(*program, evaluation.programs.get(*program), *local, node, counters)- {- Ok(matches) => matches,- Err(incomplete) => {- return PrefixTransitionLookup::Missing(PrefixTransitionGap::Incomplete(incomplete));- }- },- };- self.compound_epoch[compound_index] = self.epoch;- self.compound_answer[compound_index] = matches;- counters.bump(Counter::PrefixCompoundsEvaluated);- matches- };- if !matches {- continue;- }- if matches!(- automaton.compounds[compound_index].predicate,- PrefixPredicate::Program { .. }- ) {- self.output_matched_steps.push(step_id);- }- for output in automaton.outputs_for(step) {- match output.kind {- PrefixOutputKind::UniqueTerminal | PrefixOutputKind::SharedTerminal => {- let terminal = EntryID(output.target);- if evaluation- .selection- .is_none_or(|selection| selection.contains_terminal(terminal))- {- self.admit_match(terminal);- }- }- kind => {- let successor = PrefixStepID(output.target);- if evaluation- .selection- .is_some_and(|selection| !selection.contains_step(successor))- {- continue;- }- let axis = match kind {- PrefixOutputKind::Child => SelectorPrefixAxis::Child,- PrefixOutputKind::Descendant => SelectorPrefixAxis::Descendant,- PrefixOutputKind::NextSibling => SelectorPrefixAxis::NextSibling,- PrefixOutputKind::FollowingSibling => SelectorPrefixAxis::FollowingSibling,- PrefixOutputKind::UniqueTerminal | PrefixOutputKind::SharedTerminal => unreachable!(),- };- self.admit_successor(successor, axis);- }- }- }- }-- if !self.output_matches.is_sorted() {- self.output_matches.sort_unstable();- }- if !self.output_matched_steps.is_sorted() {- self.output_matched_steps.sort_unstable();- }- let state = self.intern_transition_state(automaton, entering.parent, counters);- let right = self.intern_right_transition_state(automaton, entering.previous, counters);- let matches = self.intern_output_matches();- let truth = self.intern_output_truth();- let result = self.intern_result(matches, truth);- PrefixTransitionLookup::Known(PrefixTransition { state, right, result })- }-- fn begin_transition(&mut self, automaton: &PrefixAutomaton) {- let step_count = automaton.steps.len();- let compound_count = automaton.compounds.len();- // NB: Each scratch column carries its own length gate. Retention trims every column to- // empty, but comparison and sparse-delta paths regrow candidate_epoch on their own,- // so a shared gate on candidate_epoch alone would leave the sibling columns empty- // and the persisting-output walk indexing into them out of bounds.- self.candidate_epoch.ensure_len(step_count);- self.output_epoch.ensure_len(step_count);- self.parent_persisting_epoch.ensure_len(step_count);- self.previous_persisting_epoch.ensure_len(step_count);- self.compound_epoch.ensure_len(compound_count);- if self.compound_answer.len() < compound_count {- self.compound_answer.resize(compound_count, false);- }- advance_epoch(- &mut self.epoch,- 1,- &mut [- &mut self.candidate_epoch,- &mut self.compound_epoch,- &mut self.output_epoch,- &mut self.match_epoch,- &mut self.parent_persisting_epoch,- &mut self.previous_persisting_epoch,- ],- );- self.candidates.clear();- self.output_matches.clear();- self.output_matched_steps.clear();- self.new_descendant.clear();- self.new_child.clear();- self.new_following.clear();- self.new_adjacent.clear();- self.new_descendant_hash = 0;- self.new_child_hash = 0;- self.new_following_hash = 0;- self.new_adjacent_hash = 0;- }-- /// Mark both entering states' persisting membership so admissions dedup in O(1).- fn enter_states(&mut self, entering: EnteringStates) {- let mut marks = std::mem::take(&mut self.parent_persisting_epoch);- self.enter_state(entering.parent, &mut marks);- self.parent_persisting_epoch = marks;- let mut marks = std::mem::take(&mut self.previous_persisting_epoch);- self.enter_state(entering.previous, &mut marks);- self.previous_persisting_epoch = marks;- }-- fn enter_state(&self, state: u32, persisting_marks: &mut [u32]) {- let mut current = state;- loop {- for &step in self.additions_in(current) {- persisting_marks[step.0 as usize] = self.epoch;- }- let base = self.states[current as usize].base;- if base == current {- break;- }- current = base;- }- }-- /// Offer every root step dispatching under one of the row's keys. Buckets hold only root- /// steps, which are enabled unconditionally; continuation steps are candidates through the- /// parent state's active set instead.- fn offer_key(- &mut self,- automaton: &PrefixAutomaton,- entering: EnteringStates,- key: DispatchKey,- selection: Option<&PrefixSelection>,- ) {- let Some(bucket) = automaton.bucket(key) else {- return;- };- for &step in bucket.root_steps.as_slice() {- let index = step.0 as usize;- if selection.is_some_and(|selection| !selection.contains_step(step)) {- continue;- }- if self.candidate_epoch[index] != self.epoch {- self.candidate_epoch[index] = self.epoch;- self.candidates.push(step);- }- }- if entering.parent != 0 {- self.offer_state_range(entering.parent, bucket.first_step, bucket.end_step, selection);- }- if entering.previous != 0 && entering.previous != entering.parent {- self.offer_state_range(entering.previous, bucket.first_step, bucket.end_step, selection);- }- }-- fn offer_state_range(&mut self, state: u32, first_step: u32, end_step: u32, selection: Option<&PrefixSelection>) {- let contents = &self.states[state as usize];- self.offer_step_range(- contents.payload_start as usize + contents.additions_len as usize,- contents.expiring_len,- (first_step, end_step),- selection,- );- let mut current = state;- loop {- let contents = &self.states[current as usize];- let payload_start = contents.payload_start;- let additions_len = contents.additions_len;- let base = contents.base;- self.offer_step_range(payload_start as usize, additions_len, (first_step, end_step), selection);- if base == current {- break;- }- current = base;- }- }-- fn offer_step_range(- &mut self,- payload_start: usize,- len: u32,- dispatch_range: (u32, u32),- selection: Option<&PrefixSelection>,- ) {- // SAFETY: Callers pass a range from an interned state's initialized payload.- let steps = unsafe {- ak::slice_from_raw_parts(- self.delta_steps.as_ptr().add(payload_start).cast::<PrefixStepID>(),- len as usize,- )- };- let start = steps.partition_point(|step| step.0 < dispatch_range.0);- let end = steps[start..].partition_point(|step| step.0 < dispatch_range.1) + start;- for &step in &steps[start..end] {- if selection.is_some_and(|selection| !selection.contains_step(step)) {- continue;- }- let candidate = &mut self.candidate_epoch[step.0 as usize];- if *candidate != self.epoch {- *candidate = self.epoch;- self.candidates.push(step);- }- }- }-- fn admit_successor(&mut self, step: PrefixStepID, axis: SelectorPrefixAxis) {- let seen = &mut self.output_epoch[step.0 as usize];- if *seen == self.epoch {- return;- }- *seen = self.epoch;- let hash = step_hash(step);- match axis {- SelectorPrefixAxis::Child => {- self.new_child.push(step);- self.new_child_hash = self.new_child_hash.wrapping_add(hash as u32);- }- SelectorPrefixAxis::Descendant => {- self.new_descendant.push(step);- self.new_descendant_hash = self.new_descendant_hash.wrapping_add(hash);- }- SelectorPrefixAxis::NextSibling => {- self.new_adjacent.push(step);- self.new_adjacent_hash = self.new_adjacent_hash.wrapping_add(hash as u32);- }- SelectorPrefixAxis::FollowingSibling => {- self.new_following.push(step);- self.new_following_hash = self.new_following_hash.wrapping_add(hash);- }- SelectorPrefixAxis::Root => unreachable!("root steps are dispatched, never admitted"),- }- }-- fn admit_match(&mut self, entry: EntryID) {- let index = entry.0 as usize;- if self.match_epoch.mark(index, self.epoch) {- self.output_matches.push(entry);- }- }-- /// Intern the transition's downward output state from the parent state and the new- /// down-axis admissions.- fn intern_transition_state(&mut self, automaton: &PrefixAutomaton, parent_state: u32, counters: &Counters) -> u32 {- let mut additions = std::mem::take(&mut self.new_descendant);- let mut additions_hash = self.new_descendant_hash;- additions.retain(|step| {- if self.parent_persisting_epoch[step.0 as usize] != self.epoch {- true- } else {- additions_hash = additions_hash.wrapping_sub(step_hash(*step));- false- }- });- automaton.sort_steps_by_dispatch_order(&mut additions);- let mut expiring = std::mem::take(&mut self.new_child);- automaton.sort_steps_by_dispatch_order(&mut expiring);- let state = self.intern_extended_state(- parent_state,- &additions,- additions_hash,- &expiring,- self.new_child_hash,- counters,- );- self.new_descendant = additions;- self.new_child = expiring;- state- }-- /// Intern the transition's rightward output state from the previous sibling's rightward- /// state and the new sibling-axis admissions.- fn intern_right_transition_state(- &mut self,- automaton: &PrefixAutomaton,- previous_state: u32,- counters: &Counters,- ) -> u32 {- let mut additions = std::mem::take(&mut self.new_following);- let mut additions_hash = self.new_following_hash;- additions.retain(|step| {- if self.previous_persisting_epoch[step.0 as usize] != self.epoch {- true- } else {- additions_hash = additions_hash.wrapping_sub(step_hash(*step));- false- }- });- automaton.sort_steps_by_dispatch_order(&mut additions);- let mut expiring = std::mem::take(&mut self.new_adjacent);- automaton.sort_steps_by_dispatch_order(&mut expiring);- let state = self.intern_extended_state(- previous_state,- &additions,- additions_hash,- &expiring,- self.new_adjacent_hash,- counters,- );- self.new_following = additions;- self.new_adjacent = expiring;- state- }-- /// Intern the state extending `base_state` with the given sorted persisting additions and- /// sorted expiring steps.- ///- /// The additions were deduplicated against the base's persisting set through the entering- /// marks, so the state stores exactly its delta and extends the order-independent persisting- /// hash by exactly the genuinely new steps. A transition that admitted nothing keeps the- /// base's persisting part by identity, which is the base itself unless it carried expiring- /// steps.- fn intern_extended_state(- &mut self,- base_state: u32,- additions: &[PrefixStepID],- additions_hash: u64,- expiring: &[PrefixStepID],- expiring_hash: u32,- counters: &Counters,- ) -> u32 {- if additions.is_empty() && expiring.is_empty() {- if self.states[base_state as usize].expiring_len == 0 {- return base_state;- }- return self.descendant_only_state(base_state, counters);- }- let additions_len = u32::try_from(additions.len()).expect("selector prefix state payload overflow");- let expiring_len = u32::try_from(expiring.len()).expect("selector prefix state payload overflow");- let base = &self.states[base_state as usize];- let descendant_len = base.descendant_len + additions_len;- let descendant_hash = base.descendant_hash.wrapping_add(additions_hash);- let key = state_content_key(descendant_len, descendant_hash, expiring_len, expiring_hash);- let state = u32::try_from(self.states.len()).expect("selector prefix state space exhausted");- let payload_start = u32::try_from(self.delta_steps.len()).expect("selector prefix state payload overflow");- self.append_delta_steps(additions);- self.append_delta_steps(expiring);- self.states.push(PrefixState {- base: base_state,- payload_start,- additions_len,- expiring_len,- descendant_len,- descendant_hash,- expiring_hash,- });- self.descendant_only.push(match expiring.is_empty() {- true => state,- false => UNKNOWN_STATE,- });- if let Some(candidate) = self.find_equal_state(key, state) {- self.states.pop();- self.descendant_only.pop();- self.delta_steps.truncate(payload_start as usize);- return candidate;- }- self.remember_state(key, state);- state- }-- fn append_delta_steps(&mut self, steps: &[PrefixStepID]) {- self.delta_steps- .extend(steps.iter().map(|&step| std::mem::MaybeUninit::new(step)));- }-- fn skip_delta_steps(&mut self, additions_len: usize, expiring_len: usize) {- for len in [additions_len, expiring_len] {- self.delta_steps.reserve(len);- let new_len = self- .delta_steps- .len()- .checked_add(len)- .expect("selector prefix state payload overflow");- // SAFETY: `MaybeUninit<PrefixStepID>` permits uninitialized elements. No state- // references this skipped range; a sparse rebase shares its source payload.- unsafe { self.delta_steps.set_len(new_len) };- }- }-- fn rebase_unchanged_local_payload(- &mut self,- source_state: u32,- old_base_state: u32,- new_base_state: u32,- counters: &Counters,- ) -> Option<u32> {- if old_base_state == new_base_state {- return Some(source_state);- }- if source_state == old_base_state {- return Some(match self.states[new_base_state as usize].expiring_len == 0 {- true => new_base_state,- false => self.descendant_only_state(new_base_state, counters),- });- }- let source = &self.states[source_state as usize];- if source.base != old_base_state {- return None;- }- let additions_len = source.additions_len;- let expiring_len = source.expiring_len;- let payload_start = source.payload_start;- let expiring_hash = source.expiring_hash;- let additions_hash = source- .descendant_hash- .wrapping_sub(self.states[old_base_state as usize].descendant_hash);- let new_base = &self.states[new_base_state as usize];- let descendant_len = new_base- .descendant_len- .checked_add(additions_len)- .expect("selector prefix state payload overflow");- let descendant_hash = new_base.descendant_hash.wrapping_add(additions_hash);- let key = state_content_key(descendant_len, descendant_hash, expiring_len, expiring_hash);- let state = u32::try_from(self.states.len()).expect("selector prefix state space exhausted");- let delta_steps_len = self.delta_steps.len();- self.skip_delta_steps(additions_len as usize, expiring_len as usize);- self.states.push(PrefixState {- base: new_base_state,- payload_start,- additions_len,- expiring_len,- descendant_len,- descendant_hash,- expiring_hash,- });- self.descendant_only.push(match expiring_len == 0 {- true => state,- false => UNKNOWN_STATE,- });- if let Some(candidate) = self.find_equal_state(key, state) {- self.states.pop();- self.descendant_only.pop();- self.delta_steps.truncate(delta_steps_len);- return Some(candidate);- }- self.remember_state(key, state);- Some(state)- }-- /// The interned state holding exactly `state`'s persisting part, memoized per state.- fn descendant_only_state(&mut self, state: u32, counters: &Counters) -> u32 {- let known = self.descendant_only[state as usize];- if known != UNKNOWN_STATE {- return known;- }- let mut additions = std::mem::take(&mut self.compare_left);- additions.clear();- additions.extend_from_slice(self.additions_in(state));- let base = self.states[state as usize].base;- let additions_hash = self.states[state as usize]- .descendant_hash- .wrapping_sub(self.states[base as usize].descendant_hash);- let interned = self.intern_extended_state(base, &additions, additions_hash, &[], 0, counters);- additions.clear();- self.compare_left = additions;- self.descendant_only[state as usize] = interned;- interned- }-- fn intern_output_matches(&mut self) -> PrefixMatchSetID {- if self.output_matches.is_empty() {- return PrefixMatchSetID(0);- }- let hash = super::intern_table::content_hash(&self.output_matches);- if let Some(candidate) = self- .match_sets_by_hash- .find(hash, |candidate, ()| self.matches_in(candidate) == self.output_matches)- {- return candidate;- }-- let matches = PrefixMatchSetID(- u32::try_from(self.match_offsets.len() - 1).expect("selector prefix match-set space exhausted"),- );- self.match_entries.extend_from_slice(&self.output_matches);- self.match_offsets- .push(u32::try_from(self.match_entries.len()).expect("selector prefix match-set payload overflow"));- self.match_sets_by_hash.insert_identity(hash, matches);- matches- }-- fn intern_output_truth(&mut self) -> PrefixTruthSetID {- if self.output_matched_steps.is_empty() {- return PrefixTruthSetID(0);- }- let hash = super::intern_table::content_hash(&self.output_matched_steps);- if let Some(candidate) = self.truth_sets_by_hash.find(hash, |candidate, ()| {- self.truth_in(candidate) == self.output_matched_steps- }) {- return candidate;- }-- let truth = PrefixTruthSetID(- u32::try_from(self.truth_offsets.len() - 1).expect("selector prefix truth-set space exhausted"),- );- self.truth_steps.extend_from_slice(&self.output_matched_steps);- self.truth_offsets- .push(u32::try_from(self.truth_steps.len()).expect("selector prefix truth-set payload overflow"));- self.truth_sets_by_hash.insert_identity(hash, truth);- truth- }-- fn intern_result(&mut self, matches: PrefixMatchSetID, truth: PrefixTruthSetID) -> PrefixResultID {- if matches == PrefixMatchSetID(0) && truth == PrefixTruthSetID(0) {- return PrefixResultID(0);- }- let hash = super::intern_table::content_hash((matches, truth));- if let Some(result) = self.result_ids.find(hash, |_result, candidate| {- candidate.matches == matches && candidate.truth == truth- }) {- return result;- }- let result = PrefixResultID(u32::try_from(self.results.len()).expect("prefix result space exhausted"));- let payload = PrefixResult { matches, truth };- self.results.push(payload);- self.result_ids.insert(hash, result, payload);- result- }-- fn compact_interned_states(&mut self) {- let mut live_states = vec![false; self.states.len()];- live_states[0] = true;- for transition in self- .transition_by_element- .iter()- .filter(|transition| transition.state != UNKNOWN_STATE)- {- for mut state in [transition.state, transition.right] {- loop {- if live_states[state as usize] {- break;- }- live_states[state as usize] = true;- let base = self.states[state as usize].base;- if base == state {- break;- }- state = base;- }- }- }-- let mut state_remap = vec![UNKNOWN_STATE; self.states.len()];- let mut states = Vec::with_capacity(live_states.iter().filter(|&&live| live).count());- let mut delta_steps = Vec::new();- for (old_index, live) in live_states.iter().copied().enumerate() {- if !live {- continue;- }- let old = &self.states[old_index];- let new_index = u32::try_from(states.len()).expect("selector prefix state space exhausted");- state_remap[old_index] = new_index;- let payload_start = u32::try_from(delta_steps.len()).expect("selector prefix state payload overflow");- delta_steps.extend(- self.additions_in(old_index as u32)- .iter()- .map(|&step| std::mem::MaybeUninit::new(step)),- );- delta_steps.extend(- self.expiring_in(old_index as u32)- .iter()- .map(|&step| std::mem::MaybeUninit::new(step)),- );- states.push(PrefixState {- base: state_remap[old.base as usize],- payload_start,- additions_len: old.additions_len,- expiring_len: old.expiring_len,- descendant_len: old.descendant_len,- descendant_hash: old.descendant_hash,- expiring_hash: old.expiring_hash,- });- }-- for transition in self- .transition_by_element- .iter_mut()- .filter(|transition| transition.state != UNKNOWN_STATE)- {- transition.state = state_remap[transition.state as usize];- transition.right = state_remap[transition.right as usize];- }- let mut descendant_only = vec![UNKNOWN_STATE; states.len()];- for (old_index, &new_index) in state_remap.iter().enumerate() {- if new_index == UNKNOWN_STATE {- continue;- }- let old_descendant = self.descendant_only[old_index];- if old_descendant != UNKNOWN_STATE {- descendant_only[new_index as usize] = state_remap[old_descendant as usize];- }- }-- self.states = states;- self.delta_steps = delta_steps;- self.descendant_only = descendant_only;- self.states_by_hash = HashMap::default();- self.states_by_hash_collision_bytes = 0;- for entering in self.entering_by_element.iter_mut() {- if entering.parent == UNKNOWN_STATE {- continue;- }- let Some(&parent) = state_remap.get(entering.parent as usize) else {- *entering = UNKNOWN_ENTERING_STATES;- continue;- };- let Some(&previous) = state_remap.get(entering.previous as usize) else {- *entering = UNKNOWN_ENTERING_STATES;- continue;- };- if parent == UNKNOWN_STATE || previous == UNKNOWN_STATE {- *entering = UNKNOWN_ENTERING_STATES;- continue;- }- entering.parent = parent;- entering.previous = previous;- }- // The states are renumbered, so this is another arena as far as anything that memoized- // answers by state index is concerned: a transition context prepared against the old- // numbering, which a cold matching traversal keeps across flushes, starts over.- self.identity = next_prefix_states_identity();- }-- fn interned_working_bytes(&self) -> u64 {- (self.states.len() * size_of::<PrefixState>() + self.delta_steps.len() * size_of::<PrefixStepID>()) as u64- }-- /// Shed unreachable interned identities and allocation slack before the working form is- /// retained. Only per-element transitions cross this boundary; traversal memos- /// and completed-answer keys are batch-local, so every remapped identity stays internal.- fn trim_for_retention(&mut self) {- let working_bytes = self.interned_working_bytes();- if self.last_compacted_working_bytes == 0- || working_bytes > self.last_compacted_working_bytes.saturating_mul(3) / 2- {- self.compact_interned_states();- self.last_compacted_working_bytes = self.interned_working_bytes();- }- // Retained state becomes scratch again before it can be mutated. Preserve the allocation- // slack of its working vectors across that cycle: trimming them here makes the next flush- // immediately allocate the same capacity again. Batch-local workspaces below still give- // their complete allocations back because none of their contents cross this boundary.- self.candidate_epoch = EpochColumn::default();- self.comparison_marks = EpochColumn::default();- self.compound_epoch = EpochColumn::default();- self.compound_answer = Vec::new();- self.output_epoch = EpochColumn::default();- self.match_epoch = EpochColumn::default();- self.parent_persisting_epoch = EpochColumn::default();- self.previous_persisting_epoch = EpochColumn::default();- self.candidates = Vec::new();- self.compare_left = Vec::new();- self.compare_right = Vec::new();- self.output_matches = Vec::new();- self.output_matched_steps = Vec::new();- self.new_descendant = Vec::new();- self.new_child = Vec::new();- self.new_following = Vec::new();- self.new_adjacent = Vec::new();- }-}--impl PrefixTransitionScratch {- fn ensure_local_fact_identity(- &mut self,- states: &mut PrefixStates,- automaton: &PrefixAutomaton,- facts: &StyleNodeFacts,- node: StyleNodeID,- counters: &Counters,- ) -> u32 {- let row = facts.row_of(node).expect("prepared fact row");- if let Some(&cached) = self.local_facts_by_row.get(&row) {- return cached;- }- let local_facts_changed = self- .composite_local_fact_changes- .as_ref()- .is_some_and(|changed| changed.binary_search(&node).is_ok());- let retained = (!local_facts_changed).then(|| states.local_facts_of(node)).flatten();- let identity = retained.unwrap_or_else(|| {- if self.composite_local_fact_changes.is_some() {- // Composite fact views retain the existing conservative unique cohorts.- counters.bump(Counter::PrefixLocalFactIdentityMisses);- states.local_fact_interner.mint_identity()- } else {- states.local_fact_interner.intern(- &mut self.local_fact_representatives,- facts,- row,- &automaton.local_fact_dependencies,- counters,- )- }- });- self.local_facts_by_row.insert(row, identity);- identity- }-- /// Drop every row-indexed answer the moment the batch's row space moves.- ///- /// Local-fact representatives hold raw row indices. A batch rebuild renumbers rows, so- /// holding them across generations reads the wrong element's facts, or past the end of- /// the batch. Appending keeps the generation and the held rows.- pub(super) fn prepare_rows(&mut self, generation: u64) {- if self.facts_generation != generation || generation == 0 {- self.facts_generation = generation;- self.local_facts_by_row.clear();- self.local_fact_representatives = Default::default();- }- }-}--impl PrefixEffects {}--impl PrefixStates {- pub(super) fn install_prefix_effects(&mut self, effects: &mut PrefixEffects) {- for write in effects.writes.drain(..) {- self.set_transition(write.node, write.transition);- self.set_entering(write.node, write.entering);- if let Some(identity) = write.local_facts {- self.set_local_facts(write.node, identity);- }- if let Some(bits) = write.positional_bits {- self.set_positional_bits(write.node, bits);- }- }- }-}--impl PrefixTransitionSurface<'_> {- fn ancestor_chain_is_empty(&self) -> bool {- self.scratch.ancestor_chain.is_empty()- }- fn clear_ancestor_chain(&mut self) {- self.scratch.ancestor_chain.clear();- }- fn push_ancestor(&mut self, node: StyleNodeID) {- self.scratch.ancestor_chain.push(node);- }- fn pop_ancestor(&mut self) -> Option<StyleNodeID> {- self.scratch.ancestor_chain.pop()- }-- fn known_transition(- &self,- evaluation: &mut PrefixEvaluation<'_, '_>,- node: StyleNodeID,- ) -> Option<PrefixTransition> {- if !evaluation.facts_are_composite() {- evaluation.facts.row_of(node)?;- }- self.scratch- .by_node- .get(&node)- .copied()- .or_else(|| match self.states.transition_of(node) {- PrefixTransitionLookup::Known(known) => Some(known),- PrefixTransitionLookup::Missing(_) => None,- })- }-- fn remember_transition(&mut self, node: StyleNodeID, transition: PrefixTransition) {- self.scratch.by_node.insert(node, transition);- }-- fn remember_inputs(- &mut self,- evaluation: &PrefixEvaluation<'_, '_>,- node: StyleNodeID,- transition: PrefixTransition,- inputs: TransitionInputs,- ) {- // NB: The dependency walk produces ancestors before descendants. Preserve that- // order when installing ancestor-closed retained coverage after the context.- self.effects.writes.push(PrefixNodeWrite {- node,- transition,- entering: inputs.entering,- positional_bits: (!evaluation.automaton.positional_tests().is_empty()).then_some(inputs.positional_bits),- local_facts: Some(inputs.local_facts),- });- }-- fn transition_from_inputs(- &mut self,- evaluation: &mut PrefixEvaluation<'_, '_>,- node: StyleNodeID,- row: MatchFactRow<'_>,- inputs: TransitionInputs,- counters: &Counters,- ) -> PrefixTransitionLookup<(PrefixTransition, PrefixTransitionOrigin)> {- let key = PrefixTransitionKey {- parent: inputs.entering.parent,- previous: inputs.entering.previous,- local_facts: inputs.local_facts,- is_document_root: evaluation.tree.parent(node).is_none(),- positional_bits: inputs.positional_bits,- };- if let Some(transition) = self.scratch.memo.get(&key).copied() {- counters.bump(Counter::PrefixTransitionMemoHits);- self.remember_inputs(evaluation, node, transition, inputs);- return PrefixTransitionLookup::Known((transition, PrefixTransitionOrigin::Memoized));- }- counters.bump(Counter::PrefixTransitionMemoMisses);- let transition = self.states.transition(- evaluation,- inputs.entering,- row,- node,- key.is_document_root,- key.positional_bits,- counters,- );- let transition = match transition {- PrefixTransitionLookup::Known(transition) => transition,- PrefixTransitionLookup::Missing(gap) => return PrefixTransitionLookup::Missing(gap),- };- self.scratch.memo.insert(key, transition);- self.remember_inputs(evaluation, node, transition, inputs);- PrefixTransitionLookup::Known((transition, PrefixTransitionOrigin::Computed))- }-}--/// Walk the dependencies of one transition in the retained cache. Sibling-free automata use the-/// same walk with the previous-sibling state pinned to zero.-fn transition_for(- surface: &mut PrefixTransitionSurface<'_>,- evaluation: &mut PrefixEvaluation<'_, '_>,- node: StyleNodeID,- counters: &Counters,-) -> PrefixTransitionLookup<PrefixTransition> {- let has_sibling_steps = evaluation.automaton.has_sibling_steps();- surface.clear_ancestor_chain();- let mut current = node;- loop {- if let Err(incomplete) = evaluation.row_of(current) {- return PrefixTransitionLookup::Missing(PrefixTransitionGap::Incomplete(incomplete));- }- if let Some(known) = surface.known_transition(evaluation, current) {- if surface.ancestor_chain_is_empty() {- return PrefixTransitionLookup::Known(known);- }- break;- }- surface.push_ancestor(current);- if has_sibling_steps && let Some(previous) = evaluation.tree.previous_element_sibling(current) {- current = previous;- continue;- }- let Some(parent) = evaluation.tree.parent(current) else {- break;- };- if Some(parent) == evaluation.shadow_root {- break;- }- current = parent;- }-- // NB: Observe whether this ask can use completed selector-axis inputs without- // producing any ancestor or preceding-sibling transition first.- counters.bump(Counter::PrefixTransitionInputAsks);- if surface.scratch.ancestor_chain.len() == 1 {- counters.bump(Counter::PrefixTransitionInputsReady);- }- let mut result = UNKNOWN_TRANSITION;- while let Some(node) = surface.pop_ancestor() {- let row = match evaluation.row_of(node) {- Ok(row) => row,- Err(incomplete) => {- return PrefixTransitionLookup::Missing(PrefixTransitionGap::Incomplete(incomplete));- }- };- let parent_state = match evaluation.tree.parent(node) {- Some(parent) if Some(parent) != evaluation.shadow_root => {- match surface.known_transition(evaluation, parent) {- Some(transition) => transition.state,- None => return PrefixTransitionLookup::Missing(PrefixTransitionGap::MissingTransition(parent)),- }- }- Some(_) | None => 0,- };- let previous_state = if has_sibling_steps {- match evaluation.tree.previous_element_sibling(node) {- Some(previous) => match surface.known_transition(evaluation, previous) {- Some(transition) => transition.right,- None => {- return PrefixTransitionLookup::Missing(PrefixTransitionGap::MissingTransition(previous));- }- },- None => 0,- }- } else {- 0- };- let local_facts = surface.scratch.ensure_local_fact_identity(- surface.states,- evaluation.automaton,- evaluation.facts,- node,- counters,- );- let positional_bits = match evaluation.positional_bits(node, counters) {- Ok(bits) => bits,- Err(incomplete) => return PrefixTransitionLookup::Missing(PrefixTransitionGap::Incomplete(incomplete)),- };- result = match surface.transition_from_inputs(- evaluation,- node,- row,- TransitionInputs {- entering: EnteringStates {- parent: parent_state,- previous: previous_state,- },- local_facts,- positional_bits,- },- counters,- ) {- PrefixTransitionLookup::Known((transition, _)) => transition,- PrefixTransitionLookup::Missing(gap) => return PrefixTransitionLookup::Missing(gap),- };- surface.remember_transition(node, result);- }- PrefixTransitionLookup::Known(result)-}--fn selected_matches_equal(left: &[EntryID], right: &[EntryID], selection: &PrefixSelection) -> bool {- left.iter()- .copied()- .filter(|&entry| selection.contains_terminal(entry))- .eq(right- .iter()- .copied()- .filter(|&entry| selection.contains_terminal(entry)))-}--/// Prefix states shared by every element ask in one synchronous matching traversal.-///-/// The delta representation keeps the working form small enough to retain outright, so there is-/// no compact retained encoding. Retention keeps the same working form.-pub(super) struct PrefixStateCache {- by_program: Column<Option<Box<PrefixStates>>>,- lifecycle: PrefixStateCacheLifecycle,-}--#[derive(Clone, Copy)]-enum PrefixStateCacheCoverage {- Full,- Sparse,-}--#[derive(Clone, Copy)]-enum PrefixStateCacheLifecycle {- Scratch(PrefixStateCacheCoverage),- Retained(PrefixStateCacheCoverage),- CurrentScratch(PrefixStateCacheCoverage),- CurrentRetained(PrefixStateCacheCoverage),-}--impl PrefixStateCacheLifecycle {- fn coverage(self) -> PrefixStateCacheCoverage {- match self {- Self::Scratch(coverage)- | Self::Retained(coverage)- | Self::CurrentScratch(coverage)- | Self::CurrentRetained(coverage) => coverage,- }- }-- fn is_retained(self) -> bool {- matches!(self, Self::Retained(_) | Self::CurrentRetained(_))- }-- fn is_current(self) -> bool {- matches!(self, Self::CurrentScratch(_) | Self::CurrentRetained(_))- }-}--impl Default for PrefixStateCache {- fn default() -> Self {- Self {- by_program: Column::default(),-- lifecycle: PrefixStateCacheLifecycle::Scratch(PrefixStateCacheCoverage::Full),- }- }-}--#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub(super) enum PrefixStateCacheGap {- MissingProgram(ScopeProgramID),-}--impl PrefixStateCache {- pub(super) fn has_relation(&self) -> bool {- self.by_program.iter().flatten().any(|states| states.relation.is_some())- }-- /// Whether a retained relation still holds any of `nodes` as a live node.- pub(super) fn relation_holds_any(&self, nodes: &[StyleNodeID]) -> bool {- self.by_program- .iter()- .flatten()- .filter_map(|states| states.relation.as_deref())- .any(|relation| nodes.iter().any(|&node| relation.holds(node)))- }-- pub(super) fn lookup(&self, program: ScopeProgramID) -> Lookup<&PrefixStates, PrefixStateCacheGap> {- match self.by_program.get(program.0 as usize).and_then(Option::as_deref) {- Some(states) => Lookup::Known(states),- None => Lookup::Missing(PrefixStateCacheGap::MissingProgram(program)),- }- }-- pub(super) fn prepare_program(&mut self, program: ScopeProgramID) -> &mut PrefixStates {- self.by_program- .entry(program.0 as usize)- .get_or_insert_with(|| Box::new(PrefixStates::new()))- }-- pub(super) fn lookup_mut(&mut self, program: ScopeProgramID) -> Lookup<&mut PrefixStates, PrefixStateCacheGap> {- match self.by_program.get_mut(program.0 as usize).and_then(Option::as_mut) {- Some(states) => Lookup::Known(states),- None => Lookup::Missing(PrefixStateCacheGap::MissingProgram(program)),- }- }-- pub(super) fn release(&mut self) {- self.by_program = Column::default();- self.lifecycle = PrefixStateCacheLifecycle::Scratch(self.lifecycle.coverage());- }-- pub(super) fn release_transition_states(&mut self) {- if !self.has_relation() {- self.release();- return;- }- for slot in self.by_program.iter_mut() {- // The next installation restores the relation answers from the relation.- *slot = slot.as_mut().and_then(|states| states.relation.take()).map(|relation| {- let mut states = PrefixStates::new();- states.relation = Some(relation);- Box::new(states)- });- }- let coverage = self.lifecycle.coverage();- self.lifecycle = if self.lifecycle.is_current() {- PrefixStateCacheLifecycle::CurrentScratch(coverage)- } else {- PrefixStateCacheLifecycle::Scratch(coverage)- };- }-- pub(super) fn retain(&mut self) {- if self.lifecycle.is_retained() {- return;- }- for states in self.by_program.iter_mut().flatten() {- states.trim_for_retention();- }-- self.lifecycle = match self.lifecycle {- PrefixStateCacheLifecycle::Scratch(coverage) => PrefixStateCacheLifecycle::Retained(coverage),- PrefixStateCacheLifecycle::CurrentScratch(coverage) => PrefixStateCacheLifecycle::CurrentRetained(coverage),- PrefixStateCacheLifecycle::Retained(_) | PrefixStateCacheLifecycle::CurrentRetained(_) => unreachable!(),- };- }-- /// Forget one element's transition. This is the whole maintenance a pure tree flush needs,- /// so it stays valid on a retained cache.- pub(super) fn forget_transition(&mut self, program: ScopeProgramID, node: StyleNodeID) {- if let Some(states) = self.by_program.get_mut(program.0 as usize).and_then(Option::as_mut) {- states.forget_transition(node);- }- }-- /// Whether the resident states were last given back by a publication completion batch,- /// which warms spines but covers only the nodes that were asked: a walk over such a cache- /// must keep every pending route, since subsumption speaks for a route's whole candidate- /// space. A walk that refreshes the cache clears this.- #[must_use]- pub(super) fn is_sparse(&self) -> bool {- matches!(self.lifecycle.coverage(), PrefixStateCacheCoverage::Sparse)- }-- fn set_coverage(&mut self, coverage: PrefixStateCacheCoverage) {- self.lifecycle = match self.lifecycle {- PrefixStateCacheLifecycle::Scratch(_) => PrefixStateCacheLifecycle::Scratch(coverage),- PrefixStateCacheLifecycle::Retained(_) => PrefixStateCacheLifecycle::Retained(coverage),- PrefixStateCacheLifecycle::CurrentScratch(_) => PrefixStateCacheLifecycle::CurrentScratch(coverage),- PrefixStateCacheLifecycle::CurrentRetained(_) => PrefixStateCacheLifecycle::CurrentRetained(coverage),- };- }-- pub(super) fn mark_sparse(&mut self) {- self.set_coverage(PrefixStateCacheCoverage::Sparse);- }-- pub(super) fn mark_full(&mut self) {- self.set_coverage(PrefixStateCacheCoverage::Full);- }-- #[must_use]- pub(super) fn is_current(&self) -> bool {- self.lifecycle.is_current()- }-- #[must_use]- pub(super) fn is_retained(&self) -> bool {- self.lifecycle.is_retained()- }-- pub(super) fn mark_current(&mut self) {- self.lifecycle = match self.lifecycle {- PrefixStateCacheLifecycle::Scratch(coverage) => PrefixStateCacheLifecycle::CurrentScratch(coverage),- PrefixStateCacheLifecycle::Retained(coverage) => PrefixStateCacheLifecycle::CurrentRetained(coverage),- current- @ (PrefixStateCacheLifecycle::CurrentScratch(_) | PrefixStateCacheLifecycle::CurrentRetained(_)) => current,- };- }-- pub(super) fn mark_previous(&mut self) {- self.lifecycle = match self.lifecycle {- PrefixStateCacheLifecycle::CurrentScratch(coverage) => PrefixStateCacheLifecycle::Scratch(coverage),- PrefixStateCacheLifecycle::CurrentRetained(coverage) => PrefixStateCacheLifecycle::Retained(coverage),- previous @ (PrefixStateCacheLifecycle::Scratch(_) | PrefixStateCacheLifecycle::Retained(_)) => previous,- };- for states in self.by_program.iter_mut().flatten() {- if let Some(relation) = states.relation.as_mut() {- // A key's routes change with the program.- relation.handled_routing_keys.clear();- }- }- }-- pub(super) fn make_scratch(&mut self) {- if !self.lifecycle.is_retained() {- return;- }-- self.lifecycle = match self.lifecycle {- PrefixStateCacheLifecycle::Retained(coverage) => PrefixStateCacheLifecycle::Scratch(coverage),- PrefixStateCacheLifecycle::CurrentRetained(coverage) => PrefixStateCacheLifecycle::CurrentScratch(coverage),- PrefixStateCacheLifecycle::Scratch(_) | PrefixStateCacheLifecycle::CurrentScratch(_) => unreachable!(),- };- }-- pub(super) fn prepare_to_mutate(&mut self) {- debug_assert!(!self.lifecycle.is_retained());- for states in self.by_program.iter_mut().flatten() {- states.rebuild_interners();- }- }-- pub(super) fn remove(&mut self, program: ScopeProgramID) {- let index = program.0 as usize;- if let Some(entry) = self.by_program.get_mut(index) {- *entry = None;- }- }-}--fn hash_local_facts(facts: &StyleNodeFacts, row: u32, dependencies: &PrefixFactDependencies) -> u64 {- let mut hasher = fast_hasher();- facts.tag_of(row).hash(&mut hasher);- facts.folded_tag_of(row).hash(&mut hasher);- dependencies.id_of(facts, row).hash(&mut hasher);- facts.states_of(row).hash(&mut hasher);- facts.directionality_of(row).hash(&mut hasher);- facts.language_of(row).hash(&mut hasher);- facts.language_tag_of(row).hash(&mut hasher);- facts.namespace_of(row).hash(&mut hasher);- facts.heading_level_of(row).hash(&mut hasher);- facts.custom_states_of(row).hash(&mut hasher);- facts.parts_of(row).hash(&mut hasher);- for class in facts- .classes_of(row)- .iter()- .filter(|class| dependencies.classes.contains(class))- {- class.hash(&mut hasher);- }- for &attribute in facts- .attributes_of(row)- .iter()- .filter(|attribute| dependencies.reads_attribute(facts, attribute))- {- attribute.name.hash(&mut hasher);- dependencies.attribute_value(facts, attribute).hash(&mut hasher);- }- hasher.finish()-}--fn rows_have_equal_local_facts_between(- left_facts: &StyleNodeFacts,- left: u32,- right_facts: &StyleNodeFacts,- right: u32,- dependencies: &PrefixFactDependencies,-) -> bool {- if std::ptr::eq(left_facts, right_facts) && left == right {- return true;- }- if left_facts.tag_of(left) != right_facts.tag_of(right)- || left_facts.folded_tag_of(left) != right_facts.folded_tag_of(right)- || dependencies.id_of(left_facts, left) != dependencies.id_of(right_facts, right)- || left_facts.states_of(left) != right_facts.states_of(right)- || left_facts.directionality_of(left) != right_facts.directionality_of(right)- || left_facts.language_of(left) != right_facts.language_of(right)- || left_facts.language_tag_of(left) != right_facts.language_tag_of(right)- || left_facts.namespace_of(left) != right_facts.namespace_of(right)- || left_facts.heading_level_of(left) != right_facts.heading_level_of(right)- || left_facts.custom_states_of(left) != right_facts.custom_states_of(right)- || left_facts.parts_of(left) != right_facts.parts_of(right)- || !left_facts- .classes_of(left)- .iter()- .filter(|class| dependencies.classes.contains(class))- .eq(right_facts- .classes_of(right)- .iter()- .filter(|class| dependencies.classes.contains(class)))- {- return false;- }- let mut left_attributes = left_facts- .attributes_of(left)- .iter()- .filter(|attribute| dependencies.reads_attribute(left_facts, attribute));- let mut right_attributes = right_facts- .attributes_of(right)- .iter()- .filter(|attribute| dependencies.reads_attribute(right_facts, attribute));- loop {- match (left_attributes.next(), right_attributes.next()) {- (None, None) => return true,- (Some(&left), Some(&right))- if left.name == right.name- && dependencies.attribute_value(left_facts, left)- == dependencies.attribute_value(right_facts, right) => {}- _ => return false,- }- }-}--/// Whether a canonical feature holds. Canonical attribute features are answerable by their value atom alone.-fn matches_feature(row: MatchFactRow<'_>, feature: FeatureTest) -> bool {- super::selector_evaluation::matches_feature(&row, feature, |test, (_, attribute), _| match test.operator {- AttributeOperator::Presence => true,- AttributeOperator::Exact => attribute.value == test.value_atom,- _ => unreachable!("only atom-answerable features are canonicalized"),- })-}--#[cfg(test)]-mod tests {- use super::super::index::StyleAtomID;- use super::*;-- #[test]- fn local_fact_identity_distinguishes_only_observed_attribute_values() {- use super::super::index::StateSet;- use super::super::selector::{AttributeCase, AttributeTest};-- let name = StyleAtomID(20);- let mut facts = StyleNodeFacts::new();- for index in 0..3 {- facts.push_row(- StyleNodeID::element(index + 1),- StyleAtomID(1),- StyleAtomID::NONE,- StateSet(0),- &[],- &[AttributeFact {- name,- value: StyleAtomID(30 + index),- }],- );- }- for operator in [- AttributeOperator::Presence,- AttributeOperator::Exact,- AttributeOperator::Substring,- ] {- let mut dependencies = PrefixFactDependencies::default();- dependencies.add(FeatureTest::Attribute(AttributeTest {- name,- any_namespace: false,- folded: name,- fold_in_namespace: StyleAtomID::NONE,- operator,- value_atom: StyleAtomID(31),- value_offset: 0,- value_length: 0,- case: AttributeCase::Sensitive,- }));- let mut interner = LocalFactInterner::new();- let mut representatives = Default::default();- let identities: Vec<_> = (0..3)- .map(|row| interner.intern(&mut representatives, &facts, row, &dependencies, &Counters::default()))- .collect();- match operator {- AttributeOperator::Presence => assert_eq!(identities, [1, 1, 1]),- AttributeOperator::Exact => assert_eq!(identities, [1, 2, 1]),- AttributeOperator::Substring => assert_eq!(identities, [1, 2, 3]),- _ => unreachable!(),- }- }- }-- #[test]- fn local_fact_cohorts_only_inspect_queried_rows() {- use super::super::index::StateSet;-- let mut facts = StyleNodeFacts::new();- for node in 1..=1000 {- facts.push_row(- StyleNodeID::element(node),- StyleAtomID(10),- StyleAtomID::NONE,- StateSet(0),- &[],- &[],- );- }- let mut states = PrefixStates::new();- let automaton = PrefixAutomaton::default();- let counters = Counters::default();- let mut context = PrefixTransitionContext::new(&mut states, &facts);- assert_eq!(counters.get(Counter::PrefixLocalFactIdentityHits), 0);- assert_eq!(counters.get(Counter::PrefixLocalFactIdentityMisses), 0);-- let first = context.scratch.ensure_local_fact_identity(- &mut states,- &automaton,- &facts,- StyleNodeID::element(999),- &counters,- );- let second = context.scratch.ensure_local_fact_identity(- &mut states,- &automaton,- &facts,- StyleNodeID::element(1000),- &counters,- );- assert_eq!(first, second);- assert_eq!(counters.get(Counter::PrefixLocalFactIdentityHits), 1);- assert_eq!(counters.get(Counter::PrefixLocalFactIdentityMisses), 1);- assert_eq!(- first,- context.scratch.ensure_local_fact_identity(- &mut states,- &automaton,- &facts,- StyleNodeID::element(999),- &counters,- ),- );- assert_eq!(counters.get(Counter::PrefixLocalFactIdentityHits), 1);- assert_eq!(counters.get(Counter::PrefixLocalFactIdentityMisses), 1);- }-- #[test]- fn composite_cohorts_lazily_preserve_unchanged_retained_identities() {- use super::super::index::StateSet;-- let mut facts = StyleNodeFacts::new();- for node in 1..=3 {- facts.push_row(- StyleNodeID::element(node),- StyleAtomID(10),- StyleAtomID::NONE,- StateSet(0),- &[],- &[],- );- }- let mut states = PrefixStates::new();- let retained = states.local_fact_interner.mint_identity();- states.set_local_facts(StyleNodeID::element(1), retained);- states.set_local_facts(StyleNodeID::element(2), retained);- let counters = Counters::default();- let mut context = PrefixTransitionContext::new_composite(&mut states, &facts, &[StyleNodeID::element(1)]);- assert_eq!(counters.get(Counter::PrefixLocalFactIdentityMisses), 0);- let mut identity = |node| {- context.scratch.ensure_local_fact_identity(- &mut states,- &PrefixAutomaton::default(),- &facts,- StyleNodeID::element(node),- &counters,- )- };- let changed = identity(1);- assert_ne!(changed, retained);- assert_eq!(identity(2), retained);- let unretained = identity(3);- assert_ne!(unretained, retained);- assert_ne!(unretained, changed);- assert_eq!(identity(1), changed);- assert_eq!(counters.get(Counter::PrefixLocalFactIdentityMisses), 2);- assert_eq!(counters.get(Counter::PrefixLocalFactIdentityHits), 0);- }-- #[test]- fn rebinding_a_context_drops_answers_naming_a_replaced_arena() {- use super::super::index::StateSet;-- let mut facts = StyleNodeFacts::new();- for node in 1..=2 {- facts.push_row(- StyleNodeID::element(node),- StyleAtomID(10),- StyleAtomID::NONE,- StateSet(0),- &[],- &[],- );- }- let program = ScopeProgramID(0);- let node = StyleNodeID::element(1);- let memoized = PrefixTransition {- state: 7,- right: 0,- result: PrefixResultID(9),- };- let mut states = PrefixStates::new();- let mut contexts = PrefixTransitionContexts::default();- contexts.prepare(program, &mut states, &facts);- {- let context = contexts.get_mut(program);- context.scratch.by_node.insert(node, memoized);- context.effects.writes.push(PrefixNodeWrite {- node,- transition: memoized,- entering: UNKNOWN_ENTERING_STATES,- positional_bits: None,- local_facts: None,- });- }-- // Releasing the cache rebuilds the arena every answer above names by index.- let mut rebuilt = PrefixStates::new();- contexts.rebind(program, &mut rebuilt, &facts);- let context = contexts.get_mut(program);- assert!(context.scratch.by_node.is_empty());- assert!(context.scratch.memo.is_empty());- assert!(context.effects.writes.is_empty());- assert!(context.scratch.local_facts_by_row.is_empty());-- // The arena it now names keeps what the traversal memoizes against it.- contexts.get_mut(program).scratch.by_node.insert(node, memoized);- contexts.rebind(program, &mut rebuilt, &facts);- assert_eq!(contexts.get_mut(program).scratch.by_node.get(&node), Some(&memoized));- }-- #[test]- fn prepared_local_facts_survive_nested_domains_and_appends() {- use super::super::index::StateSet;-- let mut facts = StyleNodeFacts::new();- for (node, tag) in [(1, 10), (2, 20), (3, 10)] {- facts.push_row(- StyleNodeID::element(node),- StyleAtomID(tag),- StyleAtomID::NONE,- StateSet(0),- &[],- &[],- );- }- let mut states = PrefixStates::new();- let automaton = PrefixAutomaton::default();- let identity =- |context: &mut PrefixTransitionContext, states: &mut PrefixStates, facts: &StyleNodeFacts, node| {- context.scratch.ensure_local_fact_identity(- states,- &automaton,- facts,- StyleNodeID::element(node),- &Counters::default(),- )- };- let mut context = PrefixTransitionContext::new(&mut states, &facts);- let first = identity(&mut context, &mut states, &facts, 1);- let second = identity(&mut context, &mut states, &facts, 2);- assert_ne!(first, second);- assert_eq!(first, identity(&mut context, &mut states, &facts, 3));-- // A nested retry has its own representatives in a different row ordering.- let mut retry_facts = StyleNodeFacts::new();- for (node, tag) in [(3, 10), (2, 20), (1, 10)] {- retry_facts.push_row(- StyleNodeID::element(node),- StyleAtomID(tag),- StyleAtomID::NONE,- StateSet(0),- &[],- &[],- );- }- let mut retry = PrefixTransitionContext::new(&mut states, &retry_facts);- assert_eq!(- identity(&mut retry, &mut states, &retry_facts, 1),- identity(&mut retry, &mut states, &retry_facts, 3)- );- assert_ne!(- identity(&mut retry, &mut states, &retry_facts, 1),- identity(&mut retry, &mut states, &retry_facts, 2)- );- // IDs remain unique across contexts sharing the same state arena.- assert_ne!(first, identity(&mut retry, &mut states, &retry_facts, 2));- drop(retry);- assert_eq!(first, identity(&mut context, &mut states, &facts, 1));- assert_eq!(second, identity(&mut context, &mut states, &facts, 2));-- // Appending to the suspended domain retains its old cohorts, including new members.- facts.push_row(- StyleNodeID::element(4),- StyleAtomID(20),- StyleAtomID::NONE,- StateSet(0),- &[],- &[],- );- context.prepare(&mut states, &facts);- assert_eq!(second, identity(&mut context, &mut states, &facts, 4));- assert_eq!(first, identity(&mut context, &mut states, &facts, 3));-- // Reusing scratch for a rebuilt domain must re-prepare every row.- context.prepare(&mut states, &retry_facts);- assert_eq!(- identity(&mut context, &mut states, &retry_facts, 1),- identity(&mut context, &mut states, &retry_facts, 3)- );- assert_ne!(- identity(&mut context, &mut states, &retry_facts, 1),- identity(&mut context, &mut states, &retry_facts, 2)- );- }-- #[test]- fn begin_transition_sizes_every_scratch_column_independently() {- let mut automaton = PrefixAutomaton::default();- for _ in 0..8_u32 {- automaton.steps.push(PrefixStep {- compound: PrefixCompoundID(0),- output_start: 0,- output_len: 0,- });- }- let mut states = PrefixStates::new();- // Retention trims every column to empty; comparison and sparse-delta paths regrow- // candidate_epoch alone. begin_transition must size the siblings regardless.- states.candidate_epoch.resize(automaton.steps.len(), 0);- states.begin_transition(&automaton);- assert_eq!(states.output_epoch.len(), automaton.steps.len());- assert_eq!(states.parent_persisting_epoch.len(), automaton.steps.len());- assert_eq!(states.previous_persisting_epoch.len(), automaton.steps.len());- }-- #[test]- fn prefix_state_digests_use_existing_alignment_space() {- assert_eq!(size_of::<PrefixState>(), 32);- }-- #[test]- fn a_forgotten_prefix_transition_is_a_typed_missing_node() {- let mut states = PrefixStates::new();- let node = StyleNodeID::element(1);- assert!(matches!(- states.transition_of(node),- PrefixTransitionLookup::Missing(PrefixTransitionGap::MissingTransition(gap)) if gap == node- ));-- states.install_prefix_effects(&mut PrefixEffects {- writes: vec![PrefixNodeWrite {- node,- transition: PrefixTransition {- state: 0,- right: 0,- result: PrefixResultID::default(),- },- entering: EnteringStates { parent: 0, previous: 0 },- positional_bits: Some(0b11),- local_facts: None,- }],- });- assert!(matches!(states.transition_of(node), PrefixTransitionLookup::Known(_)));- states.forget_transition(node);- assert_eq!(- states.entering_by_element[node.element_index().unwrap() as usize].parent,- UNKNOWN_STATE- );- assert_eq!(- states.positional_bits_by_element[node.element_index().unwrap() as usize],- 0- );- assert!(matches!(- states.transition_of(node),- PrefixTransitionLookup::Missing(PrefixTransitionGap::MissingTransition(gap)) if gap == node- ));- }-- #[test]- fn sparse_rebase_shares_unchanged_local_payload() {- let mut states = PrefixStates::new();- let counters = Counters::new();- let old_base_step = PrefixStepID(1);- let local_step = PrefixStepID(2);- let expiring_step = PrefixStepID(3);- let new_base_step = PrefixStepID(4);- let old_base = states.intern_extended_state(0, &[old_base_step], step_hash(old_base_step), &[], 0, &counters);- let source = states.intern_extended_state(- old_base,- &[local_step],- step_hash(local_step),- &[expiring_step],- step_hash(expiring_step) as u32,- &counters,- );- let new_base = states.intern_extended_state(0, &[new_base_step], step_hash(new_base_step), &[], 0, &counters);- let source_payload = states.states[source as usize].payload_start;-- let rebased = states- .rebase_unchanged_local_payload(source, old_base, new_base, &counters)- .expect("a one-level local payload can be rebased");-- assert_eq!(states.states[rebased as usize].base, new_base);- assert_eq!(states.states[rebased as usize].payload_start, source_payload);- assert_eq!(states.additions_in(rebased), [local_step]);- assert_eq!(states.expiring_in(rebased), [expiring_step]);- }-- #[test]- fn equal_prefix_state_contents_share_an_identity_across_base_chains() {- let first = PrefixStepID(1);- let second = PrefixStepID(2);- let mut states = PrefixStates::new();- states.automaton_step_count = 3;- let counters = Counters::new();- let first_base = states.intern_extended_state(0, &[first], step_hash(first), &[], 0, &counters);- let second_base = states.intern_extended_state(0, &[second], step_hash(second), &[], 0, &counters);-- let first_then_second =- states.intern_extended_state(first_base, &[second], step_hash(second), &[], 0, &counters);- let second_then_first =- states.intern_extended_state(second_base, &[first], step_hash(first), &[], 0, &counters);-- assert_eq!(first_then_second, second_then_first);- }-- #[test]- fn prefix_state_interning_checks_equal_length_and_hash_collisions() {- let first = PrefixStepID(1);- let second = PrefixStepID(2);- let third = PrefixStepID(3);- let fourth = PrefixStepID(4);- let mut states = PrefixStates::new();- states.automaton_step_count = 5;- let counters = Counters::new();- let first_base = states.intern_extended_state(0, &[first], step_hash(first), &[], 0, &counters);- let second_base = states.intern_extended_state(0, &[second], step_hash(second), &[], 0, &counters);- let collision_hash = step_hash(first).wrapping_add(step_hash(second));- let collision = states.intern_extended_state(0, &[third, fourth], collision_hash, &[], 0, &counters);- let first_then_second =- states.intern_extended_state(first_base, &[second], step_hash(second), &[], 0, &counters);-- assert_ne!(collision, first_then_second);- let key = state_content_key(2, collision_hash, 0, 0);- assert_eq!(states.states_by_hash[&key].first, PrefixStateID(collision));- assert_eq!(- states.states_by_hash[&key].collisions,- [PrefixStateID(first_then_second)]- );-- let second_then_first =- states.intern_extended_state(second_base, &[first], step_hash(first), &[], 0, &counters);- assert_eq!(second_then_first, first_then_second);- }-- #[test]- fn prefix_state_equality_compares_structural_sets_without_sorting() {- let first = PrefixStepID(1);- let second = PrefixStepID(2);- let third = PrefixStepID(3);- let mut states = PrefixStates::new();- states.automaton_step_count = 4;- states.candidate_epoch.resize(4, 0);- states.delta_steps = [first, second, first, second, third]- .into_iter()- .map(std::mem::MaybeUninit::new)- .collect();- states.states.extend([- PrefixState {- base: 0,- payload_start: 0,- additions_len: 2,- expiring_len: 0,- descendant_len: 2,- descendant_hash: step_hash(first).wrapping_add(step_hash(second)),- expiring_hash: 0,- },- PrefixState {- base: 0,- payload_start: 2,- additions_len: 1,- expiring_len: 0,- descendant_len: 1,- descendant_hash: step_hash(first),- expiring_hash: 0,- },- PrefixState {- base: 2,- payload_start: 3,- additions_len: 1,- expiring_len: 0,- descendant_len: 2,- descendant_hash: step_hash(first).wrapping_add(step_hash(second)),- expiring_hash: 0,- },- PrefixState {- base: 2,- payload_start: 4,- additions_len: 1,- expiring_len: 0,- descendant_len: 2,- descendant_hash: step_hash(first).wrapping_add(step_hash(third)),- expiring_hash: 0,- },- ]);-- assert!(states.selected_states_equal(1, 3, None));- assert!(!states.selected_states_equal(3, 4, None));- let selection = PrefixSelection {- steps: vec![false, true, false, false].into_boxed_slice(),- terminals: Box::new([]),- };- assert!(states.selected_states_equal(3, 4, Some(&selection)));- }-- #[test]- fn prefix_state_deltas_compare_the_selected_active_set() {- let cancelled = PrefixStepID(1);- let changed = PrefixStepID(2);- let mut arena = PrefixDeltaArena::default();- arena.scratch[0].extend([cancelled, changed]);- arena.scratch[3].push(cancelled);- let delta = arena.append_scratch_delta(0);- let cancelled_selection = PrefixSelection {- steps: vec![false, true, false].into_boxed_slice(),- terminals: Box::new([]),- };- let changed_selection = PrefixSelection {- steps: vec![false, true, true].into_boxed_slice(),- terminals: Box::new([]),- };-- assert!(!arena.changes_selected_state(delta, &cancelled_selection));- assert!(arena.changes_selected_state(delta, &changed_selection));- }-- #[test]- fn sparse_rebase_applies_signed_local_output_edits() {- let mut states = PrefixStates::new();- let counters = Counters::new();- let old_base_step = PrefixStepID(0);- let retained_step = PrefixStepID(1);- let removed_step = PrefixStepID(2);- let new_base_step = PrefixStepID(3);- let removed_expiring_step = PrefixStepID(4);- let added_step = PrefixStepID(5);- let added_expiring_step = PrefixStepID(6);- let old_base = states.intern_extended_state(0, &[old_base_step], step_hash(old_base_step), &[], 0, &counters);- let source = states.intern_extended_state(- old_base,- &[retained_step, removed_step],- step_hash(retained_step).wrapping_add(step_hash(removed_step)),- &[removed_expiring_step],- step_hash(removed_expiring_step) as u32,- &counters,- );- let new_base = states.intern_extended_state(0, &[new_base_step], step_hash(new_base_step), &[], 0, &counters);- let mut arena = PrefixDeltaArena::default();- arena.scratch[0].extend([new_base_step, added_step]);- arena.scratch[1].push(removed_step);- arena.scratch[2].push(added_expiring_step);- arena.scratch[3].push(removed_expiring_step);- let delta = arena.append_scratch_delta(0);-- let rebased = states- .rebase_payload_with_local_delta(source, old_base, new_base, delta, &arena, true, &counters)- .expect("a one-level local payload can apply signed edits");-- assert_eq!(states.states[rebased as usize].base, new_base);- assert_eq!(states.additions_in(rebased), [retained_step, added_step]);- assert_eq!(states.expiring_in(rebased), [added_expiring_step]);- }-- #[test]- fn finished_automaton_classifies_terminal_producers() {- let mut automaton = PrefixAutomaton::default();- automaton.compounds.push(PrefixCompound {- predicate: PrefixPredicate::Features {- feature_start: 0,- feature_len: 0,- required_positional_bits: 0,- },- dispatch_key: DispatchKey::Universal,- });- automaton- .buckets- .insert(DispatchKey::Universal, PrefixDispatchBucket::default());- for _ in 0..2 {- automaton.steps.push(PrefixStep {- compound: PrefixCompoundID(0),- output_start: 0,- output_len: 0,- });- automaton.step_predecessors.push(u32::MAX);- automaton.step_output_builders.push(PrefixStepOutputBuilder::default());- }- let unique = EntryID(0);- let shared = EntryID(1);- automaton.step_output_builders[0]- .terminals- .extend([unique, unique, shared]);- automaton.step_output_builders[1].terminals.push(shared);-- automaton.finish(&mut PrefixPools::default());-- let first_outputs = automaton.outputs_for(&automaton.steps[0]);- assert!(matches!(first_outputs[0].kind, PrefixOutputKind::UniqueTerminal));- assert!(matches!(first_outputs[1].kind, PrefixOutputKind::UniqueTerminal));- assert!(matches!(first_outputs[2].kind, PrefixOutputKind::SharedTerminal));- let second_outputs = automaton.outputs_for(&automaton.steps[1]);- assert!(matches!(second_outputs[0].kind, PrefixOutputKind::SharedTerminal));- }-- #[test]- fn finished_automaton_remaps_step_references_into_dispatch_order() {- let mut automaton = PrefixAutomaton::default();- automaton.compounds.extend([- PrefixCompound {- predicate: PrefixPredicate::Features {- feature_start: 0,- feature_len: 0,- required_positional_bits: 0,- },- dispatch_key: DispatchKey::Universal,- },- PrefixCompound {- predicate: PrefixPredicate::Features {- feature_start: 0,- feature_len: 0,- required_positional_bits: 0,- },- dispatch_key: DispatchKey::Id(StyleAtomID(1)),- },- ]);- automaton.buckets.insert(- DispatchKey::Universal,- PrefixDispatchBucket {- root_steps: PrefixRootSteps::One(PrefixStepID(0)),- ..PrefixDispatchBucket::default()- },- );- automaton- .buckets- .insert(DispatchKey::Id(StyleAtomID(1)), PrefixDispatchBucket::default());- automaton.steps.extend([- PrefixStep {- compound: PrefixCompoundID(0),- output_start: 0,- output_len: 0,- },- PrefixStep {- compound: PrefixCompoundID(1),- output_start: 0,- output_len: 0,- },- ]);- automaton.step_predecessors.extend([u32::MAX, 0]);- automaton- .step_output_builders- .resize(2, PrefixStepOutputBuilder::default());- automaton.step_output_builders[0].child_successors.push(PrefixStepID(1));- automaton.entry_path_steps.extend([PrefixStepID(0), PrefixStepID(1)]);- automaton.entry_paths.push(PrefixEntryPath {- terminal: EntryID(0),- steps: 0..2,- });-- automaton.finish(&mut PrefixPools::default());-- assert_eq!(- automaton.compounds[automaton.steps[0].compound.0 as usize].dispatch_key,- DispatchKey::Id(StyleAtomID(1))- );- assert_eq!(automaton.predecessor_of(PrefixStepID(0)), Some(PrefixStepID(1)));- let outputs = automaton.outputs_for(&automaton.steps[1]);- assert!(matches!(outputs[0].kind, PrefixOutputKind::Child));- assert_eq!(outputs[0].target, 0);- assert_eq!(- automaton.bucket(DispatchKey::Universal).unwrap().root_steps.as_slice(),- [PrefixStepID(1)]- );- assert_eq!(- automaton.path_for(EntryID(0)).unwrap(),- [PrefixStepID(1), PrefixStepID(0)]- );- }-- #[test]- fn sparse_match_delta_applies_additions_and_removals() {- let mut states = PrefixStates::new();- let removed = EntryID(0);- let retained = EntryID(1);- let added = EntryID(2);- states.output_matches.extend([removed, retained]);- let matches = states.intern_output_matches();- let old_result = states.intern_result(matches, PrefixTruthSetID::default());- let mut arena = PrefixDeltaArena::default();- arena.match_scratch[0].push(added);- arena.match_scratch[1].push(removed);- let delta = arena.append_match_delta();-- let result = states.apply_local_match_delta(old_result, delta, &arena);-- assert_eq!(- states.matches_in(states.results[result.0 as usize].matches),- [retained, added]- );- assert_eq!(states.results[result.0 as usize].truth, PrefixTruthSetID::default());- }-- #[test]- fn compaction_invalidates_a_prepared_transition_context() {- let mut states = PrefixStates::new();- let facts = StyleNodeFacts::new();- let mut context = PrefixTransitionContext::new(&mut states, &facts);- // An answer memoized against a state the compaction below drops.- states.states.push(PrefixState {- base: 0,- payload_start: 0,- additions_len: 0,- expiring_len: 0,- descendant_len: 0,- descendant_hash: 0,- expiring_hash: 0,- });- states.descendant_only.push(UNKNOWN_STATE);- let key = PrefixTransitionKey {- parent: 0,- previous: 0,- local_facts: 0,- is_document_root: true,- positional_bits: 0,- };- context.scratch.memo.insert(- key,- PrefixTransition {- state: 1,- right: 0,- result: PrefixResultID::default(),- },- );-- states.compact_interned_states();- assert_eq!(states.states.len(), 1);- context.prepare(&mut states, &facts);- assert!(context.scratch.memo.is_empty());- }-- #[test]- fn retention_compacts_prefix_states_from_element_roots() {- let mut states = PrefixStates::new();- states.delta_steps = vec![- std::mem::MaybeUninit::new(PrefixStepID(1)),- std::mem::MaybeUninit::new(PrefixStepID(2)),- std::mem::MaybeUninit::new(PrefixStepID(3)),- ];- states.states.extend([- PrefixState {- base: 0,- payload_start: 0,- additions_len: 1,- expiring_len: 0,- descendant_len: 1,- descendant_hash: step_hash(PrefixStepID(1)),- expiring_hash: 0,- },- PrefixState {- base: 0,- payload_start: 1,- additions_len: 1,- expiring_len: 0,- descendant_len: 1,- descendant_hash: step_hash(PrefixStepID(2)),- expiring_hash: 0,- },- PrefixState {- base: 2,- payload_start: 2,- additions_len: 1,- expiring_len: 0,- descendant_len: 2,- descendant_hash: step_hash(PrefixStepID(2)).wrapping_add(step_hash(PrefixStepID(3))),- expiring_hash: 0,- },- ]);- states.descendant_only = vec![0, 1, 2, 3];- let node = StyleNodeID::element(1);- states.install_prefix_effects(&mut PrefixEffects {- writes: vec![PrefixNodeWrite {- node,- transition: PrefixTransition {- state: 3,- right: 0,- result: PrefixResultID::default(),- },- entering: EnteringStates { parent: 3, previous: 0 },- positional_bits: None,- local_facts: None,- }],- });- states.compact_interned_states();-- assert_eq!(states.states.len(), 3);- assert_eq!(states.additions_in(1), [PrefixStepID(2)]);- assert_eq!(states.additions_in(2), [PrefixStepID(3)]);- let PrefixTransitionLookup::Known(transition) = states.transition_of(node) else {- panic!("the compacted transition must be known");- };- assert_eq!(transition.state, 2);- assert_eq!(- states.entering_by_element[node.element_index().unwrap() as usize].parent,- 2- );- assert_eq!(states.states[transition.state as usize].base, 1);- }-- #[test]- fn retention_preserves_working_vector_capacity() {- let mut states = PrefixStates::new();- states.last_compacted_working_bytes = states.interned_working_bytes();- states.match_offsets.reserve(32);- states.match_entries.reserve(32);- states.truth_offsets.reserve(32);- states.truth_steps.reserve(32);- states.results.reserve(32);- states.transition_by_element.reserve(32);- let capacities = [- states.match_offsets.capacity(),- states.match_entries.capacity(),- states.truth_offsets.capacity(),- states.truth_steps.capacity(),- states.results.capacity(),- states.transition_by_element.capacity(),- ];-- states.trim_for_retention();-- assert_eq!(- capacities,- [- states.match_offsets.capacity(),- states.match_entries.capacity(),- states.truth_offsets.capacity(),- states.truth_steps.capacity(),- states.results.capacity(),- states.transition_by_element.capacity(),- ]- );- }-}diff --git a/Libraries/LibWeb/Rust/src/css/style/prefix/relation.rs b/Libraries/LibWeb/Rust/src/css/style/prefix/relation.rsdeleted file mode 100644index e3b3819730a..00000000000--- a/Libraries/LibWeb/Rust/src/css/style/prefix/relation.rs+++ /dev/null@@ -1,1789 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! Incremental selector-prefix membership, organized by selector step.-//!-//! Each step retains the elements matching its complete prefix. A changed local predicate or-//! predecessor membership propagates only to candidates reachable through the next combinator.-//! Terminal changes supply both the planner's signed selector truth and matching completion.--use smallvec::SmallVec;--use super::super::fast_hash::FastSet as HashSet;-use super::super::selector::RoutingKey;-use super::super::tree::TreeScopeID;-use super::{- Column, Counter, Counters, DispatchKey, EntryID, HashMap, PrefixAutomaton, PrefixEvaluation, PrefixOutputKind,- PrefixPredicate, PrefixStates, PrefixStepID, PrefixTransitionLookup, StyleNodeID, StyleNodeTree, matches_feature,-};--// This is derived only from the immutable automaton. Memberships and pending edits stay in-// PrefixRelation, while every scope using that automaton shares its traversal and lookup tables.-pub(super) struct PrefixRelationProgram {- // Step identities are in dispatch order, so retain their dependency order separately.- queue: Vec<QueuedStep>,- step_ranks: Vec<u32>,- compound_step_offsets: Vec<u32>,- compound_steps: Vec<u32>,- has_following_steps: bool,- /// Whether any step is reached over each geometry axis, in the order of `PrefixRelation::geometry_targets`: the- /// child, descendant, next-sibling and following-sibling axes.- geometry_axes: [bool; 4],- compounds_by_key: HashMap<DispatchKey, std::ops::Range<u32>>,- keyed_compounds: Vec<u32>,- terminal_steps: HashMap<EntryID, SmallVec<[usize; 1]>>,-}--/// A step in dependency order, with what an update reads of it as it runs: how it is reached, its compound and its-/// predecessor (`u32::MAX` for none). Updates run steps in this order, so they read these one after another.-#[derive(Clone, Copy)]-struct QueuedStep {- step: u32,- axis: PrefixOutputKind,- compound: u32,- predecessor: u32,-}--impl PrefixRelationProgram {- fn compounds_for_key(&self, key: &DispatchKey) -> Option<impl Iterator<Item = usize> + '_> {- let range = self.compounds_by_key.get(key)?;- Some(- self.keyed_compounds[range.start as usize..range.end as usize]- .iter()- .map(|&index| index as usize),- )- }-- fn steps_for_compound(&self, compound: usize) -> impl Iterator<Item = usize> + '_ {- self.compound_steps- [self.compound_step_offsets[compound] as usize..self.compound_step_offsets[compound + 1] as usize]- .iter()- .map(|&step| step as usize)- }-}--/// The positions a compound or a step holds, which the relation asks about far more often than it changes. Most sets-/// hold none or a handful: a set is listed in ascending order while that takes less room than a bitmap up to its last-/// position, and is that bitmap, which answers with one load, once it takes more. The set lives in the dense table of-/// sets, so asking it reads its buffer and nothing else; a set that never held a position allocates nothing.-enum PositionSet {- /// Ascending.- Listed(Vec<u32>),- /// Bit `position % 64` of word `position / 64` for each position, and how many there are.- Bits { words: Vec<u64>, len: u32 },-}--// The dense table holds a set per compound and per step, most of them empty.-const _: () = assert!(size_of::<PositionSet>() == 32);--impl Default for PositionSet {- fn default() -> Self {- Self::Listed(Vec::new())- }-}--impl FromIterator<usize> for PositionSet {- /// The set of the ascending `positions`.- fn from_iter<I: IntoIterator<Item = usize>>(positions: I) -> Self {- let list: Vec<u32> = positions.into_iter().map(position_u32).collect();- debug_assert!(list.is_sorted());- let mut set = Self::Listed(list);- set.settle();- set- }-}--impl PositionSet {- fn len(&self) -> usize {- match self {- Self::Listed(list) => list.len(),- Self::Bits { len, .. } => *len as usize,- }- }-- fn is_empty(&self) -> bool {- self.len() == 0- }-- fn contains(&self, position: usize) -> bool {- match self {- Self::Listed(list) => u32::try_from(position).is_ok_and(|position| list.binary_search(&position).is_ok()),- Self::Bits { words, .. } => has_bit(words, position),- }- }-- /// The positions, ascending.- fn iter(&self) -> impl Iterator<Item = usize> + '_ {- let (list, words): (&[u32], &[u64]) = match self {- Self::Listed(list) => (list, &[]),- Self::Bits { words, .. } => (&[], words),- };- list.iter().map(|&position| position as usize).chain(- words- .iter()- .enumerate()- .flat_map(|(index, &word)| set_bits(index, word)),- )- }-- /// Removes the `departed` positions, which `live` no longer holds, returning whether the set held any. A list- /// keeps what is live; a bitmap clears the departed.- fn remove_departed(&mut self, departed: &[usize], live: &[bool]) -> bool {- match self {- Self::Listed(list) => {- let before = list.len();- list.retain(|&position| live[position as usize]);- list.len() != before- }- Self::Bits { words, len } => {- let before = *len;- for &position in departed {- if has_bit(words, position) {- words[position / 64] &= !(1 << (position % 64));- *len -= 1;- }- }- *len != before- }- }- }-- /// Empties the set into `into`, in ascending order. The set keeps its buffer.- fn drain_into(&mut self, into: &mut Vec<usize>) {- match self {- Self::Listed(list) => into.extend(list.drain(..).map(|position| position as usize)),- Self::Bits { words, len } => {- for (index, word) in words.iter_mut().enumerate() {- into.extend(set_bits(index, std::mem::take(word)));- }- *len = 0;- }- }- }-- /// Flips whether the set holds each of the ascending, distinct `changes`.- fn toggle(&mut self, changes: &[usize]) {- let Some(&last) = changes.last() else {- return;- };- match self {- Self::Listed(list) => toggle_listed(list, changes),- Self::Bits { words, len } => {- if words.len() <= last / 64 {- words.resize(last / 64 + 1, 0);- }- for &position in changes {- let word = &mut words[position / 64];- let bit = 1 << (position % 64);- *word ^= bit;- if *word & bit != 0 {- *len += 1;- } else {- *len -= 1;- }- }- }- }- self.settle();- }-- /// Keeps the set in the form that takes less room: listed until its positions take more room than the bitmap up- /// to the last of them, and listed again once they take less than half the bitmap, so that a set whose size wavers- /// around the bound does not convert back and forth.- fn settle(&mut self) {- match self {- Self::Listed(list) => {- let Some(&last) = list.last() else {- return;- };- let word_count = last as usize / 64 + 1;- if size_of_val(list.as_slice()) <= word_count * size_of::<u64>() {- return;- }- let mut words = vec![0_u64; word_count];- for &position in list.iter() {- words[position as usize / 64] |= 1 << (position % 64);- }- let len = position_u32(list.len());- *self = Self::Bits { words, len };- }- Self::Bits { words, len } => {- if 2 * *len as usize * size_of::<u32>() >= size_of_val(words.as_slice()) {- return;- }- let list = words- .iter()- .enumerate()- .flat_map(|(index, &word)| set_bits(index, word))- .map(position_u32)- .collect();- *self = Self::Listed(list);- }- }- }-}--/// A position as a set lists it: a relation holds nowhere near 2^32 elements.-fn position_u32(position: usize) -> u32 {- debug_assert!(- u32::try_from(position).is_ok(),- "prefix relation position space exhausted"- );- position as u32-}--fn has_bit(words: &[u64], position: usize) -> bool {- words- .get(position / 64)- .is_some_and(|word| word & (1 << (position % 64)) != 0)-}--/// The positions the bits of word `index` of a bitmap stand for, ascending.-fn set_bits(index: usize, mut word: u64) -> impl Iterator<Item = usize> {- std::iter::from_fn(move || {- (word != 0).then(|| {- let bit = word.trailing_zeros() as usize;- word &= word - 1;- index * 64 + bit- })- })-}--pub(in crate::css::style) struct PrefixRelation {- program: std::sync::Arc<PrefixRelationProgram>,- // Membership positions are stable slots. Inserting or removing a node does not renumber- // unrelated matches; retired slots are reused only after their memberships are removed.- nodes: Vec<StyleNodeID>,- positions: Column<usize>,- parents: Vec<usize>,- previous: Vec<usize>,- live: Vec<bool>,- free_slots: Vec<usize>,- departures: Vec<usize>,- compound_matches: Vec<PositionSet>,- matches: Vec<PositionSet>,- walk_truth: PrefixWalkMemo,- pending_steps: PendingPrefixSteps,- positional: Vec<u32>,- geometry_targets: [Vec<usize>; 4],- old_previous: Vec<(usize, usize)>,- sibling_order_is_preserved: bool,- answers: Vec<Vec<EntryID>>,- pub(in crate::css::style) changed_answers: Vec<(StyleNodeID, Vec<EntryID>, Vec<EntryID>)>,- arrivals: Vec<usize>,- /// A bit per position for the arrivals of the update in progress, which hold no membership yet: an arrival's slot- /// is new, or was taken out of every set as it departed.- arrived: Vec<u64>,- pub(in crate::css::style) handled_routing_keys: HashMap<RoutingKey, bool>,- // Routine prefix-cache accounting must not walk every selector set for each matching node.-}--impl PrefixRelation {- fn verify_answers(&self, evaluation: &mut PrefixEvaluation<'_, '_>) {- if !cfg!(test) && !super::super::verification::prefix_relation_is_enabled() {- return;- }- let mut scalar = PrefixStates::new();- let counters = Counters::default();- let mut context = if evaluation.facts_are_composite() {- super::PrefixTransitionContext::new_composite(&mut scalar, evaluation.facts, &[])- } else {- super::PrefixTransitionContext::new(&mut scalar, evaluation.facts)- };- for (position, &node) in self.nodes.iter().enumerate() {- if !self.live[position] {- continue;- }- let PrefixTransitionLookup::Known(answer) =- scalar.match_set_for(&mut context.scratch, &mut context.effects, evaluation, node, &counters)- else {- panic!("a complete prefix relation must have a complete scalar answer");- };- assert_eq!(- self.answers[position],- scalar.matches_in(answer),- "prefix relation differs for {node:?}"- );- }- }-- /// Install the answers into `states`: every live node's when `states` holds none yet, and- /// otherwise the ones the last update changed and its arrivals. Both are installed once: a- /// transaction that installs the relation again without an update or a geometry pass would- /// otherwise pay the size of that old update again.- pub(in crate::css::style) fn install_answers(&mut self, states: &mut PrefixStates) {- if states.relation_answers.is_empty() {- for (position, (&node, entries)) in self.nodes.iter().zip(&self.answers).enumerate() {- if self.live[position] {- states.install_relation_answer(node, entries);- }- }- } else {- for (node, _, entries) in &self.changed_answers {- states.install_relation_answer(*node, entries);- }- for &position in &self.arrivals {- states.install_relation_answer(self.nodes[position], &self.answers[position]);- }- }- self.changed_answers.clear();- self.arrivals.clear();- }-- /// Whether `node` is one of the live nodes the relation answers for.- pub(in crate::css::style) fn holds(&self, node: StyleNodeID) -> bool {- let position = self.position_of(Some(node));- position != usize::MAX && self.live[position]- }-- fn position_of(&self, node: Option<StyleNodeID>) -> usize {- node.and_then(|node| self.positions.get(node.raw() as usize))- .copied()- .unwrap_or(usize::MAX)- }-- pub(in crate::css::style) fn update_geometry(- &mut self,- automaton: &PrefixAutomaton,- evaluation: &mut PrefixEvaluation<'_, '_>,- changed: &[StyleNodeID],- counters: &Counters,- ) -> Vec<StyleNodeID> {- let tree = evaluation.tree;- let mut touched = changed.to_vec();- self.arrivals.clear();- self.departures.clear();- self.old_previous.clear();- self.sibling_order_is_preserved = self.program.has_following_steps;- for &node in changed {- if !tree.is_live(node)- || self.position_of(Some(node)) != usize::MAX- || tree.tree_scope(node) != TreeScopeID::DOCUMENT- {- continue;- }- for node in tree.preorder(node) {- if self.position_of(Some(node)) != usize::MAX {- continue;- }- let position = if let Some(position) = self.free_slots.pop() {- self.nodes[position] = node;- self.live[position] = true;- position- } else {- self.nodes.push(node);- self.live.push(true);- self.parents.push(usize::MAX);- self.previous.push(usize::MAX);- self.positional.push(0);- self.answers.push(Vec::new());- self.nodes.len() - 1- };- self.positions.insert(node.raw() as usize, position);- self.arrivals.push(position);- if self.arrived.len() <= position / 64 {- self.arrived.resize(position / 64 + 1, 0);- }- self.arrived[position / 64] |= 1 << (position % 64);- touched.push(node);- }- }- touched.sort_unstable();- touched.dedup();- self.arrivals.sort_unstable();- let mut touched_parents = HashSet::default();- let mut sibling_frontier = HashSet::default();- let mut extra = Vec::new();- for targets in &mut self.geometry_targets {- targets.clear();- }- for &node in &touched {- let position = self.position_of(Some(node));- if position == usize::MAX {- continue;- }- let old_parent = self.parents[position];- if !tree.is_live(node) {- self.live[position] = false;- self.departures.push(position);- extra.push(node);- if old_parent != usize::MAX {- touched_parents.insert(old_parent);- }- continue;- }- let parent = self.position_of(tree.parent(node));- let previous = self.position_of(tree.previous_element_sibling(node));- if parent != old_parent {- if old_parent != usize::MAX {- self.sibling_order_is_preserved = false;- }- self.geometry_targets[0].push(position);- if old_parent != usize::MAX {- let descendants: Vec<_> = tree.preorder(node).map(|node| self.position_of(Some(node))).collect();- self.geometry_targets[1].extend(descendants);- }- if old_parent != usize::MAX {- touched_parents.insert(old_parent);- }- if parent != usize::MAX {- touched_parents.insert(parent);- }- }- if parent != old_parent || previous != self.previous[position] {- if self.program.has_following_steps {- self.old_previous.push((position, self.previous[position]));- }- self.geometry_targets[2].push(position);- sibling_frontier.insert(position);- if parent != usize::MAX {- touched_parents.insert(parent);- }- }- self.parents[position] = parent;- self.previous[position] = previous;- }- if self.sibling_order_is_preserved {- self.sibling_order_is_preserved = self.old_previous.iter().all(|&(position, mut previous)| {- if has_bit(&self.arrived, position) {- return true;- }- // Departed slots still hold their old links. Arrivals hold only current links.- // Removing both from the comparison leaves the order of retained siblings.- while previous != usize::MAX && !self.live[previous] {- previous = self.previous[previous];- }- let mut current_previous = self.previous[position];- while current_previous != usize::MAX && has_bit(&self.arrived, current_previous) {- current_previous = self.previous[current_previous];- }- previous == current_previous- });- }- let has_positional_tests = !automaton.positional_tests().is_empty();- for &parent in &touched_parents {- if !self.live[parent] || !has_positional_tests {- continue;- }- extra.push(self.nodes[parent]);- for node in tree.children(self.nodes[parent]) {- let position = self.position_of(Some(node));- assert_ne!(position, usize::MAX);- let bits = evaluation.positional_bits(node, counters).unwrap();- if bits != self.positional[position] {- extra.push(node);- }- }- }- if self.program.has_following_steps && !self.sibling_order_is_preserved {- for parent in touched_parents {- if !self.live[parent] {- continue;- }- let mut follows_frontier = false;- for node in tree.children(self.nodes[parent]) {- let position = self.position_of(Some(node));- follows_frontier |= sibling_frontier.contains(&position);- if follows_frontier {- self.geometry_targets[3].push(position);- }- }- }- }- extra.extend(self.arrivals.iter().map(|&position| self.nodes[position]));- extra- }-- // Inserting nodes cannot remove a following-sibling witness. When retained siblings keep- // their order, only a removed witness can change this context, and only until another old- // witness survives. New memberships are propagated separately through the current tree.- fn following_geometry_changes(- &self,- automaton: &PrefixAutomaton,- old_evaluation: &mut PrefixEvaluation<'_, '_>,- ) -> HashMap<usize, Vec<usize>> {- let mut result: HashMap<usize, Vec<usize>> = HashMap::default();- if !self.sibling_order_is_preserved {- return result;- }- let mut removed_steps = Vec::new();- for &(frontier, old_previous) in &self.old_previous {- if has_bit(&self.arrived, frontier) {- continue;- }- removed_steps.clear();- let mut removed = old_previous;- while removed != usize::MAX && !self.live[removed] {- let row = old_evaluation.row_of(self.nodes[removed]).unwrap();- row.facts.for_each_dispatch_key(row.row, false, |key| {- if let Some(compounds) = self.program.compounds_for_key(&key) {- for compound in compounds {- for step in self.program.steps_for_compound(compound) {- if self.matches[step].contains(removed)- && automaton- .outputs_for(&automaton.steps[step])- .iter()- .any(|output| matches!(output.kind, PrefixOutputKind::FollowingSibling))- {- removed_steps.push(step);- }- }- }- }- });- removed = self.previous[removed];- }- removed_steps.sort_unstable();- removed_steps.dedup();- for &step in &removed_steps {- let members = &self.matches[step];- let mut previous = self.previous[frontier];- while previous != usize::MAX && !members.contains(previous) {- previous = self.previous[previous];- }- if previous != usize::MAX {- continue;- }- let mut node = Some(self.nodes[frontier]);- while let Some(current) = node {- let position = self.position_of(Some(current));- for output in automaton.outputs_for(&automaton.steps[step]) {- // Newly matching local predicates seed their own step changes below.- // Geometry only needs the candidates which matched before this batch.- if matches!(output.kind, PrefixOutputKind::FollowingSibling)- && self.compound_matches[automaton.steps[output.target as usize].compound.0 as usize]- .contains(position)- {- result.entry(output.target as usize).or_default().push(position);- }- }- if members.contains(position) {- break;- }- node = old_evaluation.tree.next_element_sibling(current);- }- }- }- result- }-- pub(in crate::css::style) fn update(- &mut self,- automaton: &PrefixAutomaton,- evaluation: &mut PrefixEvaluation<'_, '_>,- old_evaluation: &mut PrefixEvaluation<'_, '_>,- changed_nodes: &[StyleNodeID],- counters: &Counters,- ) {- counters.bump(Counter::PrefixRelationUpdates);- let following_geometry = self.following_geometry_changes(automaton, old_evaluation);- let mut changed_compounds: HashMap<usize, Vec<usize>> = HashMap::default();- let mut keys = Vec::new();- // Departed nodes need no terminal delta or selector re-evaluation. Remove their positive- // memberships once per affected set; live siblings are handled by the geometry frontier.- // Sharing the dispatch-key lookup across the batch avoids testing every possible local- // compound again for every departed element.- let mut departed_keys = HashSet::default();- for &position in &self.departures {- let node = self.nodes[position];- let row = old_evaluation.row_of(node).unwrap();- row.facts- .for_each_dispatch_key(row.row, self.parents[position] == usize::MAX, |key| {- departed_keys.insert(key);- });- }- for key in &departed_keys {- let Some(compounds) = self.program.compounds_for_key(key) else {- continue;- };- for compound in compounds {- if !self.compound_matches[compound].remove_departed(&self.departures, &self.live) {- continue;- }- for step in self.program.steps_for_compound(compound) {- self.matches[step].remove_departed(&self.departures, &self.live);- }- }- }- // Transaction rows can come from several fact stores. Intern within each store so- // representative row indices are never interpreted in another store's columns.- let mut local_facts: HashMap<*const _, LocalFactStore> = HashMap::default();- let mut next_local_identity = 0_u32;- let mut local_matches: HashMap<u64, bool> = HashMap::default();- self.geometry_targets[0].sort_unstable();- self.geometry_targets[0].dedup();- for &node in changed_nodes {- let Some(&position) = node- .element_index()- .and_then(|index| self.positions.get(index as usize))- else {- continue;- };- if position == usize::MAX || !self.live[position] {- continue;- }- let row = evaluation.row_of(node);- let previous_row = old_evaluation.row_of(node);- let row = row.or(previous_row).unwrap();- let previous_row = previous_row.unwrap_or(row);- let positional = evaluation.positional_bits(node, counters).unwrap();- let positional_changes = self.positional[position] ^ positional;- self.positional[position] = positional;- // Geometry frontiers include retained nodes whose local facts did not change.- // Preserve their predicate memberships, revisiting only changed positional tests.- // A changed parent conservatively requires checking :root again.- let arrived = has_bit(&self.arrived, position);- let local_changed = arrived- || self.geometry_targets[0].binary_search(&position).is_ok()- || !super::rows_have_equal_local_facts_between(- row.facts,- row.row,- previous_row.facts,- previous_row.row,- &automaton.local_fact_dependencies,- );- if !local_changed && positional_changes == 0 {- continue;- }- keys.clear();- let is_root = evaluation.tree.parent(node).is_none();- row.facts.for_each_dispatch_key(row.row, is_root, |key| keys.push(key));- if !(std::ptr::eq(row.facts, previous_row.facts) && row.row == previous_row.row) {- previous_row- .facts- .for_each_dispatch_key(previous_row.row, is_root, |key| keys.push(key));- }- keys.sort_unstable();- keys.dedup();- let store = std::ptr::from_ref(row.facts);- let facts = local_facts.entry(store).or_insert_with(LocalFactStore::new);- let identity = facts.interner.intern(- &mut facts.representatives,- row.facts,- row.row,- &automaton.local_fact_dependencies,- counters,- ) as usize;- let identity = facts.dense_identity(identity, &mut next_local_identity);- for key in &keys {- let Some(compounds) = self.program.compounds_for_key(key) else {- continue;- };- for index in compounds {- let compound = &automaton.compounds[index];- if !local_changed {- match &compound.predicate {- PrefixPredicate::Features {- required_positional_bits,- ..- } if required_positional_bits & positional_changes != 0 => {}- _ => continue,- }- }-- // Positional truth is checked per node; it does not change the local- // predicate result shared by nodes with identical facts.- let positional_matches = match &compound.predicate {- PrefixPredicate::Features {- required_positional_bits,- ..- } => positional & required_positional_bits == *required_positional_bits,- PrefixPredicate::Program { .. } => true,- };- let matched = positional_matches- && *local_matches- .entry(local_match_key(identity, is_root, index))- .or_insert_with(|| {- counters.bump(Counter::PrefixCompoundsEvaluated);- match &compound.predicate {- PrefixPredicate::Features {- feature_start,- feature_len,- ..- } => automaton- .features_for(*feature_start, *feature_len)- .all(|feature| matches_feature(row, feature)),- PrefixPredicate::Program { program, local, .. } => evaluation- .evaluator- .matches_prefix_local(- *program,- evaluation.programs.get(*program),- *local,- node,- counters,- )- .unwrap(),- }- });- if (!arrived && self.compound_matches[index].contains(position)) != matched {- changed_compounds.entry(index).or_default().push(position);- }- }- }- }- for (&index, changes) in &mut changed_compounds {- changes.sort_unstable();- changes.dedup();- let members = &mut self.compound_matches[index];-- members.toggle(changes);- }- let mut geometry_memberships: [HashMap<usize, Vec<usize>>; 4] = std::array::from_fn(|_| HashMap::default());- // An arrival's memberships are all changes of its compounds already, which every step of those compounds- // visits, so geometry only reaches retained nodes, over the axes some step is reached by.- for (axis, targets) in self.geometry_targets.iter().enumerate() {- if !self.program.geometry_axes[axis] {- continue;- }- for &position in targets {- if !self.live[position] || has_bit(&self.arrived, position) {- continue;- }- let node = self.nodes[position];- let row = evaluation.row_of(node).unwrap();- row.facts- .for_each_dispatch_key(row.row, evaluation.tree.parent(node).is_none(), |key| {- if let Some(compounds) = self.program.compounds_for_key(&key) {- for compound in compounds {- if self.compound_matches[compound].contains(position) {- geometry_memberships[axis].entry(compound).or_default().push(position);- }- }- }- });- }- }- for compound in changed_compounds.keys().copied().chain(- geometry_memberships- .iter()- .flat_map(|compounds| compounds.keys().copied()),- ) {- for step in self.program.steps_for_compound(compound) {- if step_is_inert(automaton, &self.matches, step) {- continue;- }- self.pending_steps.insert(self.program.step_ranks[step] as usize);- }- }- for &step in following_geometry.keys() {- if step_is_inert(automaton, &self.matches, step) {- continue;- }- self.pending_steps.insert(self.program.step_ranks[step] as usize);- }- // What each step that ran changed is a run of `changed_positions`, which `step_changes` names by step.- let mut changed_positions = Vec::new();- let mut step_changes: HashMap<usize, std::ops::Range<usize>> = HashMap::default();- let mut terminal_changes = Vec::new();- let mut affected = Vec::new();- let mut descendants = Vec::new();- let mut following_parents = HashSet::default();- let mut walk_truth = std::mem::take(&mut self.walk_truth);- // Which question `walk_truth` answers: whether a position's ancestors, or previous siblings, hold a member of a- // predecessor step. Steps sharing a predecessor and axis share the answers, as a step's members are final once- // it ran and steps run in dependency order.- let mut walk_truth_question: Option<(usize, u8)> = None;- let mut ancestor_chain = Vec::new();- // Every local change is seeded before evaluation. Dependency order ensures that a step- // runs once, after all changes to its predecessor, and only propagates a changed result.- while let Some(rank) = self.pending_steps.pop_first() {- let QueuedStep {- step: step_index,- axis,- compound: compound_index,- predecessor,- } = self.program.queue[rank];- let (step_index, compound_index) = (step_index as usize, compound_index as usize);- let predecessor = (predecessor != u32::MAX).then_some(predecessor as usize);- let first_change = changed_positions.len();- if predecessor.is_some_and(|predecessor| self.matches[predecessor].is_empty()) {- // No predecessor witness can satisfy any outgoing combinator. Remove the old- // matches directly without evaluating local predicates or changed geometry.- self.matches[step_index].drain_into(&mut changed_positions);- } else {- let predecessor_changes = predecessor- .and_then(|predecessor| step_changes.get(&predecessor))- .map_or(&[][..], |run| &changed_positions[run.clone()]);- let geometry = match axis {- PrefixOutputKind::Child => geometry_memberships[0]- .get(&compound_index)- .map_or(&[][..], Vec::as_slice),- PrefixOutputKind::Descendant => geometry_memberships[1]- .get(&compound_index)- .map_or(&[][..], Vec::as_slice),- PrefixOutputKind::NextSibling => geometry_memberships[2]- .get(&compound_index)- .map_or(&[][..], Vec::as_slice),- PrefixOutputKind::FollowingSibling => {- if self.sibling_order_is_preserved {- following_geometry.get(&step_index).map_or(&[][..], Vec::as_slice)- } else {- geometry_memberships[3]- .get(&compound_index)- .map_or(&[][..], Vec::as_slice)- }- }- _ => &[],- };- let compound_changes = changed_compounds.get(&compound_index).map_or(&[][..], Vec::as_slice);- if compound_changes.is_empty() && predecessor_changes.is_empty() && geometry.is_empty() {- continue;- }- let candidates = &self.compound_matches[compound_index];- affected.clear();- affected.extend_from_slice(compound_changes);- affected.extend_from_slice(geometry);- if !predecessor_changes.is_empty() {- match axis {- PrefixOutputKind::Child => {- for &source in predecessor_changes {- for child in evaluation.tree.children(self.nodes[source]) {- let position = self.positions[child.element_index().unwrap() as usize];- if candidates.contains(position) {- affected.push(position);- }- }- }- }- PrefixOutputKind::NextSibling => {- for &source in predecessor_changes {- if let Some(next) = evaluation.tree.next_element_sibling(self.nodes[source]) {- let position = self.positions[next.element_index().unwrap() as usize];- if candidates.contains(position) {- affected.push(position);- }- }- }- }- PrefixOutputKind::Descendant => {- // Enumerate a small changed subtree directly. If it is larger than- // the candidate set, test those candidates against the changed roots.- // The bound is the other join input's size, not a tuned batch cutoff.- descendants.clear();- let mut complete = true;- 'sources: for &source in predecessor_changes {- if !self.live[source] {- continue;- }- for node in evaluation.tree.preorder(self.nodes[source]).skip(1) {- if descendants.len() == candidates.len() {- complete = false;- break 'sources;- }- descendants.push(self.position_of(Some(node)));- }- }- if complete {- affected.extend(- descendants- .iter()- .copied()- .filter(|&position| candidates.contains(position)),- );- } else {- walk_truth.clear();- walk_truth_question = None;- for position in candidates.iter() {- ancestor_chain.clear();- let mut source = self.parents[position];- let mut found = false;- while source != usize::MAX {- if predecessor_changes.binary_search(&source).is_ok() {- found = true;- break;- }- if let Some(truth) = walk_truth.get(source) {- found = truth;- break;- }- ancestor_chain.push(source);- source = self.parents[source];- }- for &source in &ancestor_chain {- walk_truth.insert(source, found);- }- if found {- affected.push(position);- }- }- }- }- PrefixOutputKind::FollowingSibling => {- following_parents.clear();- for &source in predecessor_changes {- if self.parents[source] != usize::MAX {- following_parents.insert(self.parents[source]);- }- }- for &parent in &following_parents {- let mut follows_source = false;- for node in evaluation.tree.children(self.nodes[parent]) {- let position = self.position_of(Some(node));- if follows_source && candidates.contains(position) {- affected.push(position);- }- follows_source |= predecessor_changes.binary_search(&position).is_ok();- }- }- }- _ => unreachable!(),- }- }- // NB: Each source of `affected` is in position order, which the stable sort merges as runs.- affected.sort();- affected.dedup();- if affected.is_empty() {- continue;- }- let question = predecessor.map(|predecessor| (predecessor, axis as u8));- if question.is_none() || question != walk_truth_question {- walk_truth.clear();- walk_truth_question = question;- }- for &position in &affected {- // A step runs once per update, so what it held is what it held before, which no arrival is in.- let previously_matched =- !has_bit(&self.arrived, position) && self.matches[step_index].contains(position);- let mut matched = candidates.contains(position);- if matched && let Some(predecessor) = predecessor {- let predecessor = &self.matches[predecessor];- let contains = |position| predecessor.contains(position);- matched = match axis {- PrefixOutputKind::Child | PrefixOutputKind::NextSibling => {- let source = if matches!(axis, PrefixOutputKind::Child) {- self.parents[position]- } else {- self.previous[position]- };- source != usize::MAX && contains(source)- }- PrefixOutputKind::Descendant => {- ancestor_chain.clear();- let mut current = self.parents[position];- let mut found = false;- while current != usize::MAX {- if contains(current) {- found = true;- break;- }- if let Some(truth) = walk_truth.get(current) {- found = truth;- break;- }- ancestor_chain.push(current);- current = self.parents[current];- }- for &ancestor in &ancestor_chain {- walk_truth.insert(ancestor, found);- }- found- }- PrefixOutputKind::FollowingSibling => {- ancestor_chain.clear();- let mut source = self.previous[position];- let mut found = false;- while source != usize::MAX {- if contains(source) {- found = true;- break;- }- if let Some(truth) = walk_truth.get(source) {- found = truth;- break;- }- ancestor_chain.push(source);- source = self.previous[source];- }- for &source in &ancestor_chain {- walk_truth.insert(source, found);- }- found- }- _ => unreachable!(),- };- }- if previously_matched != matched {- changed_positions.push(position);- }- }- let members = &mut self.matches[step_index];-- members.toggle(&changed_positions[first_change..]);- }- let changes = first_change..changed_positions.len();- if changes.is_empty() {- counters.bump(Counter::PrefixRelationStops);- continue;- }- for successor in automaton.outputs_for(&automaton.steps[step_index]) {- match successor.kind {- PrefixOutputKind::UniqueTerminal | PrefixOutputKind::SharedTerminal => {- for &position in &changed_positions[changes.clone()] {- terminal_changes.push((position, EntryID(successor.target)));- }- }- _ => {- let successor = successor.target as usize;- self.pending_steps.insert(self.program.step_ranks[successor] as usize);- }- }- }- step_changes.insert(step_index, changes);- }- // NB: Each step's changes are in position order, which the stable sort merges as runs.- terminal_changes.sort();- terminal_changes.dedup();- self.changed_answers.clear();- let mut old = Vec::new();- let mut cursor = 0;- while cursor < terminal_changes.len() {- let position = terminal_changes[cursor].0;- old.clear();- old.extend_from_slice(&self.answers[position]);- while cursor < terminal_changes.len() && terminal_changes[cursor].0 == position {- let entry = terminal_changes[cursor].1;- // Multiple paths can produce the same terminal. Losing one path changes the- // selector answer only when no other path still matches this element.- let matched = self.program.terminal_steps[&entry]- .iter()- .any(|&step| self.matches[step].contains(position));- let entries = &mut self.answers[position];- match (entries.binary_search(&entry), matched) {- (Ok(index), false) => {- entries.remove(index);- }- (Err(index), true) => {- entries.insert(index, entry);- }- _ => {}- }- cursor += 1;- }- if self.live[position] && old != self.answers[position] {- self.changed_answers.push((- self.nodes[position],- std::mem::take(&mut old),- self.answers[position].clone(),- ));- }- }- for targets in &mut self.geometry_targets {- targets.clear();- }- for &position in &self.departures {- self.answers[position].clear();- self.positions[self.nodes[position].raw() as usize] = usize::MAX;- self.parents[position] = usize::MAX;- self.previous[position] = usize::MAX;- self.positional[position] = 0;- self.free_slots.push(position);- }- self.departures.clear();- self.old_previous.clear();- for &position in &self.arrivals {- self.arrived[position / 64] = 0;- }- self.walk_truth = walk_truth;-- self.verify_answers(evaluation);- }-}--impl PrefixAutomaton {- pub(in crate::css::style) fn supports_relation(&self, tree: &StyleNodeTree, root: StyleNodeID) -> bool {- !self.steps.is_empty()- && tree.parent(root).is_none()- && tree- .preorder(root)- .all(|node| tree.tree_scope(node) == TreeScopeID::DOCUMENT)- }-- pub(in crate::css::style) fn build_relation(- &self,- evaluation: &mut PrefixEvaluation<'_, '_>,- root: StyleNodeID,- counters: &Counters,- ) -> PrefixRelation {- counters.bump(Counter::PrefixRelationBuilds);- let tree = evaluation.tree;- let nodes: Vec<_> = tree.preorder(root).collect();- let count = nodes.len();- let mut positions = Column::new(|| usize::MAX);- let mut rows = Vec::with_capacity(count);- for (position, &node) in nodes.iter().enumerate() {- positions.insert(node.element_index().unwrap() as usize, position);- rows.push(evaluation.row_of(node).unwrap());- }- let position_of = |node: Option<StyleNodeID>| {- node.and_then(|node| node.element_index())- .map_or(usize::MAX, |index| positions[index as usize])- };- let parents: Vec<_> = nodes.iter().map(|&node| position_of(tree.parent(node))).collect();- let previous: Vec<_> = nodes- .iter()- .map(|&node| position_of(tree.previous_element_sibling(node)))- .collect();- let mut subtree_ends: Vec<_> = (1..=count).collect();- for position in (0..count).rev() {- if parents[position] != usize::MAX {- subtree_ends[parents[position]] = subtree_ends[parents[position]].max(subtree_ends[position]);- }- }- let mut candidates: HashMap<DispatchKey, Vec<usize>> = HashMap::default();- for compound in self.compounds.iter() {- candidates.entry(compound.dispatch_key).or_default();- }- for (position, row) in rows.iter().enumerate() {- row.facts- .for_each_dispatch_key(row.row, tree.parent(nodes[position]).is_none(), |key| {- if let Some(candidates) = candidates.get_mut(&key)- && candidates.last() != Some(&position)- {- candidates.push(position);- }- });- }- let positional: Vec<_> = nodes- .iter()- .map(|&node| evaluation.positional_bits(node, counters).unwrap())- .collect();- // Local predicates read the same facts for every member of a fact cohort. Reuse their- // answers while building memberships, as scalar prefix transitions already do. Keep- // document-root identity in the key and check positional truth separately per node.- let mut local_facts = HashMap::default();- let mut identities = HashMap::default();- let local_fact_keys: Vec<_> = rows- .iter()- .enumerate()- .map(|(position, row)| {- let store = std::ptr::from_ref(row.facts);- let (interner, representatives) = local_facts- .entry(store)- .or_insert_with(|| (super::LocalFactInterner::new(), Default::default()));- let identity = interner.intern(- representatives,- row.facts,- row.row,- &self.local_fact_dependencies,- counters,- );- let next = identities.len();- *identities- .entry((store, identity, parents[position] == usize::MAX))- .or_insert(next)- })- .collect();- let mut local_matches = vec![None; identities.len()];- let mut compound_matches = Vec::with_capacity(self.compounds.len());- for compound in self.compounds.iter() {- // Dispatch postings already prove universal, ID, and class predicates. With- // no additional local or positional test, the posting is the membership set.- if let PrefixPredicate::Features {- feature_start,- feature_len,- required_positional_bits: 0,- } = &compound.predicate- && self- .features_for(*feature_start, *feature_len)- .all(|feature| match feature {- super::FeatureTest::AnyElement => true,- super::FeatureTest::Id(id) => compound.dispatch_key == DispatchKey::Id(id),- super::FeatureTest::Class(class) => compound.dispatch_key == DispatchKey::Class(class),- _ => false,- })- {- compound_matches.push(candidates[&compound.dispatch_key].clone());- continue;- }- local_matches.fill(None);- let matched: Vec<_> = candidates[&compound.dispatch_key]- .iter()- .copied()- .filter(|&position| {- if let PrefixPredicate::Features {- required_positional_bits,- ..- } = &compound.predicate- && positional[position] & required_positional_bits != *required_positional_bits- {- return false;- }- *local_matches[local_fact_keys[position]].get_or_insert_with(|| {- counters.bump(Counter::PrefixCompoundsEvaluated);- let row = rows[position];- match &compound.predicate {- PrefixPredicate::Features {- feature_start,- feature_len,- ..- } => self- .features_for(*feature_start, *feature_len)- .all(|feature| matches_feature(row, feature)),- PrefixPredicate::Program { program, local, .. } => evaluation- .evaluator- .matches_prefix_local(- *program,- evaluation.programs.get(*program),- *local,- nodes[position],- counters,- )- .unwrap(),- }- })- })- .collect();- compound_matches.push(matched);- }- let mut matches: Vec<Vec<u32>> = vec![Vec::new(); self.steps.len()];- let mut queue: Vec<_> = (0..self.steps.len())- .filter(|&step| self.predecessor_of(PrefixStepID(step as u32)).is_none())- .map(|step| (step, PrefixOutputKind::UniqueTerminal))- .collect();- let mut cursor = 0;- let mut selected = Vec::new();- let mut first_following = vec![usize::MAX; count];- let mut following_parents = Vec::new();- let mut output: Vec<Vec<EntryID>> = vec![Vec::new(); count];- while cursor < queue.len() {- let (step_index, axis) = queue[cursor];- cursor += 1;- let step = &self.steps[step_index];- let candidates = &compound_matches[step.compound.0 as usize];- selected.clear();- if let Some(predecessor) = self.predecessor_of(PrefixStepID(step_index as u32)) {- let predecessor = &matches[predecessor.0 as usize];- match axis {- _ if predecessor.is_empty() => {}- PrefixOutputKind::Child | PrefixOutputKind::NextSibling => {- let sources = if matches!(axis, PrefixOutputKind::Child) {- &parents- } else {- &previous- };- selected.extend(candidates.iter().copied().filter(|&position| {- let source = sources[position];- source != usize::MAX && predecessor.binary_search(&(source as u32)).is_ok()- }));- }- PrefixOutputKind::Descendant => {- let mut sources = predecessor.iter().map(|&position| position as usize).peekable();- let mut covered_end = 0;- for &position in candidates {- while let Some(&source) = sources.peek() {- if source >= position {- break;- }- covered_end = covered_end.max(subtree_ends[source]);- sources.next();- }- if position < covered_end {- selected.push(position);- }- }- }- PrefixOutputKind::FollowingSibling => {- following_parents.clear();- for source in predecessor.iter().map(|&position| position as usize) {- let parent = parents[source];- if parent != usize::MAX && first_following[parent] == usize::MAX {- first_following[parent] = source;- following_parents.push(parent);- }- }- selected.extend(candidates.iter().copied().filter(|&position| {- let parent = parents[position];- parent != usize::MAX && first_following[parent] < position- }));- for &parent in &following_parents {- first_following[parent] = usize::MAX;- }- }- _ => unreachable!(),- }- } else {- selected.extend_from_slice(candidates);- }- matches[step_index].extend(selected.iter().map(|&position| position as u32));- for successor in self.outputs_for(step) {- match successor.kind {- PrefixOutputKind::UniqueTerminal | PrefixOutputKind::SharedTerminal => {- for &position in &selected {- output[position].push(EntryID(successor.target));- }- }- axis => queue.push((successor.target as usize, axis)),- }- }- }- assert_eq!(queue.len(), self.steps.len());- for entries in &mut output {- entries.sort_unstable();- entries.dedup();- }- let program = std::sync::Arc::clone(self.relation_program.get_or_init(|| {- // Pack compounds with the same dispatch key into one immutable array. Preserve their- // original order within each key without retaining a separate allocation for each list.- let mut keyed_compounds: Vec<u32> = (0..self.compounds.len())- .map(|index| u32::try_from(index).expect("prefix compound space exhausted"))- .collect();- keyed_compounds.sort_unstable_by_key(|&index| (self.compounds[index as usize].dispatch_key, index));- let mut compounds_by_key: HashMap<DispatchKey, std::ops::Range<u32>> = HashMap::default();- for (position, &index) in keyed_compounds.iter().enumerate() {- let position = u32::try_from(position).expect("prefix compound space exhausted");- compounds_by_key- .entry(self.compounds[index as usize].dispatch_key)- .or_insert(position..position)- .end = position.checked_add(1).expect("prefix compound space exhausted");- }- compounds_by_key.shrink_to_fit();- let mut terminal_steps: HashMap<EntryID, SmallVec<[usize; 1]>> = HashMap::default();- for (index, step) in self.steps.iter().enumerate() {- for output in self.outputs_for(step) {- if matches!(- output.kind,- PrefixOutputKind::UniqueTerminal | PrefixOutputKind::SharedTerminal- ) {- terminal_steps.entry(EntryID(output.target)).or_default().push(index);- }- }- }- let mut step_ranks = vec![0; self.steps.len()];- let mut compound_step_offsets = vec![0_u32; self.compounds.len() + 1];- for step in &self.steps {- let count = &mut compound_step_offsets[step.compound.0 as usize + 1];- *count = count.checked_add(1).expect("prefix step space exhausted");- }- for index in 1..compound_step_offsets.len() {- compound_step_offsets[index] = compound_step_offsets[index]- .checked_add(compound_step_offsets[index - 1])- .expect("prefix step space exhausted");- }- let mut positions = compound_step_offsets[..self.compounds.len()].to_vec();- let mut compound_steps = vec![0; self.steps.len()];- for (rank, &(step, _)) in queue.iter().enumerate() {- step_ranks[step] = u32::try_from(rank).expect("prefix step space exhausted");- let position = &mut positions[self.steps[step].compound.0 as usize];- compound_steps[*position as usize] = u32::try_from(step).expect("prefix step space exhausted");- *position += 1;- }- let has_following_steps = queue- .iter()- .any(|(_, axis)| matches!(axis, PrefixOutputKind::FollowingSibling));- let mut geometry_axes = [false; 4];- for (_, axis) in &queue {- match axis {- PrefixOutputKind::Child => geometry_axes[0] = true,- PrefixOutputKind::Descendant => geometry_axes[1] = true,- PrefixOutputKind::NextSibling => geometry_axes[2] = true,- PrefixOutputKind::FollowingSibling => geometry_axes[3] = true,- PrefixOutputKind::UniqueTerminal | PrefixOutputKind::SharedTerminal => {}- }- }- let program = PrefixRelationProgram {- queue: queue- .into_iter()- .map(|(step, axis)| (u32::try_from(step).expect("prefix step space exhausted"), axis))- .map(|(step, axis)| QueuedStep {- step,- axis,- compound: self.steps[step as usize].compound.0,- predecessor: self.step_predecessors[step as usize],- })- .collect::<Box<[_]>>()- .into_vec(),- step_ranks,- compound_step_offsets,- compound_steps,- has_following_steps,- geometry_axes,- compounds_by_key,- keyed_compounds,- terminal_steps,- };- std::sync::Arc::new(program)- }));- let relation = PrefixRelation {- program,- nodes,- positions,- parents,- previous,- live: vec![true; count],- free_slots: Vec::new(),- departures: Vec::new(),- compound_matches: compound_matches- .into_iter()- .map(PositionSet::from_iter)- .collect::<Box<[_]>>()- .into_vec(),- matches: matches- .into_iter()- .map(|positions| positions.into_iter().map(|position| position as usize).collect())- .collect::<Box<[_]>>()- .into_vec(),- walk_truth: PrefixWalkMemo::default(),- pending_steps: PendingPrefixSteps::new(self.steps.len()),- positional,- geometry_targets: std::array::from_fn(|_| Vec::new()),- old_previous: Vec::new(),- sibling_order_is_preserved: false,- answers: output,- changed_answers: Vec::new(),- arrivals: Vec::new(),- arrived: Vec::new(),- handled_routing_keys: HashMap::default(),- };-- relation.verify_answers(evaluation);- relation- }-}--// Walks only memoize stable relation slots. Reuse their storage across selector steps-// and transactions; a fresh generation separates queries without clearing or hashing-// the visited nodes. The column grows only when a walk records a result.-struct PrefixWalkMemo {- stamps: Column<u64>,- generation: u64,-}--impl Default for PrefixWalkMemo {- fn default() -> Self {- Self {- stamps: Column::default(),- generation: 2,- }- }-}--impl PrefixWalkMemo {- fn clear(&mut self) {- self.generation = self- .generation- .checked_add(2)- .expect("prefix walk generation overflowed");- }-- fn get(&self, position: usize) -> Option<bool> {- let stamp = *self.stamps.get(position)?;- (stamp & !1 == self.generation).then_some(stamp & 1 != 0)- }-- fn insert(&mut self, position: usize, truth: bool) {- self.stamps.insert(position, self.generation | u64::from(truth));- }-}--/// One transaction's local fact identities for one fact store, numbered densely across every-/// store so that a memo entry names a compound result with a single integer.-struct LocalFactStore {- interner: super::LocalFactInterner,- representatives: super::super::intern_table::InternTable<super::LocalFactSlot, (u32, u32)>,- dense: Vec<u32>,-}--impl LocalFactStore {- fn new() -> Self {- Self {- interner: super::LocalFactInterner::new(),- representatives: Default::default(),- dense: Vec::new(),- }- }-- fn dense_identity(&mut self, identity: usize, next: &mut u32) -> u32 {- if self.dense.len() <= identity {- self.dense.resize(identity + 1, u32::MAX);- }- if self.dense[identity] == u32::MAX {- self.dense[identity] = *next;- *next += 1;- }- self.dense[identity]- }-}--/// Name one compound's result for one local fact identity. Hashing a single integer costs less-/// than hashing the store, identity, root flag and compound the memo used to carry separately.-fn local_match_key(identity: u32, is_root: bool, compound: usize) -> u64 {- debug_assert!(compound < 1 << 31, "compound identity space exhausted");- (u64::from(identity) << 32) | (u64::from(is_root) << 31) | compound as u64-}--// A step with no predecessor witness can match nothing, so one which also holds no members has-// nothing to add and nothing to remove. Leaving it out of the queue is free: a predecessor that-// gains members later in the same update queues its successors through the automaton's outputs,-// and the queued step still reads its own compound and geometry changes when it runs.-fn step_is_inert(automaton: &PrefixAutomaton, matches: &[PositionSet], step: usize) -> bool {- matches[step].is_empty()- && automaton- .predecessor_of(PrefixStepID(step as u32))- .is_some_and(|predecessor| matches[predecessor.0 as usize].is_empty())-}--// Merge a batch of membership flips once. Repeated Vec::insert/remove would move the-// unaffected tail once per changed element, multiplying batch size by the set's population.-fn toggle_listed(members: &mut Vec<u32>, changes: &[usize]) {- let (lowest, highest) = match *changes {- [] => return,- [position] => {- let position = position_u32(position);- match members.binary_search(&position) {- Ok(index) => {- members.remove(index);- }- Err(index) => members.insert(index, position),- }- return;- }- [lowest, .., highest] => (position_u32(lowest), position_u32(highest)),- };- let first = members.partition_point(|&position| position < lowest);- let end = members.partition_point(|&position| position <= highest);- let removed_prefix = members[first..end]- .iter()- .zip(changes)- .take_while(|&(member, position)| *member == position_u32(*position))- .count();- let mut cursor = first + removed_prefix;- let changes = &changes[removed_prefix..];- let mut replacement = Vec::with_capacity(end - cursor + changes.len());- for &position in changes {- let position = position_u32(position);- while cursor < end && members[cursor] < position {- replacement.push(members[cursor]);- cursor += 1;- }- if cursor < end && members[cursor] == position {- cursor += 1;- } else {- replacement.push(position);- }- }- replacement.extend_from_slice(&members[cursor..end]);- members.splice(first..end, replacement);-}--// Each upper bit names a nonempty word in the level below. Popping drains the marks, so-// subsequent transactions neither clear the whole program nor scan empty rank ranges.-struct PendingPrefixSteps {- levels: Vec<Vec<u64>>,-}--impl PendingPrefixSteps {- fn new(mut count: usize) -> Self {- let mut levels = Vec::new();- loop {- count = count.max(1).div_ceil(u64::BITS as usize);- levels.push(vec![0; count]);- if count == 1 {- return Self { levels };- }- }- }-- fn insert(&mut self, mut rank: usize) {- for level in &mut self.levels {- let word = &mut level[rank / u64::BITS as usize];- let was_empty = *word == 0;- *word |= 1 << (rank % u64::BITS as usize);- if !was_empty {- break;- }- rank /= u64::BITS as usize;- }- }-- fn pop_first(&mut self) -> Option<usize> {- if self.levels.last().unwrap()[0] == 0 {- return None;- }- let mut rank = 0;- for level in self.levels.iter().rev() {- rank = rank * u64::BITS as usize + level[rank].trailing_zeros() as usize;- }- let result = rank;- for level in &mut self.levels {- let word = &mut level[rank / u64::BITS as usize];- *word &= !(1 << (rank % u64::BITS as usize));- if *word != 0 {- break;- }- rank /= u64::BITS as usize;- }- Some(result)- }-}--#[cfg(test)]-mod tests {- use super::{PendingPrefixSteps, PositionSet, PrefixWalkMemo, toggle_listed};- use std::collections::BTreeSet;-- fn is_bitmap(set: &PositionSet) -> bool {- matches!(set, PositionSet::Bits { .. })- }-- #[test]- fn ordered_prefix_membership_queries_preserve_gaps_duplicates_and_boundary_slots() {- for slots in [- Vec::new(),- vec![0],- vec![u32::MAX],- (0..256).step_by(3).collect(),- (0..10_000).step_by(997).collect(),- vec![1, 63, 64, 127, 128, 10_000, u32::MAX],- ] {- let expected: BTreeSet<_> = slots.iter().copied().collect();- let members: PositionSet = slots.iter().map(|&slot| slot as usize).collect();- assert!(members.iter().eq(slots.iter().map(|&slot| slot as usize)));- for positions in [- Vec::new(),- vec![5000],- vec![usize::MAX],- vec![0, 1, 1, 63, 64, 64, 127, 128, 10_000, u32::MAX as usize, usize::MAX],- (0..10_001).collect(),- ] {- let actual: Vec<_> = positions.iter().map(|&position| members.contains(position)).collect();- let expected: Vec<_> = positions- .iter()- .map(|&position| u32::try_from(position).is_ok_and(|position| expected.contains(&position)))- .collect();- assert_eq!(actual, expected);- }- }- }-- #[test]- fn position_sets_answer_alike_listed_or_as_a_bitmap() {- let mut set = PositionSet::default();- let mut model = BTreeSet::new();- let mut seed = 1_u64;- let mut was_bitmap = false;- let mut was_listed_again = false;- for round in 0..400 {- // Batches grow the set past the bitmap bound, then shrink it back below half of it.- let mut changes = BTreeSet::new();- if round < 200 {- for _ in 0..16 {- seed = seed- .wrapping_mul(6_364_136_223_846_793_005)- .wrapping_add(1_442_695_040_888_963_407);- changes.insert((seed >> 33) as usize % 2_000);- }- } else {- changes.extend(model.iter().copied().step_by(3).take(16));- }- let changes: Vec<_> = changes.into_iter().collect();- set.toggle(&changes);- for &position in &changes {- if !model.remove(&position) {- model.insert(position);- }- }- was_listed_again |= was_bitmap && !is_bitmap(&set);- was_bitmap |= is_bitmap(&set);- assert_eq!(set.len(), model.len());- assert!(set.iter().eq(model.iter().copied()));- assert!((0..2_100).all(|position| set.contains(position) == model.contains(&position)));- }- assert!(was_bitmap && was_listed_again);-- for stride in [1, 97] {- let positions: Vec<usize> = (0..2_000).step_by(stride).collect();- let mut set: PositionSet = positions.iter().copied().collect();- assert_eq!(is_bitmap(&set), stride == 1);- let departed: Vec<_> = positions.iter().copied().step_by(2).collect();- let mut live = vec![true; 2_000];- for &position in &departed {- live[position] = false;- }- assert!(set.remove_departed(&departed, &live));- assert!(!set.remove_departed(&departed, &live));- let kept: Vec<_> = positions.iter().copied().skip(1).step_by(2).collect();- assert_eq!(set.len(), kept.len());- assert!(set.iter().eq(kept.iter().copied()));- let mut drained = Vec::new();- set.drain_into(&mut drained);- assert_eq!(drained, kept);- assert!(set.is_empty() && set.iter().next().is_none());- }- }-- #[test]- fn prefix_walk_memo_separates_true_false_and_unknown_across_queries() {- let mut memo = PrefixWalkMemo::default();- for query in 0..128 {- for position in [0, 63, 64, 128] {- assert_eq!(memo.get(position), None);- let truth = (position + query) % 2 == 0;- memo.insert(position, truth);- assert_eq!(memo.get(position), Some(truth));- memo.insert(position, !truth);- assert_eq!(memo.get(position), Some(!truth));- }- memo.clear();- }- }-- #[test]- fn batched_membership_flips_preserve_the_unchanged_ranges() {- let mut members = vec![1_u32, 3, 5, 7, 9];- toggle_listed(&mut members, &[0, 3, 4, 7, 8]);- assert_eq!(members, [0, 1, 4, 5, 8, 9]);- toggle_listed(&mut members, &[0, 3, 4, 7, 8]);- assert_eq!(members, [1, 3, 5, 7, 9]);- toggle_listed(&mut members, &[1, 3, 5, 7, 9]);- assert!(members.is_empty());- toggle_listed(&mut members, &[2, 4, 6]);- assert_eq!(members, [2, 4, 6]);- }-- #[test]- fn pending_prefix_steps_order_deduplicate_and_drain_across_word_boundaries() {- let mut pending = PendingPrefixSteps::new(65_537);- for _ in 0..3 {- assert_eq!(pending.pop_first(), None);- for rank in [65_536, 4_096, 63, 64, 0, 4_095, 64, 65_535] {- pending.insert(rank);- }- for rank in [0, 63, 64, 4_095, 4_096, 65_535, 65_536] {- assert_eq!(pending.pop_first(), Some(rank));- // A dependency can schedule another step while the queue is draining.- if rank == 64 {- pending.insert(65);- pending.insert(4_095);- assert_eq!(pending.pop_first(), Some(65));- }- }- assert_eq!(pending.pop_first(), None);- }- }-- #[test]- fn empty_memberships_allocate_on_first_use_and_retain_warm_buffers() {- let listed = |set: &PositionSet| match set {- PositionSet::Listed(list) => Some(list.as_ptr()),- _ => None,- };- let mut members = PositionSet::default();- let mut drained = Vec::new();- members.drain_into(&mut drained);- assert!(drained.is_empty());- assert!(!members.remove_departed(&[1], &[true, false]));- members.toggle(&[1, 3]);- assert!(members.iter().eq([1, 3]));- let buffer = listed(&members);- assert!(buffer.is_some(), "a small set is listed");-- members.drain_into(&mut drained);- assert_eq!(drained, [1, 3]);- members.toggle(&[2, 4]);- assert_eq!(listed(&members), buffer);- assert!(members.iter().eq([2, 4]));- }-}diff --git a/Libraries/LibWeb/Rust/src/css/style/program_updates.rs b/Libraries/LibWeb/Rust/src/css/style/program_updates.rsdeleted file mode 100644index 79b9a8b9397..00000000000--- a/Libraries/LibWeb/Rust/src/css/style/program_updates.rs+++ /dev/null@@ -1,1386 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--use super::*;-use crate::css::color_conversion::{RGB, SRGB};-use crate::css::css_string::CssString;-use crate::css::declaration_block;-use crate::css::style_compute::keyword;-use crate::css::style_value::{ColorBase, RetainedStyleValueData, shared_style_value};-use crate::css::value_codes::*;-use std::sync::Arc;--// The context-free form used to identify numeric RGB declarations, so that every spelling of one color names one-// declaration. Other colors still need element, inherited style, or other computation context.-fn canonical_specified_value(value: &StyleValueData) -> Option<Arc<StyleValueData>> {- let StyleValueData::ColorFunction {- color_base,- channel_0,- channel_1,- channel_2,- alpha,- origin_color,- ..- } = value- else {- return None;- };- if !color_base.has_color_type || color_base.color_type != RGB || origin_color.optional_data().is_some() {- return None;- }- let number = |channel: &RetainedStyleValueData| match channel.data() {- StyleValueData::Number { value } => Some(*value),- _ => None,- };- let channels = [number(channel_0)?, number(channel_1)?, number(channel_2)?];- let alpha = match alpha.optional_data() {- None => 1.0,- Some(StyleValueData::Number { value }) => *value,- _ => return None,- };- let number = |value| RetainedStyleValueData::from_arc(shared_style_value(StyleValueData::Number { value }));- // NB: Whole channels, as every hexadecimal and most functional spellings have, stay in the rgb() form, whose- // numbers are shared; any other channel is named in the srgb form.- let whole = channels- .iter()- .all(|&channel| channel.fract() == 0.0 && (0.0..=255.0).contains(&channel));- let (color_type, [channel_0, channel_1, channel_2]) = if whole {- (RGB, channels.map(number))- } else {- (SRGB, channels.map(|value| number(value / 255.0)))- };- Some(Arc::new(StyleValueData::ColorFunction {- color_base: ColorBase {- has_color_type: true,- color_type,- color_syntax: COLOR_SYNTAX_MODERN,- },- channel_0,- channel_1,- channel_2,- alpha: number(alpha),- has_name: false,- name: CssString::none(),- origin_color: RetainedStyleValueData::none(),- }))-}--pub(super) fn declaration_operator(value: &StyleValueData) -> CascadeOperator {- match value {- StyleValueData::Keyword {- keyword: keyword::INHERIT,- } => CascadeOperator::Inherit,- StyleValueData::Keyword {- keyword: keyword::INITIAL,- } => CascadeOperator::Initial,- StyleValueData::Keyword {- keyword: keyword::UNSET,- } => CascadeOperator::Unset,- StyleValueData::Keyword {- keyword: keyword::REVERT,- } => CascadeOperator::Revert,- StyleValueData::Keyword {- keyword: keyword::REVERT_LAYER,- } => CascadeOperator::RevertLayer,- _ => CascadeOperator::Declared,- }-}--impl RetainedState {- pub(crate) fn intern_element_declared_properties(- &mut self,- declarations: &[declaration_block::DeclaredProperty],- ) -> Vec<(DeclaredProperty, RetainedStyleValueData)> {- fn append(- engine: &mut RetainedState,- property: u16,- declaration: &declaration_block::DeclaredProperty,- declarations: &mut Vec<(DeclaredProperty, RetainedStyleValueData)>,- ) {- use crate::css::property_metadata::{longhands_for_shorthand, property_is_shorthand};- // Element declarations decide longhands. Presentation attributes can name shorthands- // whose children are themselves shorthands, so expand the complete property inventory.- if property_is_shorthand(property) && !matches!(&*declaration.value, StyleValueData::Unresolved { .. }) {- for &longhand in longhands_for_shorthand(property) {- append(engine, longhand, declaration, declarations);- }- } else {- let mut value = engine.intern_declared_property(declaration);- value.property = property;- declarations.push((value, RetainedStyleValueData::from_arc(declaration.value.clone())));- }- }- let mut interned = Vec::with_capacity(declarations.len());- for declaration in declarations {- append(self, declaration.property_id, declaration, &mut interned);- }- interned- }-- pub(crate) fn intern_declared_property(- &mut self,- declaration: &declaration_block::DeclaredProperty,- ) -> DeclaredProperty {- let canonical = canonical_specified_value(&declaration.value);- let value = canonical.as_ref().unwrap_or(&declaration.value);- let value = self.intern_specified_value(value);- self.alias_specified_value(&declaration.value, value);- let operator = declaration_operator(&declaration.value);- DeclaredProperty {- property: declaration.property_id,- important: declaration.important,- operator,- value,- }- }-- /// Intern one immutable specified value into the rule program's dense value table.- pub fn intern_specified_value(&mut self, value: &Arc<StyleValueData>) -> SpecifiedValueID {- let (id, reused) = self.specified_values.intern(value);- if reused {- self.counters.bump(Counter::SpecifiedValuesReused);- }- id- }-- /// Register an authored spelling as an alias of its context-free canonical value.- pub fn alias_specified_value(&mut self, value: &Arc<StyleValueData>, id: SpecifiedValueID) {- self.specified_values.alias(value, id);- }-- /// Make every concrete scope resolve its ranked program again. Programs whose sheet and layer- /// dependencies are unchanged remain interned for one invalidation generation, preserving the- /// dispatch and prefix work shared by unaffected scopes.- pub(super) fn invalidate_scope_programs(&mut self) {- for index in 0..self.scope_programs.len() {- if !self.scope_programs[index]- .as_ref()- .is_some_and(|program| program.scope_count == 0)- {- continue;- }- let id = ScopeProgramID(u32::try_from(index).expect("scope program identity space exhausted"));- self.remove_scope_program(id);- }- for program in self.scope_programs.iter_mut().flatten() {- program.scope_count = 0;- }- self.scope_program_by_scope.clear();- }-- /// Drop the ranked program for one tree scope while leaving equivalent scopes' shared program- /// and prefix caches alive. Callers without the replacement document sheet order conservatively- /// invalidate every shadow scope because they cannot distinguish author-only changes.- pub(super) fn invalidate_scope_program(&mut self, tree_scope: TreeScopeID) {- if tree_scope == TreeScopeID::DOCUMENT {- self.invalidate_scope_programs();- return;- }- self.invalidate_concrete_scope_program(tree_scope);- }-- fn invalidate_concrete_scope_program(&mut self, tree_scope: TreeScopeID) {- let Some((_, program)) = self- .scope_program_by_scope- .get_mut(tree_scope.0 as usize)- .and_then(Option::take)- else {- return;- };- self.release_scope_program(program);- }-- /// Drop only concrete scope programs that consume `sheet`. The key contains the effective- /// document sheets as well as locally attached sheets, so this also reaches shadow scopes that- /// inherit a changed document sheet without scanning the DOM's attachment topology again.- pub(super) fn invalidate_scope_programs_for_sheet(&mut self, sheet: SheetID) {- for index in 0..self.scope_program_by_scope.len() {- let Some((_, program)) = self.scope_program_by_scope[index] else {- continue;- };- if self- .scope_program(program)- .key- .sheets- .iter()- .any(|&(candidate, _)| candidate == sheet)- {- let scope = TreeScopeID(u32::try_from(index).expect("tree scope identity space exhausted"));- self.invalidate_concrete_scope_program(scope);- }- }- }-- pub(super) fn settle_program(&mut self) {}-- #[must_use]- pub(super) fn fact_value_is_reconstructible(key: LocalFeatureKey, value: FeatureValue) -> bool {- match key {- LocalFeatureKey::Class(_)- | LocalFeatureKey::Part(_)- | LocalFeatureKey::CustomState(_)- | LocalFeatureKey::Emptiness => {- matches!(value, FeatureValue::Absent | FeatureValue::Present)- }- LocalFeatureKey::TagName- | LocalFeatureKey::FoldedTagName- | LocalFeatureKey::Id- | LocalFeatureKey::Attribute(_)- | LocalFeatureKey::PartExposure- | LocalFeatureKey::Language- | LocalFeatureKey::Directionality => matches!(value, FeatureValue::Absent | FeatureValue::Atom(_)),- LocalFeatureKey::HeadingLevel => matches!(value, FeatureValue::Number(_)),- LocalFeatureKey::ArrivingFacts => false,- }- }-- pub(super) fn input_routes_to_prefix(&self, input: &NormalizedInput) -> bool {- let route_is_prefix = |key| {- self.routing- .routes_for(key)- .iter()- .any(|&route| self.routing.entry_has_prefix_chain(route))- };- if routing_keys_for_input(input).into_iter().any(route_is_prefix) {- return true;- }- let InputKey::LocalFeature(_, LocalFeatureKey::Attribute(name)) = input.key else {- return false;- };- self.facts- .attribute_name_keys(name)- .map(RoutingKey::AttributeName)- .any(route_is_prefix)- }-- /// Classify the local facts and relations available on both sides of this transaction.- pub(super) fn classify_transaction_facts(- &self,- transaction: &StyleTransaction,- arrival_regions: &ImpactRegions,- ) -> TransactionFactClassification {- let coarsened = transaction.has_coarsened_markers();- let mut prefix_available = !coarsened;- let retained_truth_available = !coarsened- && transaction.inputs.iter().all(|input| {- matches!(- input.key,- InputKey::LocalFeature(_, LocalFeatureKey::ArrivingFacts)- | InputKey::LocalFeature(..)- | InputKey::State(..)- | InputKey::RuleField(_, RuleField::Activation | RuleField::Declarations | RuleField::Layer)- | InputKey::SheetAttachment(..)- | InputKey::SheetActivation(_)- | InputKey::CustomPropertyRegistration(_)- | InputKey::CascadeTopology(_)- | InputKey::ElementDeclaration(..)- | InputKey::ElementStyleInput(..)- ) && !matches!(input.key, InputKey::LocalFeature(_, LocalFeatureKey::ArrivingFacts))- });- let mut roots = Vec::new();- let mut departures = Vec::new();- let mut sibling_frontier = Vec::new();- let mut tree_relations_changed = false;- let arrived = |node| arrival_regions.is_covered_by_subtree(ImpactRegion::Node(node), &self.tree);-- for input in &transaction.inputs {- if prefix_available {- match (input.key, input.old, input.new) {- (InputKey::TreeRelations(node), InputValue::TreeRelations(old), InputValue::TreeRelations(new)) => {- tree_relations_changed = true;- match (old, new) {- (None, Some(new)) => {- sibling_frontier.push(node);- sibling_frontier.extend(new.next_element_sibling);- }- (Some(old), None) => {- departures.push(node);- sibling_frontier.extend(old.next_element_sibling);- }- (None, None) => {}- (Some(old), Some(new)) if old.parent == new.parent && old.tree_scope == new.tree_scope => {- sibling_frontier.push(node);- sibling_frontier.extend(old.next_element_sibling);- sibling_frontier.extend(new.next_element_sibling);- }- _ => prefix_available = false,- }- }- (- InputKey::LocalFeature(_, LocalFeatureKey::ArrivingFacts)- | InputKey::ElementDeclaration(..)- | InputKey::ElementStyleInput(..),- _,- _,- ) => {}- (key, _, _)- if key- .program_tree_scope()- .is_some_and(|scope| scope != TreeScopeID::DOCUMENT) => {}- (- InputKey::LocalFeature(node, key),- InputValue::Feature(old_value),- InputValue::Feature(new_value),- ) => {- if !self.input_routes_to_prefix(input) {- continue;- }- if !Self::fact_value_is_reconstructible(key, old_value)- || !Self::fact_value_is_reconstructible(key, new_value)- {- prefix_available = false;- } else if self.tree.is_live(node)- && self.tree.tree_scope(node) == TreeScopeID::DOCUMENT- && !arrived(node)- {- roots.push(node);- }- }- (InputKey::State(node, _), InputValue::State(_), InputValue::State(_)) => {- if !self.input_routes_to_prefix(input) {- continue;- }- if self.tree.is_live(node)- && self.tree.tree_scope(node) == TreeScopeID::DOCUMENT- && !arrived(node)- {- roots.push(node);- }- }- _ => prefix_available = false,- }- }- }-- let prefix = prefix_available.then(|| {- departures.sort_unstable();- departures.dedup();- roots.sort_unstable();- roots.dedup();- sibling_frontier.retain(|&node| {- self.tree.is_live(node)- && self.tree.tree_scope(node) == TreeScopeID::DOCUMENT- && departures.binary_search(&node).is_err()- });- sibling_frontier.sort_unstable();- sibling_frontier.dedup();- PrefixFactTransition {- roots,- departures,- tree_relations_changed,- sibling_frontier,- }- });- TransactionFactClassification {- prefix,- retained_truth_available,- }- }-- pub(super) fn transaction_fact_view_for(- &mut self,- transaction: &mut StyleTransaction,- root: StyleNodeID,- arrival_regions: &ImpactRegions,- ) -> TransactionFactView {- self.match_workspace.clear_old_evaluation_sides();-- let classification = self.classify_transaction_facts(transaction, arrival_regions);- let before_facts = transaction.take_before_facts();- let before = (!transaction.has_coarsened_markers()).then_some(before_facts).flatten();- TransactionFactView {- root,- moved_features: if !transaction.has_coarsened_markers() {- self.feature_delta_for(transaction)- } else {- FeatureFluxColumn::default()- },- before,- 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: classification.prefix,- retained_truth_available: classification.retained_truth_available,- }- }-}--impl StyleEngine {- /// Put the qualified layer names in the order one tree scope declares them in.- pub fn set_layer_order(&mut self, scope: TreeScopeID, layers: &[CascadeLayerID]) {- let ranks = StyleSheetProgram::layer_ranks_in_order(layers);- let pending_order = self.host.program_staging.layer_orders.after(scope);- if pending_order.map_or_else(- || self.retained.program.layer_ranks_match(scope, &ranks),- |pending| pending == &ranks,- ) {- return;- }- let initialized = pending_order.is_some() || self.retained.program.layer_order_is_initialized(scope);- let program_version = self.retained.program.version();- self.host.program_staging.base_version.get_or_insert(program_version);- self.invalidate_scope_program(scope);- self.host- .program_staging- .layer_orders- .stage(scope, || self.retained.program.layer_ranks(scope), ranks);- if initialized {- self.record_layer_topology_change(scope);- }- }-- /// The dense layer rank consumed by the C++ property cascade and non-style rule lookup.- #[must_use]- pub fn layer_index(&self, scope: TreeScopeID, layer: CascadeLayerID) -> u32 {- self.host.program_staging.layer_orders.after(scope).map_or_else(- || self.retained.program.layer_index(scope, layer),- |ranks| {- ranks- .get(&layer)- .copied()- .unwrap_or_else(|| u32::try_from(ranks.len()).expect("cascade layer count exhausted"))- },- )- }-- pub(super) fn stage_rule_declared_properties(- &mut self,- rule: RuleID,- declared: Vec<DeclaredProperty>,- written_values: Vec<RetainedStyleValueData>,- custom_declarations: Vec<CustomDeclaration>,- custom_written_values: Vec<RetainedStyleValueData>,- ) {- if !self.staged_rule_is_arriving(rule) {- let program_version = self.retained.program.version();- self.host.program_staging.base_version.get_or_insert(program_version);- let sheet = self.retained.program.rule_sheet(rule);- self.invalidate_scope_programs_for_sheet(sheet);- }- self.host.program_staging.rule_declarations.stage(- rule,- || PendingRuleDeclarations {- declared: self.retained.program.declared_properties_of(rule).to_vec(),- written_values: self.retained.program.written_values_of(rule).to_vec(),- custom_declarations: self.retained.program.custom_declarations_of(rule).to_vec(),- custom_written_values: self.retained.program.custom_written_values_of(rule).to_vec(),- },- PendingRuleDeclarations {- declared,- written_values,- custom_declarations,- custom_written_values,- },- );- }-- pub(super) fn current_declared_properties_of(&self, rule: RuleID) -> &[DeclaredProperty] {- self.host- .program_staging- .rule_declarations- .after(rule)- .map(|pending| pending.declared.as_slice())- .unwrap_or_else(|| self.retained.program.declared_properties_of(rule))- }-- pub(super) fn current_custom_declarations_of(&self, rule: RuleID) -> &[CustomDeclaration] {- self.host- .program_staging- .rule_declarations- .after(rule)- .map(|pending| pending.custom_declarations.as_slice())- .unwrap_or_else(|| self.retained.program.custom_declarations_of(rule))- }-- pub(super) fn current_declarations_are_complete_for(&self, rule: RuleID) -> bool {- self.host- .program_staging- .rule_declarations- .after(rule)- .map(|pending| pending.custom_declarations.is_empty())- .unwrap_or_else(|| self.retained.program.declarations_are_complete_for(rule))- }-- /// Preserve the property range of a declaration edit until its block identity is journaled.- pub(super) fn record_rule_declaration_change(- &mut self,- rule: RuleID,- declared: &[DeclaredProperty],- custom_declarations: &[CustomDeclaration],- ) {- if self.replacement_rule(rule).is_none() && self.current_rule_version(rule).declaration_block.is_none() {- return;- }- let custom_declarations_changed = self.current_custom_declarations_of(rule) != custom_declarations;- if let Some(change) = self- .host- .program_staging- .rule_declaration_changes- .iter_mut()- .find(|change| change.rule == rule)- {- change.new_properties.clear();- change- .new_properties- .extend(declared.iter().map(|declared| declared.property));- change.new_properties.sort_unstable();- change.new_properties.dedup();- change.custom_declarations_changed |= custom_declarations_changed;- return;- }- let mut new_properties: Vec<u16> = declared.iter().map(|declared| declared.property).collect();- new_properties.sort_unstable();- new_properties.dedup();- let previous = self- .replacement_rule(rule)- .map(|replacement| replacement.declared.as_slice())- .unwrap_or_else(|| self.current_declared_properties_of(rule));- let mut old_properties: Vec<u16> = previous.iter().map(|declared| declared.property).collect();- old_properties.sort_unstable();- old_properties.dedup();- // An incomplete inventory can hold custom properties, and those never reach the winner- // columns, so nothing downstream can prove such an edit inert. Capture that on the old- // side only: the first edit in a transaction reads the state every proof compares against.- if !self.current_declarations_are_complete_for(rule) {- self.host- .program_staging- .rules_with_incomplete_old_declarations- .push(rule);- }- self.host- .program_staging- .rule_declaration_changes- .push(PendingRuleDeclarationChange {- rule,- old_properties,- new_properties,- custom_declarations_changed,- });- }-- pub fn set_rule_conditions_hold(&mut self, rule: RuleID, conditions_hold: bool) {- let previous = self- .host- .program_staging- .rule_conditions- .current(rule, || self.retained.program.rule_conditions_hold(rule));- if previous == conditions_hold {- return;- }- self.stage_program_activation();- self.host.program_staging.rule_conditions.stage(- rule,- || self.retained.program.rule_conditions_hold(rule),- conditions_hold,- );- // While the rule's sheet is still arriving, whether its condition holds is part of what- // arrives rather than something that moved: routing the attachment reads the activation the- // rule ends the transaction with, and skips it if it decides nothing.- if self.rule_change_is_carried_by_its_sheet(rule) {- return;- }- self.record_input(- InputKey::RuleField(rule, RuleField::Activation),- InputValue::Flag(previous),- InputValue::Flag(conditions_hold),- );- }-- /// Record whether a sheet's conditions hold, as evaluating its media queries decides.- pub fn set_sheet_conditions_hold(&mut self, sheet: SheetID, conditions_hold: bool) {- let previous = self- .host- .program_staging- .sheet_conditions- .current(sheet, || self.retained.program.sheet_conditions_hold(sheet));- if previous == conditions_hold {- return;- }- self.stage_program_activation();- self.host.program_staging.sheet_conditions.stage(- sheet,- || self.retained.program.sheet_conditions_hold(sheet),- conditions_hold,- );- self.record_input(- InputKey::SheetActivation(sheet),- InputValue::Flag(previous),- InputValue::Flag(conditions_hold),- );- }-- #[cfg(test)]- pub(super) fn set_sheet_enabled(&mut self, sheet: SheetID, enabled: bool) {- let previous = self- .host- .program_staging- .sheet_enabled- .current(sheet, || self.retained.program.sheet_is_enabled(sheet));- if previous == enabled {- return;- }- self.stage_program_activation();- self.host- .program_staging- .sheet_enabled- .stage(sheet, || self.retained.program.sheet_is_enabled(sheet), enabled);- self.record_input(- InputKey::SheetActivation(sheet),- InputValue::Flag(previous),- InputValue::Flag(enabled),- );- }-- /// Begin rebuilding a sheet while retaining compatible style-rule identities by cascade- /// position. The parsed CSSOM objects are new, but an unchanged semantic rule does not become a- /// departure followed by an arrival merely because the whole sheet was reparsed.- pub fn begin_sheet_rules_replacement(&mut self, sheet: SheetID) {- assert!(- self.host.sheet_rule_replacement.is_none(),- "stylesheet replacements do not nest"- );- if let Some(slot) = self- .host- .program_staging- .sheet_rule_replacements- .get_mut(sheet.0 as usize)- && let Some(mut replacement) = slot.take()- {- replacement.reused = 0;- replacement.reuse_disabled = false;- self.host.sheet_rule_replacement = Some(replacement);- return;- }- let rules = self.current_rules_in_sheet(sheet);- if rules- .iter()- .any(|&rule| self.current_rule_version(rule).kind != RuleKind::Style)- {- self.clear_sheet_rules(sheet);- return;- }- let rules: Vec<ReplacedStyleRule> = rules- .into_iter()- .map(|rule| ReplacedStyleRule {- rule,- version: self.current_rule_version(rule),- declared: self.current_declared_properties_of(rule).to_vec(),- declarations_are_complete: self.current_declarations_are_complete_for(rule),- gated_by_container_query: self.current_rule_is_gated_by_container_query(rule),- })- .collect();- self.host.sheet_rule_replacement = Some(SheetRuleReplacement {- sheet,- rules,- reused: 0,- reuse_disabled: false,- });- }-- /// Finish a synchronous sheet rebuild, retiring unmatched old rules and publishing declaration- /// changes on identities that were reused.- pub fn finish_sheet_rules_replacement(&mut self, sheet: SheetID, declaration_block: u32) {- let Some(replacement) = self.host.sheet_rule_replacement.take() else {- return;- };- assert_eq!(replacement.sheet, sheet);- for old in &replacement.rules[..replacement.reused] {- let declarations_changed = !old.declarations_are_complete- || !self.current_declarations_are_complete_for(old.rule)- || self.current_declared_properties_of(old.rule) != old.declared- || self.current_rule_is_gated_by_container_query(old.rule) != old.gated_by_container_query;- if declarations_changed {- let mut version = self.current_rule_version(old.rule);- version.declaration_block = Some(DeclarationBlockID(declaration_block));- self.replace_rule_version(old.rule, version);- }- }- if replacement.reused < replacement.rules.len() {- let index = sheet.0 as usize;- self.host- .program_staging- .sheet_rule_replacements- .insert(index, Some(replacement));- self.settle_program();- return;- }- self.settle_program();- }-- pub(super) fn finalize_staged_sheet_rule_replacements(&mut self) {- for index in 0..self.host.program_staging.sheet_rule_replacements.len() {- let Some(replacement) = self.host.program_staging.sheet_rule_replacements[index].take() else {- continue;- };- for old in &replacement.rules[replacement.reused..] {- self.remove_rule(old.rule);- }- }- }-- pub(super) fn replacement_rule(&self, rule: RuleID) -> Option<&ReplacedStyleRule> {- let replacement = self.host.sheet_rule_replacement.as_ref()?;- let old = replacement.rules.get(replacement.reused.checked_sub(1)?)?;- (old.rule == rule).then_some(old)- }-- pub(super) fn reuse_replaced_style_rule(&mut self, sheet: SheetID) -> Option<RuleID> {- let replacement = self.host.sheet_rule_replacement.as_mut()?;- if replacement.sheet != sheet || replacement.reuse_disabled {- return None;- }- let old = replacement.rules.get(replacement.reused)?;- if old.version.kind != RuleKind::Style {- replacement.reuse_disabled = true;- return None;- }- let rule = old.rule;- let declaration_block = old.version.declaration_block;- replacement.reused += 1;-- self.set_rule_conditions_hold(rule, true);- self.stage_rule_declared_properties(rule, Vec::new(), Vec::new(), Vec::new(), Vec::new());- self.stage_rule_in_a_layer(rule, false);- self.stage_rule_gated_by_container_query(rule, false);- let mut version = RuleVersion::new(rule, RuleKind::Style);- version.declaration_block = declaration_block;- self.replace_rule_version(rule, version);- Some(rule)- }-- pub(super) fn current_rule_version(&self, rule: RuleID) -> RuleVersion {- self.host- .program_staging- .rule_versions- .current(rule, || self.retained.program.rule_version(rule))- }-- pub(super) fn stage_rule_version(&mut self, rule: RuleID, contents: RuleVersion) {- if !self.staged_rule_is_arriving(rule) {- let program_version = self.retained.program.version();- self.host.program_staging.base_version.get_or_insert(program_version);- let sheet = self.retained.program.rule_sheet(rule);- self.invalidate_scope_programs_for_sheet(sheet);- }- self.host- .program_staging- .rule_versions- .stage(rule, || self.retained.program.rule_version(rule), contents);- }-- pub(super) fn current_rule_is_gated_by_container_query(&self, rule: RuleID) -> bool {- self.host- .program_staging- .rule_gated_by_container_query- .current(rule, || self.retained.program.rule_is_gated_by_container_query(rule))- }-- pub(super) fn stage_rule_gated_by_container_query(&mut self, rule: RuleID, gated: bool) {- if !self.staged_rule_is_arriving(rule) {- let program_version = self.retained.program.version();- self.host.program_staging.base_version.get_or_insert(program_version);- let sheet = self.retained.program.rule_sheet(rule);- self.invalidate_scope_programs_for_sheet(sheet);- }- self.host.program_staging.rule_gated_by_container_query.stage(- rule,- || self.retained.program.rule_is_gated_by_container_query(rule),- gated,- );- }-- pub(super) fn stage_rule_in_a_layer(&mut self, rule: RuleID, in_a_layer: bool) {- if !self.staged_rule_is_arriving(rule) {- let program_version = self.retained.program.version();- self.host.program_staging.base_version.get_or_insert(program_version);- let sheet = self.retained.program.rule_sheet(rule);- self.invalidate_scope_programs_for_sheet(sheet);- }- self.host.program_staging.rule_in_a_layer.stage(- rule,- || self.retained.program.rule_is_in_a_layer(rule),- in_a_layer,- );- }-- /// A structural program edit cannot be applied while an epoch is reading the program, and it- /// cannot be half-applied either, so it is a phase-contract violation rather than something to- /// queue. Script cannot reach here mid-evaluation; an input that legitimately becomes ready- /// mid-evaluation - a sheet finishing its load - is queued as a whole operation by its caller- /// and arrives in a later transaction.- /// The stylesheet program, for a change to it.- ///- /// Every scope's rule dispatch is derived from the program, so a kept one cannot outlive a- /// change to it. Going through here rather than at the field is what makes that true by- /// construction: a mutation that forgets to drop the dispatch does not compile.- /// The stylesheet program, for an activation-only change to it.- ///- /// Whether a rule or sheet's conditions hold is match-time state: every scope dispatch keeps- /// its structurally live rules and candidates are filtered on activation as they are- /// consumed, so the derived scope programs and the retained prefix transition caches stay- /// valid across the flip. Memoized prefix answers were filtered through the old activation,- /// so those are dropped here.- pub(super) fn stage_program_activation(&mut self) {- let program_version = self.retained.program.version();- self.host.program_staging.base_version.get_or_insert(program_version);- self.retained- .prefix_caches- .borrow_mut()- .answers- .release(&mut self.retained.match_answers);- }-- pub(super) fn commit_staged_program(&mut self) {- let changes_program = self.host.program_staging.is_dirty();- let rule_conditions = self.host.program_staging.rule_conditions.take_dirty();- let sheet_conditions = self.host.program_staging.sheet_conditions.take_dirty();- let sheet_enabled = self.host.program_staging.sheet_enabled.take_dirty();- if !rule_conditions.is_empty() || !sheet_conditions.is_empty() || !sheet_enabled.is_empty() {- for (rule, conditions_hold) in rule_conditions {- self.retained.program.set_rule_conditions_hold(rule, conditions_hold);- }- for (sheet, conditions_hold) in sheet_conditions {- self.retained.program.set_sheet_conditions_hold(sheet, conditions_hold);- }- for (sheet, enabled) in sheet_enabled {- self.retained.program.set_sheet_enabled(sheet, enabled);- }- self.settle_program();- }-- let declarations = self.host.program_staging.rule_declarations.take_dirty();- for (rule, pending) in declarations {- self.retained.program.set_rule_declared_properties(- rule,- pending.declared,- pending.written_values,- pending.custom_declarations,- pending.custom_written_values,- );- }-- let mut versions = self.host.program_staging.rule_versions.take_dirty();- if !versions.is_empty() {- versions.sort_unstable_by_key(|(rule, _)| *rule);- for (rule, version) in versions {- if self.staged_rule_is_arriving(rule) {- self.retained.program.replace_reserved_rule_version(rule, version);- } else {- self.retained.program.replace_rule_version(rule, version);- }- }- self.settle_program();- }-- let in_a_layer = self.host.program_staging.rule_in_a_layer.take_dirty();- let gated_by_container_query = self.host.program_staging.rule_gated_by_container_query.take_dirty();- for (rule, value) in in_a_layer {- self.retained.program.set_rule_in_a_layer(rule, value);- }- for (rule, value) in gated_by_container_query {- self.retained.program.set_rule_gated_by_container_query(rule, value);- }-- let mut liveness_changes = self.host.program_staging.rule_liveness.take_dirty();- if !liveness_changes.is_empty() {- liveness_changes.sort_unstable_by_key(|(rule, _)| *rule);- self.retained.program.set_rule_liveness(&liveness_changes);- self.settle_program();- }-- let layer_orders = self.host.program_staging.layer_orders.take_dirty();- let scopes = self.host.program_staging.scopes_using_document_sheets.take_dirty();- if !layer_orders.is_empty() || !scopes.is_empty() {- for (scope, ranks) in layer_orders {- self.retained.program.set_layer_ranks(scope, ranks);- }- for (scope, uses_document_sheets) in scopes {- if uses_document_sheets {- self.retained.program.set_scope_uses_document_sheets(scope);- }- }- self.settle_program();- }-- let mut sheet_orders = self.host.program_staging.sheets_in_scope.take_dirty();- if !sheet_orders.is_empty() {- sheet_orders.sort_unstable_by_key(|(scope, _)| *scope);- for (scope, sheets) in sheet_orders {- self.retained.program.set_sheets_in_scope(scope, sheets);- }- self.settle_program();- }-- if changes_program {- self.invalidate_outdated_scope_programs();- }- }-- /// Drop the ranked programs that no longer match the program of their scope. Staging a change drops the programs it- /// reaches, but a read between the staging and this commit ranks a scope again from the program without it.- fn invalidate_outdated_scope_programs(&mut self) {- for index in 0..self.scope_program_by_scope.len() {- let Some((_, program)) = self.scope_program_by_scope[index] else {- continue;- };- let scope = TreeScopeID(u32::try_from(index).expect("tree scope identity space exhausted"));- if self.scope_program(program).key != self.scope_dispatch_key(scope) {- self.invalidate_concrete_scope_program(scope);- }- }- }-- pub(super) fn current_rule_is_live(&self, rule: RuleID) -> bool {- self.host- .program_staging- .rule_liveness- .current(rule, || self.retained.program.rule_is_live(rule))- }-- fn staged_rule_is_arriving(&self, rule: RuleID) -> bool {- !self- .host- .program_staging- .rule_liveness- .side(rule, TransactionFactSide::Before, || {- self.retained.program.rule_is_live(rule)- })- && self.current_rule_is_live(rule)- }-- pub(super) fn stage_rule_liveness(&mut self, rule: RuleID, live: bool) {- let program_version = self.retained.program.version();- self.host.program_staging.base_version.get_or_insert(program_version);- if !self.rule_change_is_carried_by_its_sheet(rule) {- let sheet = self.retained.program.rule_sheet(rule);- self.invalidate_scope_programs_for_sheet(sheet);- }- self.host- .program_staging- .rule_liveness- .stage(rule, || self.retained.program.rule_is_live(rule), live);- }-- pub(super) fn current_sheets_in_scope(&self, tree_scope: TreeScopeID) -> &[SheetID] {- self.host- .program_staging- .sheets_in_scope- .after(tree_scope)- .map_or_else(|| self.retained.program.sheets_in_scope(tree_scope), Vec::as_slice)- }-- pub(super) fn stage_sheets_in_scope(&mut self, tree_scope: TreeScopeID, sheets: Vec<SheetID>) {- self.host.program_staging.rule_change_is_carried_by_sheet.clear();- let program_version = self.retained.program.version();- self.host.program_staging.base_version.get_or_insert(program_version);- if tree_scope == TreeScopeID::DOCUMENT {- // Ordinary shadow roots add only the document's non-author sheets to their local sheet- // set. Keep their ranked programs when a document author sheet changes, while scopes- // that explicitly consume document author sheets still follow every document change.- let non_author_changed = self- .current_sheets_in_scope(tree_scope)- .iter()- .copied()- .filter(|&sheet| self.retained.program.sheet_origin(sheet) != CascadeOrigin::Author)- .ne(sheets- .iter()- .copied()- .filter(|&sheet| self.retained.program.sheet_origin(sheet) != CascadeOrigin::Author));- for index in 0..self.retained.scope_program_by_scope.len() {- let Some((_, program)) = self.retained.scope_program_by_scope[index] else {- continue;- };- let invalidate = index == TreeScopeID::DOCUMENT.0 as usize- || self.scope_program(program).key.document_sheet_mode == DocumentSheetMode::All- || (non_author_changed- && self.scope_program(program).key.document_sheet_mode == DocumentSheetMode::NonAuthor);- if invalidate {- let scope = TreeScopeID(u32::try_from(index).expect("tree scope identity space exhausted"));- self.invalidate_concrete_scope_program(scope);- }- }- } else {- self.invalidate_concrete_scope_program(tree_scope);- }- self.host.program_staging.sheets_in_scope.stage(- tree_scope,- || self.retained.program.sheets_in_scope(tree_scope).to_vec(),- sheets,- );- }-- pub(super) fn record_attachment(&mut self, sheet: SheetID, tree_scope: TreeScopeID, previous: bool, current: bool) {- let key = InputKey::SheetAttachment(sheet, tree_scope);- // A sheet that leaves a scope and comes back to it inside one transaction is attached at both- // ends, so its attachment says nothing - and it is exactly how a reorder is performed, since- // assigning `adoptedStyleSheets` or moving a `style` element detaches and attaches again.- // What moved is the sheet's place in the scope's order, which is an input of its own. Asking- // the journal before recording is what distinguishes that from a sheet that arrived and left- // again, whose cancellation really does mean nothing happened.- let reattached = current && self.host.journal.pending_old(key) == Some(InputValue::Flag(true));- self.record_input(key, InputValue::Flag(previous), InputValue::Flag(current));- if reattached {- self.record_sheet_order_change(tree_scope);- }- self.settle_program();- }-- /// Whether a change to this rule is already carried by what its sheet is doing.- ///- /// A sheet attaching routes every rule in it, so a rule's fields recorded while that attachment- /// is still pending in the same transaction say nothing the attachment does not already say. A- /// sheet attached nowhere is the same case from the other side: routing ignores its rules- /// outright, and whatever attaches it later will route them all.- ///- /// This is what keeps a stylesheet arriving from journalling a field or two per rule. A page- /// with a few thousand rules would otherwise fill the transaction's whole scratch budget on the- /// way in, and a journal that has to coarsen loses which keys moved - which costs a restyle of- /// the entire document, for rules whose arrival was already accounted for.- #[must_use]- pub(super) fn rule_change_is_carried_by_its_sheet(&mut self, rule: RuleID) -> bool {- let sheet = self.retained.program.rule_sheet(rule);- if let Some(&carried) = self.host.program_staging.rule_change_is_carried_by_sheet.get(&sheet) {- return carried;- }- let mut scopes = self.retained.program.sheet_scopes(sheet);- scopes.extend(- self.host- .program_staging- .sheets_in_scope- .pairs()- .filter_map(|(scope, before, after)| {- (before.contains(&sheet) || after.contains(&sheet)).then_some(scope)- }),- );- scopes.sort_unstable();- scopes.dedup();- if scopes.is_empty() {- self.host- .program_staging- .rule_change_is_carried_by_sheet- .insert(sheet, true);- return true;- }- // Every scope it decides in has to be arriving. A sheet adopted somewhere long ago and- // attached somewhere new this transaction still has to answer for the old scope.- let carried = scopes.iter().all(|&tree_scope| {- self.host- .journal- .pending_old(InputKey::SheetAttachment(sheet, tree_scope))- == Some(InputValue::Flag(false))- });- self.host- .program_staging- .rule_change_is_carried_by_sheet- .insert(sheet, carried);- carried- }-- /// A layer topology change updates priority comparisons for declarations that already matched.- /// It never invalidates selector truth.- pub(super) fn record_layer_topology_change(&mut self, scope: TreeScopeID) {- let program_version = self.retained.program.version();- self.host.program_staging.base_version.get_or_insert(program_version);- self.invalidate_scope_program(scope);- self.retained.winner_groups.invalidate_priorities();- let previous = self.retained.layer_topology_version;- self.retained.layer_topology_version += 1;- self.record_input(- InputKey::CascadeTopology(TopologyAxis::LayerOrder(scope)),- InputValue::Topology(previous),- InputValue::Topology(self.retained.layer_topology_version),- );- self.settle_program();- }-}--impl StyleEngine {- pub fn set_rule_gated_by_container_query(&mut self, rule: RuleID) {- self.stage_rule_gated_by_container_query(rule, true);- }-- /// Set a rule's declarations together with the values they were written with, parallel to- /// `declared`, so a consumer computing a value can read the written spelling.- pub fn set_rule_declared_properties_with_written_values(- &mut self,- rule: RuleID,- declared: &[DeclaredProperty],- written_values: Vec<RetainedStyleValueData>,- custom_declarations: Vec<CustomDeclaration>,- custom_written_values: Vec<RetainedStyleValueData>,- ) {- self.record_rule_declaration_change(rule, declared, &custom_declarations);- self.stage_rule_declared_properties(- rule,- declared.to_vec(),- written_values,- custom_declarations,- custom_written_values,- );- }-- /// Record which cascade layer a rule sits in.- ///- /// Where a rule sits among the layers is part of what the rule is, and it is what the cascade- /// compares; whether it is in one at all is what a layer topology change routes by.- pub fn set_rule_layer(&mut self, rule: RuleID, layer: CascadeLayerID) {- let mut version = self.current_rule_version(rule);- if version.layer == layer {- return;- }- version.layer = layer;- self.replace_rule_version(rule, version);- }-- pub fn set_rule_in_a_layer(&mut self, rule: RuleID) {- self.stage_rule_in_a_layer(rule, true);- }-- pub(super) fn append_rule(&mut self, sheet: SheetID, parent: Option<RuleID>, kind: RuleKind) -> RuleID {- let rule = self.retained.program.reserve_rule(sheet, parent, kind);- self.stage_rule_liveness(rule, true);- self.record_rule_existence(rule, false, true);- rule- }-- /// Insert one rule between two neighbours. Existing rules are neither renumbered nor rematched.- pub(super) fn insert_rule_before(&mut self, before: RuleID, kind: RuleKind) -> RuleID {- let rule = self.retained.program.reserve_rule_before(before, kind);- self.stage_rule_liveness(rule, true);- self.record_rule_existence(rule, false, true);- rule- }-- /// Delete a rule, taking its subtree with it. Every removed identity is journalled, because a- /// deleted winning declaration has to be repaired wherever it was winning.- pub(super) fn remove_rule(&mut self, rule: RuleID) -> Vec<RuleID> {- if !self.current_rule_is_live(rule) {- return Vec::new();- }- let removed: Vec<RuleID> = self- .program- .rule_subtree(rule)- .into_iter()- .filter(|&rule| self.current_rule_is_live(rule))- .collect();- self.retained.selector_programs_need_sweep |= removed- .iter()- .any(|&removed| self.current_rule_version(removed).selector_program.is_some());- for &id in &removed {- self.retained.native_rules.remove(id);- self.stage_rule_liveness(id, false);- self.record_rule_existence(id, true, false);- }- removed- }-- /// Replace a rule's contents and journal only the fields that actually changed.- pub(super) fn replace_rule_version(&mut self, rule: RuleID, contents: RuleVersion) {- let previous = self.current_rule_version(rule);- self.stage_rule_version(rule, contents);-- if self.rule_change_is_carried_by_its_sheet(rule) {- self.settle_program();- return;- }-- if previous.selector_program != contents.selector_program {- self.record_input(- InputKey::RuleField(rule, RuleField::Selector),- InputValue::SelectorProgram(previous.selector_program),- InputValue::SelectorProgram(contents.selector_program),- );- }- if previous.declaration_block != contents.declaration_block {- self.record_input(- InputKey::RuleField(rule, RuleField::Declarations),- InputValue::RuleDeclarations(previous.declaration_block),- InputValue::RuleDeclarations(contents.declaration_block),- );- }- if previous.activation_predicate != contents.activation_predicate {- self.record_input(- InputKey::RuleField(rule, RuleField::Activation),- InputValue::ActivationPredicate(previous.activation_predicate),- InputValue::ActivationPredicate(contents.activation_predicate),- );- }- if previous.layer != contents.layer {- self.record_input(- InputKey::RuleField(rule, RuleField::Layer),- InputValue::Layer(previous.layer),- InputValue::Layer(contents.layer),- );- }- if previous.scope != contents.scope {- self.record_input(- InputKey::RuleField(rule, RuleField::Scope),- InputValue::Scope(previous.scope),- InputValue::Scope(contents.scope),- );- }- self.settle_program();- }-- pub(super) fn current_top_level_rules_in_sheet(&self, sheet: SheetID) -> Vec<RuleID> {- self.retained- .program- .all_top_level_rules_in_sheet(sheet)- .iter()- .copied()- .filter(|&rule| self.current_rule_is_live(rule))- .collect()- }-- pub(super) fn current_rules_in_sheet(&self, sheet: SheetID) -> Vec<RuleID> {- self.retained- .program- .all_rules_in_sheet(sheet)- .into_iter()- .filter(|&rule| self.current_rule_is_live(rule))- .collect()- }-- pub(super) fn record_rule_existence(&mut self, rule: RuleID, previous: bool, current: bool) {- if self.rule_change_is_carried_by_its_sheet(rule) {- self.settle_program();- return;- }- self.record_input(- InputKey::RuleField(rule, RuleField::Existence),- InputValue::Flag(previous),- InputValue::Flag(current),- );- self.settle_program();- }-- /// Answers the identities the end of the transaction released, for the host to mint again.- pub(super) fn discard_style_transaction_outputs(&mut self) -> Vec<u32> {- self.retained.forget_custom_property_environments_by_answer();- if let Some(pass) = self.host.suspended_style_pass.take() {- self.abandon_style_pass(pass);- }- self.discard_engine_computed_records();- self.retain_prefix_states();- self.discard_prepared_batch_matching_traversal();- self.discard_published_match_answers();- // Published matching scratch is the last owner that may name a retired identity.- self.retained.tree.release_retired_identities()- }-}--impl StyleEngine {- /// Record already decoded cascade operators beside canonical specified values.- #[cfg(test)]- pub fn set_rule_declared_properties_with_operators(&mut self, rule: RuleID, declared: &[DeclaredProperty]) {- self.set_rule_declared_properties_with_written_values(rule, declared, Vec::new(), Vec::new(), Vec::new());- }-- /// Drop every rule of a sheet.- ///- /// This is for `replace()`, which really does swap the whole rule list. Every other edit to a- /// sheet moves one rule and is patched one rule at a time, because retiring identities that did- /// not change turns a one-rule edit into a program change over the whole sheet.- pub(super) fn clear_sheet_rules(&mut self, sheet: SheetID) {- for rule in self.current_top_level_rules_in_sheet(sheet) {- self.remove_rule(rule);- }- self.settle_program();- }-- /// Delete one rule and settle the program around it.- pub fn remove_style_rule(&mut self, rule: RuleID) {- self.remove_rule(rule);- self.settle_program();- }-- pub(super) fn record_sheet_order_change(&mut self, tree_scope: TreeScopeID) {- self.retained.winner_groups.invalidate_priorities();- let previous = self.retained.sheet_order_version;- self.retained.sheet_order_version += 1;- self.record_input(- InputKey::CascadeTopology(TopologyAxis::SheetOrder(tree_scope)),- InputValue::Topology(previous),- InputValue::Topology(self.retained.sheet_order_version),- );- self.settle_program();- }-}--impl StyleEngine {- /// Record which longhand properties a rule declares, and which of them it marks important.- #[cfg(test)]- pub(super) fn set_rule_declared_properties(&mut self, rule: RuleID, declared: &[(u16, bool)]) {- let block = self- .program- .rule_version(rule)- .declaration_block- .map_or(u32::MAX, |block| block.0);- let declared: Vec<DeclaredProperty> = declared- .iter()- .map(|&(property, important)| DeclaredProperty {- property,- important,- operator: CascadeOperator::Declared,- value: SpecifiedValueID((u64::from(block) << 32) ^ (u64::from(rule.0) << 16) ^ u64::from(property)),- })- .collect();- self.record_rule_declaration_change(rule, &declared, &[]);- self.stage_rule_declared_properties(rule, declared, Vec::new(), Vec::new(), Vec::new());- }-- /// Record the canonical specified value beside every declared longhand.- #[cfg(test)]- pub(super) fn set_rule_declared_properties_with_values(- &mut self,- rule: RuleID,- declared: &[(u16, bool, SpecifiedValueID)],- ) {- let declared: Vec<DeclaredProperty> = declared- .iter()- .map(|&(property, important, value)| DeclaredProperty {- property,- important,- operator: CascadeOperator::Declared,- value,- })- .collect();- self.record_rule_declaration_change(rule, &declared, &[]);- self.stage_rule_declared_properties(rule, declared, Vec::new(), Vec::new(), Vec::new());- }-- /// Take the pending transaction for the style consumer that immediately follows this call.- ///- /// Exact planning may already have packed the current facts and built document-order- /// coordinates. Keep that workspace for matching instead of reconstructing it. The- /// callback receives only accepted match-answer records after their complete payloads have been- /// published. Versions are shared by the whole emitted batch rather than repeated per record.- #[cfg(test)]- pub(super) fn take_style_transaction_nodes(&mut self, root: StyleNodeID, mut emit: impl FnMut(&[u32])) -> bool {- assert!(self.retained.diagnostic_plan_capture.is_none());- self.retained.diagnostic_plan_capture = Some(DiagnosticPlanCapture {- nodes: Vec::new(),- scoped: true,- });- let _ = self.take_style_transaction(root, |_, _, _| {});- // A pass the host would install in waves reports every wave, as the host's diagnostic take- // does.- while self.host.suspended_style_pass.is_some() {- let _ = self.take_style_transaction(root, |_, _, _| {});- }- let capture = self- .diagnostic_plan_capture- .take()- .expect("the diagnostic plan capture is active during the transaction");- let _ = self.discard_style_transaction_outputs();- if !capture.nodes.is_empty() {- emit(&capture.nodes);- }- capture.scoped- }-}diff --git a/Libraries/LibWeb/Rust/src/css/style/relative_selector.rs b/Libraries/LibWeb/Rust/src/css/style/relative_selector.rsindex 1092e7ed8db..f149e10203c 100644--- a/Libraries/LibWeb/Rust/src/css/style/relative_selector.rs+++ b/Libraries/LibWeb/Rust/src/css/style/relative_selector.rs@@ -4,28 +4,10 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! Relational selector query descriptors, inverse anchor enumeration, and the retained witnesses.+//! Relational selector query descriptors and the candidate witnesses along their axes.//!-//! A relative selector matches a witness along one axis from an anchor. Runtime matching enumerates-//! candidates along that axis, while invalidation walks the relationship backwards from a changed-//! witness to enumerate only the anchors whose Boolean result could have changed. For a simple-//! query, matching also retains the one witness it found, which routing uses to prove that an-//! anchor's Boolean cannot have flipped and drop it from the plan.--use super::fast_hash::FastMap as HashMap;--use super::index::LocalFeatureKey;-use super::partial_view::Lookup;-use super::program::SelectorProgramID;-use super::selector::Incomplete;-use super::selector::SelectorNodeID;-use super::tree::StyleNodeID;-use super::tree::StyleNodeTree;--define_id! {- /// Identity of a compiled relative query within a selector program.- pub struct RelativeQueryID(pub);-}+//! A relative selector matches a witness along one axis from an anchor, and matching enumerates+//! the candidates along that axis./// The single axis a simple relative selector traverses from its anchor.#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]@@ -43,475 +25,3 @@ pub enum RelativeAxis {/// `:has(~ .row .cell)`: the witness is somewhere under one of the following siblings.FollowingSiblingSubtree,}--/// A compiled relative query.-///-/// `driving_feature` is the positive indexable feature of the witness compound. Its presence is-/// part of what makes a query simple, because it is what a replacement search drives from.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]-pub struct RelativeQuery {- pub axis: RelativeAxis,- pub compound: SelectorNodeID,- pub driving_feature: Option<LocalFeatureKey>,- /// False for a query that needs the direct evaluator: a selector list, more than one axis, an- /// internal combinator, a structural or nested relational operator, or a scope-crossing- /// construct. Complex is not unsupported; it is exact and retains no witness.- pub simple: bool,- /// Whether the witness has to be strictly below the element the leading axis reaches.- ///- /// `:has(+ div .test)` names a `.test` under the anchor's next sibling, not a next sibling that- /// is itself a `.test`. The chain compiles to constraints on the witness, which cannot say that- /// on its own, so a selector whose every step after the leading one goes downwards says it here.- /// One that goes sideways again - `:has(+ .a + .b)` - reaches a witness beside the axis element- /// rather than below it, and does not.- pub witness_is_below_the_axis: bool,- /// Whether the argument reads the tree the anchor hosts rather than the anchor's surroundings.- ///- /// A `:has()` sharing its compound with `:host` was written in a shadow tree's own stylesheet- /// and is anchored on that tree's host, which stands outside the tree. Its argument is a- /// selector of that sheet, so it sees the tree's nodes and nothing around the host:- /// `:host:has(.x)` asks whether the shadow tree holds an `.x`, and an `.x` sitting beside the- /// host in the light DOM does not answer it. Every axis is therefore walked from the shadow- /// root, which is where `:host > .x` crosses to as well.- pub match_in_shadow_tree: bool,-}--impl RelativeQuery {- /// A query is simple when one axis leads to one local compound with a positive indexable- /// driving feature. Everything else is answered by the direct evaluator.- #[must_use]- pub fn is_simple(&self) -> bool {- self.simple && self.driving_feature.is_some()- }-}--/// The node a query's axis is actually walked from.-///-/// For an in-shadow-tree query that is the tree the anchor hosts rather than the anchor itself, and-/// a host that opens no tree witnesses nothing at all. Translating here rather than inside each walk-/// is what lets `candidate_witnesses` and the chain's own anchor tie stay as they are: both then-/// read the shadow root wherever they would have read the host.-#[must_use]-pub fn traversal_anchor(anchor: StyleNodeID, match_in_shadow_tree: bool, tree: &StyleNodeTree) -> Option<StyleNodeID> {- match match_in_shadow_tree {- true => tree.shadow_root_of(anchor),- false => Some(anchor),- }-}--/// Possible anchors for a newly matching witness of an in-shadow-tree query.-///-/// The axis was walked from a shadow root, so walking it back arrives at that root and the anchor is-/// whatever hosts it. A witness therefore has at most one anchor however wide the axis is, and only-/// when the root the axis reached back to is a hosted one.-pub fn possible_hosting_anchors(- axis: RelativeAxis,- witness: StyleNodeID,- tree: &StyleNodeTree,- mut visit: impl FnMut(StyleNodeID),-) {- let root = match axis {- RelativeAxis::Child => tree.parent(witness),- // The walk stops at the top of the witness's own tree, which is what confines a descendant- // query to the one tree the sheet was written for: a nested shadow root is not a DOM child- // of anything in it, so no walk from inside one arrives here.- RelativeAxis::Descendant => {- let mut current = witness;- while let Some(parent) = tree.parent(current) {- current = parent;- }- Some(current)- }- // A sibling axis leaves the hosted tree, so such a query witnesses nothing and is compiled- // away rather than routed.- RelativeAxis::NextSibling- | RelativeAxis::FollowingSibling- | RelativeAxis::NextSiblingSubtree- | RelativeAxis::FollowingSiblingSubtree => None,- };- if let Some(host) = root.and_then(|root| tree.host_of(root)) {- visit(host);- }-}--/// Possible anchors for a newly matching witness, per the inverse of the query's axis.-///-/// This is the bound that makes false-to-true cheap: a child query has exactly one possible anchor,-/// an adjacent-sibling query has exactly one, and a descendant query has the ancestor path.-pub fn possible_anchors(- axis: RelativeAxis,- witness: StyleNodeID,- tree: &StyleNodeTree,- scope_boundary: Option<StyleNodeID>,- mut visit: impl FnMut(StyleNodeID),-) {- match axis {- RelativeAxis::Child => {- if let Some(parent) = tree.parent(witness) {- visit(parent);- }- }- RelativeAxis::Descendant => {- for ancestor in tree.ancestors(witness) {- visit(ancestor);- if Some(ancestor) == scope_boundary {- return;- }- }- }- RelativeAxis::NextSibling => {- if let Some(previous) = tree.previous_element_sibling(witness) {- visit(previous);- }- }- RelativeAxis::FollowingSibling => {- let Some(parent) = tree.parent(witness) else {- return;- };- for sibling in tree.children(parent) {- if sibling == witness {- return;- }- visit(sibling);- }- }- // The witness is under a sibling rather than being one, so the element the anchor is a- // sibling of is the witness or one of its ancestors. Each of those contributes the- // siblings before it.- RelativeAxis::NextSiblingSubtree => {- let mut node = Some(witness);- while let Some(current) = node {- if let Some(previous) = tree.previous_element_sibling(current) {- visit(previous);- }- if Some(current) == scope_boundary {- return;- }- node = tree.parent(current);- }- }- RelativeAxis::FollowingSiblingSubtree => {- let mut node = Some(witness);- while let Some(current) = node {- if let Some(parent) = tree.parent(current) {- for sibling in tree.children(parent) {- if sibling == current {- break;- }- visit(sibling);- }- }- if Some(current) == scope_boundary {- return;- }- node = tree.parent(current);- }- }- }-}--/// One anchor's observation of one simple relational query.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]-pub struct RelationalWitnessKey {- pub program: SelectorProgramID,- pub query: RelativeQueryID,- pub anchor: StyleNodeID,-}--/// The exact missing or invalid dependency that prevents a retained witness proof from being used.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub enum RelationalWitnessGap {- MissingEntry(RelationalWitnessKey),- MissingQuery(RelationalWitnessKey),- RetiredWitness {- key: RelationalWitnessKey,- witness: StyleNodeID,- },- UnreachableAnchor(RelationalWitnessKey),- StaleAxis {- key: RelationalWitnessKey,- witness: StyleNodeID,- },- SelectorMismatch {- key: RelationalWitnessKey,- witness: StyleNodeID,- },- IncompleteFacts {- key: RelationalWitnessKey,- witness: StyleNodeID,- incomplete: Incomplete,- },-}--/// How many anchors may retain a witness at once. The table is a shortcut, not state, so hitting-/// the cap costs recomputation and nothing else.-const MAX_RETAINED_WITNESSES: usize = 16384;--/// A completed query observation or stale-proof removal to install after evaluation.-#[derive(Clone, Copy, Debug)]-pub(super) enum WitnessEffect {- Retain(RelationalWitnessKey, StyleNodeID),- Clear(RelationalWitnessKey),-}--/// The retained witnesses of simple relational queries: at most one per observed anchor.-///-/// An entry says that `witness` was seen to satisfy the query's compound on the query's axis from-/// `anchor` by an evaluation of the current tree, and that the anchor's last completed evaluation-/// of the query answered true. It is a proof cache, never semantic state: every read re-verifies-/// the claim against the tree and facts as they stand before trusting it, so dropping any entry at-/// any time is legal and costs only the shortcut.-///-/// Soundness rests on the write discipline, not on the reads: an entry is written only by an-/// evaluation of the live tree and current facts that found the witness, and is cleared by any-/// such evaluation that completed with no witness. An evaluation of an overlaid or hypothetical-/// state must never write here, because that is the one way to plant an entry whose "was true"-/// half is false - the read-side re-verification only re-establishes the "is true now" half.-#[derive(Clone, Default)]-pub struct RelationalWitnesses {- entries: HashMap<RelationalWitnessKey, StyleNodeID>,-}--impl RelationalWitnesses {- /// Retain `witness` for `key`, returning whether it was stored. A full table sheds the- /// entries whose anchor or witness identity has been retired before refusing.- pub fn retain(&mut self, key: RelationalWitnessKey, witness: StyleNodeID, tree: &StyleNodeTree) -> bool {- if self.entries.len() >= MAX_RETAINED_WITNESSES {- if let Some(retained) = self.entries.get_mut(&key) {- *retained = witness;- return true;- }- self.entries- .retain(|entry, retained| tree.is_live(entry.anchor) && tree.is_live(*retained));- if self.entries.len() >= MAX_RETAINED_WITNESSES {- return false;- }- }- self.entries.insert(key, witness);- true- }-- pub fn clear(&mut self, key: RelationalWitnessKey) {- self.entries.remove(&key);- }-- pub fn clear_all(&mut self) {- self.entries = HashMap::default();- }-}--impl RelationalWitnesses {- pub(super) fn lookup(&self, key: RelationalWitnessKey) -> Lookup<&StyleNodeID, RelationalWitnessGap> {- match self.entries.get(&key) {- Some(witness) => Lookup::Known(witness),- None => Lookup::Missing(RelationalWitnessGap::MissingEntry(key)),- }- }-}--/// Candidate witnesses for one anchor, along the query's axis.-pub fn candidate_witnesses(- axis: RelativeAxis,- below_the_axis: bool,- anchor: StyleNodeID,- tree: &StyleNodeTree,- mut visit: impl FnMut(StyleNodeID) -> bool,-) {- match axis {- RelativeAxis::Child => {- for child in tree.children(anchor) {- if !visit(child) {- return;- }- }- }- RelativeAxis::Descendant => {- for node in tree.preorder(anchor) {- if node == anchor {- continue;- }- if !visit(node) {- return;- }- }- }- RelativeAxis::NextSibling => {- if let Some(next) = tree.next_element_sibling(anchor) {- visit(next);- }- }- RelativeAxis::FollowingSibling => {- let mut current = tree.next_element_sibling(anchor);- while let Some(sibling) = current {- if !visit(sibling) {- return;- }- current = tree.next_element_sibling(sibling);- }- }- // The witness lies under the sibling rather than being it, so the sibling's whole subtree- // is the candidate range.- RelativeAxis::NextSiblingSubtree => {- if let Some(next) = tree.next_element_sibling(anchor) {- for node in tree.preorder(next) {- if below_the_axis && node == next {- continue;- }- if !visit(node) {- return;- }- }- }- }- RelativeAxis::FollowingSiblingSubtree => {- let mut current = tree.next_element_sibling(anchor);- while let Some(sibling) = current {- for node in tree.preorder(sibling) {- if below_the_axis && node == sibling {- continue;- }- if !visit(node) {- return;- }- }- current = tree.next_element_sibling(sibling);- }- }- }-}--#[cfg(test)]-mod tests {- use super::super::index::StyleAtomID;- use super::*;-- const ERROR_CLASS: LocalFeatureKey = LocalFeatureKey::Class(StyleAtomID(1));-- /// `root > [card > [a, b, c], other]`- struct Fixture {- tree: StyleNodeTree,- nodes: Vec<StyleNodeID>,- }-- impl Fixture {- fn new() -> Self {- let mut tree = StyleNodeTree::new();- let nodes: Vec<StyleNodeID> = (0..6).map(|_| tree.allocate_element()).collect();- // 0 root, 1 card, 2 other; card's children 3, 4, 5- tree.set_first_element_child(nodes[0], Some(nodes[1]));- tree.set_parent(nodes[1], Some(nodes[0]));- tree.set_parent(nodes[2], Some(nodes[0]));- tree.set_next_element_sibling(nodes[1], Some(nodes[2]));- tree.set_previous_element_sibling(nodes[2], Some(nodes[1]));- tree.set_first_element_child(nodes[1], Some(nodes[3]));- for index in 3..6 {- tree.set_parent(nodes[index], Some(nodes[1]));- tree.set_next_element_sibling(nodes[index], nodes.get(index + 1).copied());- tree.set_previous_element_sibling(nodes[index], (index > 3).then(|| nodes[index - 1]));- }-- Self { tree, nodes }- }-- fn anchors(&self, axis: RelativeAxis, witness: usize) -> Vec<usize> {- let mut found = Vec::new();- possible_anchors(axis, self.nodes[witness], &self.tree, None, |anchor| {- found.push(self.nodes.iter().position(|node| *node == anchor).unwrap());- });- found- }- }-- #[test]- fn a_child_query_has_exactly_one_possible_anchor() {- let fixture = Fixture::new();- assert_eq!(fixture.anchors(RelativeAxis::Child, 4), vec![1]);- }-- #[test]- fn an_adjacent_sibling_query_has_exactly_one_possible_anchor() {- let fixture = Fixture::new();- assert_eq!(fixture.anchors(RelativeAxis::NextSibling, 4), vec![3]);- assert_eq!(- fixture.anchors(RelativeAxis::NextSibling, 3),- Vec::<usize>::new(),- "a first child has no preceding sibling to anchor a + query"- );- }-- #[test]- fn a_descendant_query_walks_the_ancestor_path() {- let fixture = Fixture::new();- assert_eq!(fixture.anchors(RelativeAxis::Descendant, 4), vec![1, 0]);- }-- #[test]- fn a_descendant_query_stops_at_its_scope_boundary() {- let fixture = Fixture::new();- let mut found = Vec::new();- possible_anchors(- RelativeAxis::Descendant,- fixture.nodes[4],- &fixture.tree,- Some(fixture.nodes[1]),- |anchor| found.push(anchor),- );- assert_eq!(found, vec![fixture.nodes[1]]);- }-- #[test]- fn a_following_sibling_query_anchors_on_preceding_siblings() {- let fixture = Fixture::new();- assert_eq!(fixture.anchors(RelativeAxis::FollowingSibling, 5), vec![3, 4]);- }-- #[test]- fn a_simple_query_needs_a_positive_driving_feature() {- let with_feature = RelativeQuery {- axis: RelativeAxis::Descendant,- compound: SelectorNodeID(0),- driving_feature: Some(ERROR_CLASS),- simple: true,- witness_is_below_the_axis: false,- match_in_shadow_tree: false,- };- assert!(with_feature.is_simple());-- let without = RelativeQuery {- driving_feature: None,- ..with_feature- };- assert!(!without.is_simple(), "nothing to drive a replacement search from");-- let complex = RelativeQuery {- simple: false,- ..with_feature- };- assert!(!complex.is_simple());- }-- #[test]- fn an_evicted_relational_witness_is_a_typed_missing_entry() {- let fixture = Fixture::new();- let key = RelationalWitnessKey {- program: SelectorProgramID(1),- query: RelativeQueryID(2),- anchor: fixture.nodes[1],- };- let witness = fixture.nodes[4];- let mut witnesses = RelationalWitnesses::default();-- assert!(matches!(- witnesses.lookup(key),- Lookup::Missing(RelationalWitnessGap::MissingEntry(missing)) if missing == key- ));- assert!(witnesses.retain(key, witness, &fixture.tree));- assert!(matches!(witnesses.lookup(key), Lookup::Known(&retained) if retained == witness));-- witnesses.clear_all();- assert!(matches!(- witnesses.lookup(key),- Lookup::Missing(RelationalWitnessGap::MissingEntry(missing)) if missing == key- ));- }-}diff --git a/Libraries/LibWeb/Rust/src/css/style/rule_writes.rs b/Libraries/LibWeb/Rust/src/css/style/rule_writes.rsindex 8ff8420fa19..b7117e4491a 100644--- a/Libraries/LibWeb/Rust/src/css/style/rule_writes.rs+++ b/Libraries/LibWeb/Rust/src/css/style/rule_writes.rs@@ -13,14 +13,12 @@use super::StyleEngine;use super::bridge::{BoundScopeChain, FfiCascadeOrigin, intern_native_text, publish_rule_declarations, publish_style_rule,- publish_style_rule_selectors, publish_user_agent_style_rule,+ publish_style_rule_selectors,};-use super::compiler::NamespaceScope;-use super::program::{CascadeLayerID, RuleID, RuleKind, SheetID, StyleSheetObjectID};+use super::pipeline::rule_store::{CascadeLayerID, RuleDeclarations, RuleID, RuleKind, SheetID};use super::tree::TreeScopeID;use crate::css::container_conditions::ContainerConditionsData;-use crate::css::declaration_block::DeclarationBlockData;-use crate::css::selector::CompiledSelector;+use crate::css::declaration_block::SharedDeclarationBlock;use crate::css::selector_parser::RustParsedSelectorList;use crate::css::style_sheet::NativeStyleSheet;use crate::fast_hash::FastMap;@@ -102,82 +100,10 @@ fn bit(identity: u64) -> u128 {1 << (identity % IDENTITIES_PER_WORD)}-/// The namespaces a sheet declares, as text, which the engine interns as it compiles the sheet's selectors.-pub(crate) struct NamespaceTexts {- declared: Box<[DeclaredNamespace]>,-}--/// A declared namespace prefix, empty for the default namespace, and the namespace it names.-struct DeclaredNamespace {- prefix: Box<[u16]>,- uri: Box<[u16]>,-}--impl NamespaceTexts {- /// The namespaces `native` declares, or none where it declares none.- pub(crate) fn of(native: &NativeStyleSheet) -> Option<Arc<Self>> {- let mut declared = Vec::new();- native.rules().for_each_namespace(|namespace| {- declared.push(DeclaredNamespace {- prefix: namespace.prefix.units().into(),- uri: namespace.uri.units().into(),- });- });- (!declared.is_empty()).then(|| {- Arc::new(Self {- declared: declared.into(),- })- })- }-- /// The namespaces `texts` declares, as the atoms `intern` interns their texts as.- pub(super) fn scope(texts: Option<&Self>, mut intern: impl FnMut(&[u16]) -> super::StyleAtomID) -> NamespaceScope {- let mut scope = NamespaceScope::default();- for DeclaredNamespace { prefix, uri } in texts.map_or(&[][..], |texts| &texts.declared) {- let uri = if uri.is_empty() {- super::StyleAtomID::NONE- } else {- intern(uri)- };- if prefix.is_empty() {- scope.default = Some(uri);- } else {- scope.by_prefix.push((intern(prefix), uri));- }- }- scope- }-}--/// A style rule's bound selectors, the scopes it is inside, and the namespaces its sheet declares.+/// A style rule's bound selectors and the scopes it is inside.pub(crate) struct BoundSelectors {pub(crate) selectors: Arc<RustParsedSelectorList>,pub(crate) scope: Arc<BoundScopeChain>,- pub(crate) namespaces: Option<Arc<NamespaceTexts>>,-}--impl BoundSelectors {- /// Lends `publish` the selectors and the scopes they are inside, with the namespaces their sheet declares, which- /// the engine interns first.- fn compile<R>(- &self,- engine: &mut StyleEngine,- publish: impl FnOnce(&mut StyleEngine, &[&CompiledSelector], NamespaceScope, &BoundScopeChain) -> R,- ) -> R {- let namespaces = NamespaceTexts::scope(self.namespaces.as_deref(), |text| intern_native_text(engine, text));- publish(engine, &self.compiled(), namespaces, &self.scope)- }-- /// Publishes the selectors of `rule`, a rule of a user-agent sheet, with the program the process compiled for them,- /// or answers `None` where the rule is not one or the engine compiles its own.- fn publish_user_agent(&self, engine: &mut StyleEngine, sheet: u32, before: u32, rule: u64) -> Option<u32> {- let namespaces = self.namespaces.as_deref();- publish_user_agent_style_rule(engine, sheet, before, rule, &self.compiled(), namespaces, &self.scope)- }-- fn compiled(&self) -> Vec<&CompiledSelector> {- self.selectors.selectors.iter().map(AsRef::as_ref).collect()- }}/// What a compiled rule is to the engine.@@ -197,7 +123,7 @@ pub(crate) enum CompiledRuleKind {pub(crate) struct CompiledRule {pub(crate) identity: u64,pub(crate) kind: CompiledRuleKind,- pub(crate) declarations: Option<Arc<DeclarationBlockData>>,+ pub(crate) declarations: Option<SharedDeclarationBlock>,/// The native sheet the rule comes from, which may be a sheet the rule's sheet imports.pub(crate) source_identity: u64,pub(crate) conditions_hold: bool,@@ -215,13 +141,7 @@ impl CompiledRule {.map(|sheet| (SheetID(sheet), before.checked_sub(1).map(RuleID)));let rule = match &self.kind {CompiledRuleKind::Style { selectors, .. } => {- let id = selectors- .publish_user_agent(engine, sheet, before, self.identity)- .unwrap_or_else(|| {- selectors.compile(engine, |engine, compiled, namespaces, scope| {- publish_style_rule(engine, sheet, before, compiled, namespaces, scope)- })- });+ let id = publish_style_rule(engine, sheet, before, &selectors.selectors.selectors, &selectors.scope);if let Some(declarations) = &self.declarations {publish_rule_declarations(engine, id, declarations);}@@ -269,9 +189,8 @@ impl CompiledRule {engine.register_native_rule(rule,self.identity,- self.declarations,self.source_identity,- &self.layer_name,+ self.layer_name,self.containers,);}@@ -280,11 +199,10 @@ impl CompiledRule {/// A write to a document's style sheets, which the engine applies in the order the host made it.pub(crate) enum RuleWrite {/// The engine adds the sheet the host numbered `sheet`, which cascades in `origin`.- AddSheet {- sheet: u32,- object: u32,- origin: FfiCascadeOrigin,- },+ AddSheet { sheet: u32, origin: FfiCascadeOrigin },+ /// The engine adds the sheet the host numbered `sheet`, which stands for the user agent sheet the process published+ /// from the native sheet `source_identity`.+ AddUserAgentSheet { sheet: u32, source_identity: u64 },/// The engine begins to replace the rules of `sheet`, keeping the identities of those the replacement keeps.BeginSheetRulesReplacement(u32),/// Rules the host compiled into `sheet`, in order, ahead of the rule `before` names, or at the sheet's end.@@ -300,7 +218,7 @@ pub(crate) enum RuleWrite {/// The rule `identity` declares `declarations`.RuleDeclarations {identity: u64,- declarations: Option<Arc<DeclarationBlockData>>,+ declarations: Option<SharedDeclarationBlock>,},/// Whether the conditions of each rule hold.RuleConditions(Box<[(u64, bool)]>),@@ -311,8 +229,12 @@ pub(crate) enum RuleWrite {impl RuleWrite {pub(crate) fn apply(self, engine: &mut StyleEngine) {match self {- Self::AddSheet { sheet, object, origin } => {- let added = engine.add_sheet(StyleSheetObjectID(object), origin.decode());+ Self::AddSheet { sheet, origin } => {+ let added = engine.add_sheet(origin.decode());+ assert_eq!(added.0 + 1, sheet, "the engine numbers a sheet as its host did");+ }+ Self::AddUserAgentSheet { sheet, source_identity } => {+ let added = engine.add_user_agent_sheet(source_identity);assert_eq!(added.0 + 1, sheet, "the engine numbers a sheet as its host did");}Self::BeginSheetRulesReplacement(sheet) => {@@ -322,17 +244,13 @@ impl RuleWrite {}Self::PublishRules { sheet, before, rules } => {let before = rule_number(engine, before);- engine.publish_sheet_rules(sheet, |engine| {- for rule in rules {- rule.publish(engine, sheet, before);- }- });+ for rule in rules {+ rule.publish(engine, sheet, before);+ }}Self::ReplaceSelectors { identity, selectors } => {let rule = rule_number(engine, identity);- selectors.compile(engine, |engine, compiled, namespaces, scope| {- publish_style_rule_selectors(engine, rule, compiled, namespaces, scope);- });+ publish_style_rule_selectors(engine, rule, &selectors.selectors.selectors, &selectors.scope);}Self::RemoveRules(identities) => {for identity in identities {@@ -378,29 +296,57 @@ fn rule_number(engine: &StyleEngine, identity: u64) -> u32 {/// Publishes `declarations` as what the engine's rule `rule` declares.pub(crate) fn publish_native_rule_declarations(engine: &mut StyleEngine,- declarations: Option<Arc<DeclarationBlockData>>,+ declarations: Option<SharedDeclarationBlock>,rule: RuleID,) {- engine.native_rules.targets.get_mut(&rule).unwrap().declarations = declarations.clone();let version = engine.next_declaration_block_version();engine.record_rule_declarations_changed(rule, version);- if let Some(declarations) = &declarations {- publish_rule_declarations(engine, rule.0 + 1, declarations);+ match &declarations {+ Some(declarations) => {+ publish_rule_declarations(engine, rule.0 + 1, declarations);+ }+ None => engine.stage_rule_declarations(rule, RuleDeclarations::default()),}}/// Adds a sheet to the document's style engine, which cascades in `origin`, and answers the number the host gave it.#[unsafe(no_mangle)]-pub extern "C" fn style_engine_add_sheet(+pub extern "C" fn style_engine_add_sheet(host: &crate::render_state::DocumentHost, origin: FfiCascadeOrigin) -> u32 {+ let sheet = host.published_rules().mint_sheet();+ host.write_rules(RuleWrite::AddSheet { sheet, origin });+ sheet+}++/// Publishes `rules`, compiled from the native user agent sheet `source_identity`, as the process's. Each rule's+/// conditions are its document's, which the document notes where they do not hold.+pub(crate) fn publish_user_agent_sheet(source_identity: u64, rules: Vec<CompiledRule>) {+ crate::render_state::process_style().publish_user_agent_sheet(source_identity, |engine, sheet| {+ for mut rule in rules {+ assert!(!rule.in_a_layer, "no user agent rule cascades in a layer");+ rule.conditions_hold = true;+ rule.publish(engine, sheet.0 + 1, 0);+ }+ });+}++/// Adds a sheet to the document's style engine standing for the user agent sheet the process published from the native+/// sheet `source_identity`, and answers the number the host gave it.+#[unsafe(no_mangle)]+pub extern "C" fn style_engine_add_user_agent_sheet(host: &crate::render_state::DocumentHost,- object: u32,- origin: FfiCascadeOrigin,+ source_identity: u64,) -> u32 {let sheet = host.published_rules().mint_sheet();- host.write_rules(RuleWrite::AddSheet { sheet, object, origin });+ host.write_rules(RuleWrite::AddUserAgentSheet { sheet, source_identity });sheet}+/// Has the render owner apply the rule writes the host queued now, beside the host's task rather than in its next job.+#[unsafe(no_mangle)]+pub extern "C" fn style_engine_stream_rule_writes(host: &crate::render_state::DocumentHost) {+ host.stream_writes_now();+}+/// Begins to replace the rules of the sheet `sheet`, whose rules the host compiles again, or none.#[unsafe(no_mangle)]pub extern "C" fn style_engine_begin_sheet_rules_replacement(host: &crate::render_state::DocumentHost, sheet: u32) {diff --git a/Libraries/LibWeb/Rust/src/css/style/selector.rs b/Libraries/LibWeb/Rust/src/css/style/selector.rsindex d3a3e47962a..e8cde671d87 100644--- a/Libraries/LibWeb/Rust/src/css/style/selector.rs+++ b/Libraries/LibWeb/Rust/src/css/style/selector.rs@@ -4,8224 +4,477 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The selector logical IR and its match program.-//!-//! Selectors compile into a compact logical IR that defines semantic equality independently of how-//! an operator is evaluated. Every selector then has two views of the same semantics: a match-//! program answering "does this candidate subject match", and a transpose program answering "which-//! subjects could have changed". This module owns the IR and the match program; the transpose-//! direction is built on the same nodes.-//!-//! The match program is exact and evaluates right to left. A complex selector's subject is its-//! rightmost compound, and every combinator becomes an operator constraining that subject-//! leftwards: `A B` is "the subject satisfies B, and some ancestor satisfies A". Compound operands-//! are ordered cheap and high-rejection first at compile time, so the common case is a failed-//! integer comparison rather than a tree walk.-//!-//! A compound with no relational operator allocates nothing per candidate: no witness, no context,-//! no summary, no engine node. That is the ordinary path, and it is the path that has to be fastest.-//!-//! Shadow, scope, pseudo-element, and relational operators are deliberately absent here. Each-//! arrives with the semantics it needs rather than as a placeholder that would have to be guessed-//! at now.+//! What a match keeps as it runs: where elements stand among their siblings, the answers of the+//! tests that read them, and what walks back across `~` found, with the attribute value tests.-use super::column::BitColumn;-use super::column::Column;use super::column::PagedColumn;use super::column::PagedColumnPage;use super::fast_hash::FastMap as HashMap;-use super::fast_hash::FastSet as HashSet;-use super::fast_hash::fast_hasher;-use super::index::DispatchKey;-use super::index::FeatureKey;use super::index::StyleAtomID;-use super::index::StyleNodeFacts;-use super::index::dispatch_bloom_bit;-use super::instrumentation::Counters;-use super::shared_vector::{SharedVector, SharedVectorPool};-use super::weak_pool::WeakPool;use smallvec::SmallVec;use std::hash::Hash;-use std::hash::Hasher;-use std::marker::PhantomData;-use std::num::NonZeroU32;-use std::sync::Arc;-use std::sync::Mutex;-use std::sync::MutexGuard;-use std::sync::OnceLock;-use super::TransactionFactSide;-use super::TransactionFactView;-use super::partial_view::Lookup;-use super::planning::SequenceEntry;-use super::planning::SequenceEntryIndex;-use super::planning::SiblingCandidateWorkspace;-use super::program::EntryID;-use super::program::RuleID;-use super::program::SelectorProgramID;-use super::program::StyleSheetProgram;-use super::relative_selector::RelationalWitnessKey;-use super::relative_selector::RelativeAxis;-use super::relative_selector::RelativeQuery;-use super::relative_selector::RelativeQueryID;-use super::relative_selector::WitnessEffect;-use super::relative_selector::candidate_witnesses;-use super::selector_evaluation::ElementFeatures;-use super::selector_evaluation::RememberedPrefix;-use super::selector_evaluation::SelectorBindings;use super::selector_evaluation::SelectorEvaluator;use super::selector_evaluation::SelectorSubject;-use super::selector_evaluation::SelectorTree;-use super::transaction::StateFact;-use super::tree::PseudoElementTarget;use super::tree::StyleNodeID;-use super::tree::StyleNodeTree;-use super::tree::TreeScopeID;-use crate::css::css_tokenizer::TokenizerInput;pub use crate::css::selector::Specificity;-define_id! {- /// Index into one program's node arena.- pub struct SelectorNodeID(pub);-}--/// How an attribute selector compares its value.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]-pub enum AttributeOperator {- /// `[attr]`- Presence,- /// `[attr=value]`- Exact,- /// `[attr~=value]`- Includes,- /// `[attr|=value]`- DashMatch,- /// `[attr^=value]`- Prefix,- /// `[attr$=value]`- Suffix,- /// `[attr*=value]`- Substring,-}--impl From<crate::css::selector::AttributeMatchType> for AttributeOperator {- fn from(value: crate::css::selector::AttributeMatchType) -> Self {- use crate::css::selector::AttributeMatchType;- match value {- AttributeMatchType::HasAttribute => AttributeOperator::Presence,- AttributeMatchType::ExactValue => AttributeOperator::Exact,- AttributeMatchType::ContainsWord => AttributeOperator::Includes,- AttributeMatchType::ContainsString => AttributeOperator::Substring,- AttributeMatchType::StartsWithSegment => AttributeOperator::DashMatch,- AttributeMatchType::StartsWithString => AttributeOperator::Prefix,- AttributeMatchType::EndsWithString => AttributeOperator::Suffix,- }- }-}--impl AttributeOperator {- /// Whether the operator can be answered by comparing interned identities. Everything else has- /// to read the value as text, which is why the batch only carries text for those attributes.- #[must_use]- pub fn is_answerable_by_atom(self) -> bool {- matches!(self, Self::Presence | Self::Exact)- }-}--#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]-pub enum AttributeCase {- Sensitive,- /// ASCII case-insensitive, whether from the `i` flag or from a language-defined rule.- Insensitive,- /// ASCII case-insensitive for an element in this namespace and case-sensitive for any other.- ///- /// https://html.spec.whatwg.org/multipage/semantics-other.html#case-sensitivity-of-selectors- /// A handful of attribute names compare their values ASCII case-insensitively, but only on an- /// HTML element in an HTML document, so which rule applies is a fact about the subject rather- /// than about the selector. The namespace is HTML's, and only in an HTML document: outside one- /// the compiler emits `Sensitive` and this never appears.- InsensitiveForNamespace(StyleAtomID),-}--/// One attribute test. The literal lives in the program: as an atom when it was worth interning,-/// and always as text when the operator cannot be answered by identity.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]-pub struct AttributeTest {- /// The atom the test names: an attribute's qualified form for `[ns|x]`, its bare local name for- /// `[x]`, and the any-namespace form for `[*|x]`.- pub name: StyleAtomID,- /// Whether `name` is the any-namespace form, in which case it is matched against an attribute's- /// shared `local` rather than against its own name. `[*|x]` names one attribute per namespace the- /// element carries `x` in, and holds when any of them satisfies the test.- pub any_namespace: bool,- /// The ASCII-lowercase folding of `name`, equal to it when the name is already lowercase.- ///- /// The lowercase selector name applies to HTML elements in HTML documents, and the written- /// selector name applies elsewhere. Both compare with the written attribute name. Both forms- /// are carried in one test for the same reason `TagTest` does it: a disjunction of two attribute- /// tests would widen the enclosing compound's dispatch key to universal.- pub folded: StyleAtomID,- /// The namespace an element has to be in for `folded` to apply - the HTML namespace in an HTML- /// document - or `NONE` where nothing folds.- pub fold_in_namespace: StyleAtomID,- pub operator: AttributeOperator,- pub value_atom: StyleAtomID,- pub value_offset: u32,- pub value_length: u32,- pub case: AttributeCase,-}--/// A type selector's name, in the form it was written and in its ASCII-lowercase folding.-///-/// The lowercase selector name applies to HTML elements in HTML documents, and the written name-/// applies elsewhere. Both compare with the element's written local name. So `DIV` still has to-/// reach `<div>`, while `foreignobject` must not reach an SVG `foreignObject`.-/// Carrying both forms in one test keeps that a single feature: expressing-/// it as a disjunction of two tag tests would widen the enclosing compound's dispatch key to-/// universal, and a compound that dispatches universally rejects nothing.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]-pub struct TagTest {- pub written: StyleAtomID,- /// Equal to `written` when the name is already ASCII-lowercase, which is the common case.- pub folded: StyleAtomID,- /// The namespace an element has to be in for the folded form to apply, or `NONE` where nothing- /// folds. It is the HTML namespace in an HTML document and nothing at all in an XML one, where- /// a type selector is case-sensitive however it was written.- pub fold_in_namespace: StyleAtomID,-}--impl TagTest {- /// A name that is its own folding.- #[must_use]- #[cfg(test)]- pub fn exact(name: StyleAtomID) -> Self {- Self {- written: name,- folded: name,- fold_in_namespace: StyleAtomID::NONE,- }- }-}--/// A test against one local fact of a candidate.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]-pub enum FeatureTest {- /// `*`- AnyElement,- /// A qualified name, as one interned tag/namespace atom.- TagName(TagTest),- Id(StyleAtomID),- Class(StyleAtomID),- Attribute(AttributeTest),- /// What namespace the subject must be in. A type or universal selector written with a prefix- /// carries one, and so does every one of them in a sheet that declared a default namespace.- Namespace(NamespaceTest),-}--/// The namespace a qualified name constrains its subject to.-///-/// `*|x` places no constraint and compiles to nothing. The other two do, which is why they are the-/// only shapes here: a prefixed name names one namespace, and `|x` names the absence of one.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]-pub enum NamespaceTest {- /// `|x`, and `x` in a sheet with no default namespace declared: the subject is in no namespace.- None,- /// `ns|x`, and `x` in a sheet whose default namespace is `ns`.- Named(StyleAtomID),-}--/// Where in a sibling sequence a subject can be, when a positional test bounds it.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]-pub struct SubjectPosition {- pub from_end: bool,- /// How many positions from that end the subject can occupy. `u32::MAX` means unbounded.- pub bound: u32,-}--impl SubjectPosition {- pub const UNBOUNDED: Self = Self {- from_end: false,- bound: u32::MAX,- };-}--/// An `an+b` positional test, optionally restricted to siblings matching a selector or sharing a-/// type.+/// An `an+b` positional test, optionally restricted to siblings sharing a type.#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]pub struct NthPosition {pub step: i32,pub offset: i32,/// `:nth-last-child()` and `:nth-last-of-type()` count from the end.pub from_end: bool,- /// `of <selector>`: only siblings matching this contribute to the count.- pub of_selector: Option<SelectorNodeID>,/// `:nth-of-type()` family: only siblings sharing the subject's type contribute.pub of_type: bool,}-/// A structural test a prefix compound can carry: truth is a function of the subject's tree-/// position or child content rather than its own interned facts, answered per node into the-/// automaton's truth bits.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]-pub enum PrefixStructuralTest {- Nth(NthPosition),- Empty,-}--impl NthPosition {- /// Whether an element holding `count` matches this position's an+b test. The count must- /// already be in this position's own terms: from the right end for `from_end`, over the- /// qualified subsequence for `of_type` and `of_selector` forms.- #[must_use]- pub(super) fn matches_count(self, count: i64) -> bool {- matches_an_plus_b(self.step, self.offset, count)- }-- /// Whether shifting from `current` to any count in the inclusive old-count range could flip- /// this position. Sequence routing retains only aggregate arrival and departure counts, so the- /// range can be wider than the one count the element actually held but never narrower.- #[must_use]- pub(super) fn could_change_from_range(self, current: i64, first: i64, last: i64) -> bool {- let current_matches = matches_an_plus_b(self.step, self.offset, current);- match current_matches {- true => !an_plus_b_matches_every_count(self.step, self.offset, first, last),- false => an_plus_b_matches_any_count(self.step, self.offset, first, last),- }- }-}--fn an_plus_b_matches_any_count(step: i32, offset: i32, first: i64, last: i64) -> bool {- debug_assert!(first <= last);- let step = i64::from(step);- let offset = i64::from(offset);- match step.cmp(&0) {- std::cmp::Ordering::Equal => (first..=last).contains(&offset),- std::cmp::Ordering::Greater => {- let n = if first <= offset {- 0- } else {- (first - offset + step - 1) / step- };- offset + step * n <= last- }- std::cmp::Ordering::Less => {- if first > offset {- return false;- }- let magnitude = -step;- let upper = last.min(offset);- let n = (offset - upper + magnitude - 1) / magnitude;- offset - magnitude * n >= first- }- }-}--fn an_plus_b_matches_every_count(step: i32, offset: i32, first: i64, last: i64) -> bool {- debug_assert!(first <= last);- if first == last {- return matches_an_plus_b(step, offset, first);- }- match step {- 1 => first >= i64::from(offset),- -1 => last <= i64::from(offset),- _ => false,- }-}--/// One operator of the logical IR.-///-/// Combinators are expressed as constraints on the subject, which is the direction evaluation runs-/// in. `Ancestor(inner)` means "some ancestor of the subject satisfies inner", so the match-/// program for `A B` is `And[B, Ancestor(A)]`.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]-pub enum SelectorOp {- Feature(FeatureTest),- State(StateFact),- /// A compound, or an explicit conjunction. Operands are stored in a slice and ordered cheap- /// first at compile time.- And {- first: u32,- count: u32,- },- /// A selector list or `:is()`. Contributes the greatest specificity of its branches.- Or {- first: u32,- count: u32,- },- /// `:where()`: evaluates its operand and contributes no specificity.- Where(SelectorNodeID),- Not(SelectorNodeID),- /// `A > B`, evaluated from B.- Parent(SelectorNodeID),- /// `A B`, evaluated from B.- Ancestor(SelectorNodeID),- /// `A + B`, evaluated from B: the immediately preceding element sibling satisfies A.- PreviousSibling(SelectorNodeID),- /// `A ~ B`, evaluated from B: some preceding element sibling satisfies A.- PrecedingSibling(SelectorNodeID),- NthPosition(NthPosition),- /// `:has()`: an existential query relating this subject, as anchor, to a witness.- RelativeExists(RelativeQueryID),- /// `:host` / `:host()`: the subject is the shadow host of the tree this rule is attached to,- /// and satisfies the inner compound. Consumes the host relation, not DOM ancestry.- Host(SelectorNodeID),- /// `::slotted()`: the subject is assigned to a slot and satisfies the inner compound. Consumes- /// the slot-assignment relation.- Slotted(SelectorNodeID),- /// `::part()`: the subject exposes the named part. Consumes the part-exposure relation.- Part(StyleAtomID),- /// `X::part(p)` from the part element: the shadow host of the tree this node is in satisfies- /// `X`. A part compound describes two elements - the host and the element exposing the part -- /// so the host half is a step, not a conjunct.- ///- /// The names are held here rather than beside this op because `exportparts` forwards a name- /// outwards under a name of the host's choosing: each level of forwarding exposes its own names- /// to its own host, so `p` and `X` only describe an element when one level answers both. Testing- /// them as separate conjuncts would let a name from one level pair with a host from another.- ExposedToHost {- host: SelectorNodeID,- parts: SelectorNodeID,- },- /// `X::file-selector-button:hover` from the host: the element of the host's shadow tree that- /// stands for its element-backed pseudo-element of `kind` satisfies `inner`, the pseudo-classes- /// written after the pseudo-element. Those describe the pseudo-element rather than the host,- /// so they are a step to the element backing it, not conjuncts on the host.- BackingElement {- kind: u16,- inner: SelectorNodeID,- },- /// `:root`: the subject is the root of its tree.- Root,- /// `:empty`: the subject has no element or significant text children.- Empty,- /// `:scope`: the subject is the scoping root of the rule's `@scope`, or the document root.- Scope,- /// `slot::slotted(x)` from the slotted element: the slot it is assigned to satisfies the- /// compound written before `::slotted()`.- ///- /// That compound describes the slot and not the subject - the subject is the element the slot- /// stands in for - so it is a step, not a conjunct. A slot is itself a slottable, so the step- /// follows the whole assignment chain and takes the slot that is in the tree being asked.- AssignedSlot(SelectorNodeID),- /// `:scope` inside a `<scope-end>`: the subject is the scoping root of the scope instance the- /// limit is being checked against.- ///- /// One `@scope` builds one scope per element its `<scope-start>` matches, and a limit is- /// relative to each of them separately. Compiling `:scope` to the root selector would ask- /// whether *some* element matching it stands there, which excludes an element from a scope its- /// own root does not exclude it from.- ScopeRootInstance,- /// The subject is the anchor of the relational query being evaluated.- ///- /// A relative selector's chain is compiled as constraints on the witness, which cannot say on- /// its own where the chain started: `:has(+ div > .test)` would accept any `.test` whose parent- /// is a `div` rather than one whose parent is the anchor's next sibling. Ending the chain here- /// ties its leftmost step back to the anchor, which is what makes the query exact.- RelativeAnchorInstance,- /// The subject is one particular element, named by identity rather than by any feature.- ///- /// An `@scope` written without a `<scope-start>` roots at the parent of its sheet's owner node,- /// which is an element and not a selector. Compiling it to an identity test is what lets the- /// implied `:scope ` prefix, the proximity count and the limits all fall out of the machinery a- /// written root already uses.- IsNode(StyleNodeID),- /// The subject is in one scope an `@scope` opens, and satisfies `inner` under that scope.- ///- /// A scope is not a constraint the subject can carry on its own. One `@scope` builds one scope- /// per element its `<scope-start>` matches, and everything the rule says is relative to *one* of- /// them: `:scope` names that element, a limit excludes relative to it, and proximity counts to- /// it. So this walks the subject's inclusive ancestors for a root, binds each one in turn, and- /// asks `inner` under the binding - which is the specification's "for each element matched by- /// `<scope-start>`, create a scope using that element as the scoping root".- ///- /// `names_the_scope` says whether the subject may be the root itself. A scoped selector carries- /// an implied `:scope ` prefix unless it names `:scope`, so it usually cannot.- InScope {- root: SelectorNodeID,- /// The `<scope-end>`, when the scope has one. Nothing from the subject up to the root may- /// match it.- limit: Option<SelectorNodeID>,- inner: SelectorNodeID,- names_the_scope: bool,- },- /// A state whose value is a parameter rather than a boolean: `:dir()`, `:state()`.- ValueState {- kind: ValueStateTestKind,- value: StyleAtomID,- },- /// `:lang()`: the subject's resolved language tag matches one of the extended language ranges- /// named here. A range is not a name - `en` matches `en-GB` - so it cannot be an atom, and the- /// ranges live in the program as literals compared against the tag itself.- Language {- first: u32,- count: u32,- },- /// `:heading()`: a bitmask of the heading levels the subject may have, bit 0 being level 1.- ///- /// Levels run to nine, because a heading counts the heading offset its ancestors declare, and- /// bare `:heading` is every one of them rather than the six an element can be written as.- Heading(u16),-}--/// A selector state test whose value is an interned atom.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]-pub enum ValueStateTestKind {- /// `:dir()`- Directionality,- /// `:state()`, a custom element's state.- CustomState,-}--impl ValueStateTestKind {- fn routing_kind(self) -> ValueStateKind {- match self {- Self::Directionality => ValueStateKind::Directionality,- Self::CustomState => ValueStateKind::CustomState,- }- }-}--/// A value-state input category used by routing.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]-pub enum ValueStateKind {- /// `:dir()`- Directionality,- /// `:state()`, a custom element's state.- CustomState,-}--impl SelectorOp {- /// A static cost rank used to order compound operands. Lower runs first, so a failed integer- /// comparison rejects a candidate before any tree walk starts.- #[must_use]- fn cost_rank(self) -> u8 {- match self {- Self::Feature(FeatureTest::Id(_)) => 0,- Self::Feature(FeatureTest::TagName(_)) => 1,- Self::Feature(FeatureTest::Class(_)) => 2,- // A handful of short subtag comparisons against a tag the element already carries.- Self::Language { .. } => 6,- Self::Feature(FeatureTest::AnyElement) => 3,- // An ancestor walk with a nested evaluation at each step, so it runs after everything a- // lookup can reject.- Self::InScope { .. } => 15,- // One integer comparison against a fact the element always carries.- Self::Feature(FeatureTest::Namespace(_)) => 2,- Self::Feature(FeatureTest::Attribute(test)) => {- if test.operator.is_answerable_by_atom() {- 4- } else {- 5- }- }- Self::State(_) => 6,- Self::Not(_) | Self::Where(_) => 7,- Self::And { .. } | Self::Or { .. } => 8,- Self::NthPosition(_) => 9,- // Shadow operators are a lookup in a sparse relation: cheap, but only meaningful once- // the local compound has already accepted the candidate.- Self::Part(_) => 5,- Self::ExposedToHost { .. } | Self::BackingElement { .. } => 7,- Self::Root | Self::Empty | Self::Scope | Self::ScopeRootInstance => 5,- Self::IsNode(_) | Self::RelativeAnchorInstance => 0,- Self::AssignedSlot(_) => 7,- Self::ValueState { .. } | Self::Heading(_) => 6,- Self::Slotted(_) => 6,- Self::Host(_) => 11,- // Relational queries traverse to answer, so they run after everything local.- Self::RelativeExists(_) => 14,- Self::PreviousSibling(_) => 10,- Self::Parent(_) => 11,- Self::PrecedingSibling(_) => 12,- Self::Ancestor(_) => 13,- }- }-}+// -- Relational arrival keys --------------------------------------------------------------------/// One top-level complex selector of a rule's selector list.-///-/// A pseudo-element target is metadata rather than an operator over the candidate. The entry's-/// program still matches the *originating element*; the target says where the resulting-/// declarations land. That is the whole projection: matching never has to consider pseudo identities-/// as candidates, and a rule targeting `::before` never applies to the element itself.+/// Why a match evaluation could not produce an exact answer.#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]-pub struct SelectorEntry {- pub root: SelectorNodeID,- pub specificity: Specificity,- pub pseudo_element: Option<PseudoElementTarget>,- /// What the rule's `@scope` names as a scoping root, when it has one. Which root a match- /// resolved through decides its proximity, and the cascade compares that between two scoped- /// declarations, so it is answered while matching rather than reconstructed afterwards.- pub scope_root: Option<SelectorNodeID>,- properties: SelectorEntryProperties,+pub enum Incomplete {+ /// The fact batch does not cover a style node the evaluation had to read. This is never a+ /// negative answer: the caller widens the batch or asks a different question.+ MissingFacts(StyleNodeID),}-/// One local compound in an ordinary descendant-or-child selector chain.-///-/// The compiled IR represents a combinator as one operand of the compound to its right. Keeping-/// the relation operand separate lets a top-down evaluator ask the local compound once and answer-/// the relation from the state inherited from its parent.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]-pub(super) struct SelectorPrefixLocal {- pub(super) root: SelectorNodeID,- relation: Option<SelectorNodeID>,+/// Which positional tests an evaluator answers from its workspace's shared sibling index.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(super) enum PositionalIndexPolicy {+ /// Every test, and every answer is memoized. A traversal that styles whole sequences asks+ /// many programs about the same children, which amortizes building each index.+ All,+ /// Only tests with a step, which have to count the whole sequence anyway, and no memo. A+ /// bounded test such as `:first-child` stops at its near end, so a narrow exact ask over+ /// scattered candidates answers it more cheaply than materializing every sequence it walks+ /// through - and asks the same test about the same node too rarely for a memo to pay for+ /// its insertion.+ SteppedOnly,}-/// How one selector prefix is reached from the prefix immediately to its left.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]-pub(super) enum SelectorPrefixAxis {- Root,- Child,- Descendant,- /// The step's compound sits on the sibling immediately after its predecessor's.- NextSibling,- /// The step's compound sits on any sibling after its predecessor's.- FollowingSibling,+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]+pub(super) struct SiblingPositions {+ pub(super) from_start: u32,+ pub(super) from_end: u32,}-/// One left-to-right step of an ordinary selector chain.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]-pub(super) struct SelectorPrefixStep {- pub local: SelectorPrefixLocal,- pub axis: SelectorPrefixAxis,+#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]+struct SiblingSequenceMembership {+ sequence: u32,+ ordinal: u32,}-#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]-struct SelectorEntryProperties {- monotone_under_arrivals: bool,- can_use_before_sibling_relations: bool,- observes_sibling_relation: bool,- has_prefix_chain: bool,- prefix_chain_has_only_local_facts: bool,-}+const VALUE_PAGE_SHIFT: usize = 6;+const VALUE_PAGE_SIZE: usize = 1 << VALUE_PAGE_SHIFT;-/// Immutable routing facts derived from one selector entry's IR.-#[derive(Clone, Debug, PartialEq, Eq, Hash)]-pub(super) struct SelectorDispatchMetadata {- pub key: DispatchKey,- pub required_attribute_value: StyleAtomID,- pub required_parent: Option<DispatchKey>,- pub required_ancestor: Option<DispatchKey>,- pub required_subject_bloom: u64,- subject_dispatch_keys: Box<[DispatchKey]>,- subject_required_keys: Box<[DispatchKey]>,- prefix_chain: Option<Box<[SelectorPrefixStep]>>,+#[derive(Clone)]+struct ValuePage<T: Copy + Default> {+ known: u64,+ values: [T; VALUE_PAGE_SIZE],}-/// Derived acceleration is not part of a selector program's semantic identity.-#[derive(Default)]-struct CachedDispatchMetadata(Box<[SelectorDispatchMetadata]>);--impl PartialEq for CachedDispatchMetadata {- fn eq(&self, _other: &Self) -> bool {- true+impl<T: Copy + Default> Default for ValuePage<T> {+ fn default() -> Self {+ Self {+ known: 0,+ values: [T::default(); VALUE_PAGE_SIZE],+ }}}-impl Eq for CachedDispatchMetadata {}+impl<T: Copy + Default> PagedColumnPage for ValuePage<T> {+ type Value = T;-impl Hash for CachedDispatchMetadata {- fn hash<H: Hasher>(&self, _state: &mut H) {}-}+ const SHIFT: usize = VALUE_PAGE_SHIFT;-impl SelectorDispatchMetadata {- /// Sorted, distinct keys through which this entry can be reached.- #[must_use]- pub(super) fn subject_dispatch_keys(&self) -> &[DispatchKey] {- &self.subject_dispatch_keys+ fn get(&self, index: usize) -> Option<T> {+ (self.known & (1 << index) != 0).then_some(self.values[index])}- #[must_use]- pub(super) fn prefix_chain(&self) -> Option<&[SelectorPrefixStep]> {- self.prefix_chain.as_deref()+ fn insert(&mut self, index: usize, value: T) {+ self.known |= 1 << index;+ self.values[index] = value;}}-#[derive(Clone, Copy, PartialEq, Eq)]-enum DispatchRelation {- Subject,- Parent,- Ancestor,-}+type SiblingPositionColumn = PagedColumn<ValuePage<SiblingPositions>>;+type SiblingSequenceMembershipColumn = PagedColumn<ValuePage<SiblingSequenceMembership>>;-#[derive(Clone, Copy, PartialEq, Eq)]-enum DispatchQuery {- Alternatives,- Required,+#[derive(Clone, Default)]+pub(super) struct SiblingSequenceGeometry {+ sequences: Vec<Box<[StyleNodeID]>>,+ memberships: SiblingSequenceMembershipColumn,}-impl SelectorEntry {- #[must_use]- pub fn is_monotone_under_arrivals(self) -> bool {- self.properties.monotone_under_arrivals+impl SiblingSequenceGeometry {+ fn heap_size(&self) -> usize {+ crate::heap_size::vec_bytes(&self.sequences)+ + self+ .sequences+ .iter()+ .map(|sequence| size_of_val(&**sequence))+ .sum::<usize>()+ + self.memberships.heap_size()}- #[must_use]- pub fn can_use_before_sibling_relations(self) -> bool {- self.properties.can_use_before_sibling_relations+ fn insert_sequence(&mut self, children: Vec<StyleNodeID>) {+ u32::try_from(children.len()).expect("sibling sequence space exhausted");+ let sequence = u32::try_from(self.sequences.len()).expect("sibling sequence index space exhausted");+ for (ordinal, &child) in children.iter().enumerate() {+ self.memberships.insert(+ child+ .element_index()+ .expect("only elements belong to sibling sequences") as usize,+ SiblingSequenceMembership {+ sequence,+ ordinal: u32::try_from(ordinal).expect("sibling sequence space exhausted"),+ },+ );+ }+ self.sequences.push(children.into_boxed_slice());}- #[must_use]- pub fn observes_sibling_relation(self) -> bool {- self.properties.observes_sibling_relation+ fn sequence_and_ordinal(&self, node: StyleNodeID) -> Option<(&[StyleNodeID], u32)> {+ let membership = self.memberships.get(node.element_index()? as usize)?;+ Some((&*self.sequences[membership.sequence as usize], membership.ordinal))}- #[must_use]- pub(super) fn has_prefix_chain(self) -> bool {- self.properties.has_prefix_chain+ fn sibling_sequence(&self, node: StyleNodeID) -> Option<&[StyleNodeID]> {+ self.sequence_and_ordinal(node).map(|(sequence, _)| sequence)}- #[must_use]- pub(super) fn prefix_chain_has_only_local_facts(self) -> bool {- self.properties.prefix_chain_has_only_local_facts+ pub(super) fn sibling_positions(&self, node: StyleNodeID) -> Option<SiblingPositions> {+ let (sequence, ordinal) = self.sequence_and_ordinal(node)?;+ let count = u32::try_from(sequence.len()).expect("sibling sequence space exhausted");+ Some(SiblingPositions {+ from_start: ordinal + 1,+ from_end: count - ordinal,+ })}}-// A local predicate's identity excludes program-relative node IDs and text offsets.-// Prefix matching does not compute specificity, so :where() is transparent here.-#[derive(Clone, Debug, PartialEq, Eq, Hash)]-pub(super) enum SelectorPrefixPredicate {- Leaf(SelectorOp),- Attribute(AttributeTest, Box<[u16]>),- And(Box<[Self]>),- Or(Box<[Self]>),- Not(Box<Self>),- Language(Box<[Box<[u16]>]>),+/// Caller-owned scratch lent exclusively to one evaluator at a time, which reads one tree: the+/// positions and answers it keeps are of that tree.+#[derive(Clone, Default)]+pub struct MatchScratch {+ sibling_geometry: SiblingSequenceGeometry,+ type_positions: SiblingPositionColumn,+ /// The answers of relative queries, by the anchor each was asked for.+ relative_answers: HashMap<RelativeAnswerKey, bool>,+ /// How many of those answers took a walk: each one here did, as an evaluation that finds one takes no walk.+ relative_walks: u64,+ /// The number of the table of what walks back across a subsequent-sibling combinator found, by+ /// what the walks start from.+ sibling_tables: HashMap<SiblingAnswerKey, u32>,+ /// The pages of each table, by the page of the element slots they hold, or `NO_SIBLING_PAGE`:+ /// a table holds pages for the elements its walks passed alone, which a pass styling a few+ /// elements of a large document keeps small.+ sibling_answers: Vec<Vec<u32>>,+ /// What the tables' walks found for each sibling they passed, by its element slot in its+ /// table's page: none yet, false or true.+ sibling_answer_pages: Vec<[u8; SIBLING_ANSWER_PAGE]>,+}++/// How many element slots a page of a sibling answer table holds.+const SIBLING_ANSWER_PAGE: usize = 128;+const NO_SIBLING_PAGE: u32 = u32::MAX;++/// The table of what walks back across one `~` found, among a workspace's.+#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub(super) struct SiblingAnswerTable(u32);++/// What a walk back across `~` found depends on besides the facts of the tree: the compound left of+/// the `~`, and the bindings and part exposure it was evaluated under.+#[derive(Clone, Copy, PartialEq, Eq, Hash)]+pub(super) struct SiblingAnswerKey {+ pub(super) selector: super::selector_evaluation::SelectorKey,+ pub(super) scope_shadow_root: Option<StyleNodeID>,+ pub(super) scope_root_instance: Option<StyleNodeID>,+ pub(super) part_exposure_scope: Option<super::tree::TreeScopeID>,}-impl SelectorPrefixPredicate {}--/// Whose names the atoms of a selector program are.-///-/// A program is evaluated against a subject whose storage is keyed by the same atoms, so the space is part of the-/// program's type: a program compiled for one kind of storage cannot be run against another.-pub trait AtomSpace: Default + PartialEq + Eq + Hash {- /// Whether the subject's storage keys attribute values by atoms, so that an exact value test can compare two.- const KEYS_ATTRIBUTE_VALUES: bool;+/// What a `:has()` argument list's answer for one anchor depends on besides the facts of the tree:+/// the list, and the bindings it was evaluated under, but for the anchor of an enclosing query,+/// which the query binds to its own.+#[derive(Clone, Copy, PartialEq, Eq, Hash)]+pub(super) struct RelativeAnswerKey {+ list: super::selector_evaluation::SelectorListKey,+ anchor: StyleNodeID,+ scope_shadow_root: Option<StyleNodeID>,+ scope_root_instance: Option<StyleNodeID>,+ matching_host_argument: bool,+}++impl RelativeAnswerKey {+ /// The key of the `:has()` argument list `list`, asked for `anchor` under `bindings`.+ pub(super) fn of_list(+ list: super::selector_evaluation::SelectorListKey,+ anchor: StyleNodeID,+ bindings: &super::selector_evaluation::SelectorBindings<StyleNodeID>,+ ) -> Self {+ Self {+ list,+ anchor,+ scope_shadow_root: bindings.scope_shadow_root,+ scope_root_instance: bindings.scope_root_instance,+ matching_host_argument: bindings.matching_host_argument,+ }+ }}-/// The style engine's atoms, which a document's style storage is keyed by.-#[derive(Default, PartialEq, Eq, Hash)]-pub struct EngineAtoms;--impl AtomSpace for EngineAtoms {- const KEYS_ATTRIBUTE_VALUES: bool = true;+/// Where a subject's sibling sequences come from, for [`MatchScratch::indexed_sibling_position`]:+/// the parent of the element asked about and the children of a parent in the tree it reads, and+/// the type of a sibling as its facts tell it.+pub(super) struct SiblingSequenceSource<Children, TypeOf> {+ pub(super) parent: Option<StyleNodeID>,+ pub(super) children: Children,+ pub(super) type_of: TypeOf,}-/// A selector query's own names, interned when the query is compiled and compared with the DOM's names by identity.-#[derive(Default, PartialEq, Eq, Hash)]-pub struct QueryAtoms;--impl AtomSpace for QueryAtoms {- const KEYS_ATTRIBUTE_VALUES: bool = false;-}+impl MatchScratch {+ /// The bytes the scratch keeps on the heap: the sibling sequences, positions and answers it+ /// measured.+ pub(super) fn heap_size(&self) -> usize {+ self.sibling_geometry.heap_size()+ + self.type_positions.heap_size()+ + crate::heap_size::map_bytes(&self.relative_answers)+ + crate::heap_size::map_bytes(&self.sibling_tables)+ + crate::heap_size::vec_bytes(&self.sibling_answers)+ + self+ .sibling_answers+ .iter()+ .map(crate::heap_size::vec_bytes)+ .sum::<usize>()+ + crate::heap_size::vec_bytes(&self.sibling_answer_pages)+ }-/// A compiled selector program: one rule's selector list.-#[derive(Default, PartialEq, Eq, Hash)]-pub struct SelectorProgram<A: AtomSpace = EngineAtoms> {- nodes: Vec<SelectorOp>,- operands: Vec<SelectorNodeID>,- text: Vec<u16>,- entries: Vec<SelectorEntry>,- relative_queries: Vec<RelativeQuery>,- /// Ranges into `text`, one per extended language range a `:lang()` names.- language_ranges: Vec<(u32, u32)>,- /// Immutable dispatch analysis, retained so rebuilding scope dispatches never walks the IR.- dispatch_metadata: CachedDispatchMetadata,- /// Per selector node: the dispatch-bloom bits a node evaluated against that compound must- /// carry — or zero, when nothing certain is required. A combinator walk consults this before- /// trying the compound, so an ancestor that cannot possibly match costs one AND rather than- /// an evaluation. Only always-resident key kinds contribute (id, class, attribute name, tag- /// name); everything else stays out — rather than risking a bit facts never set.- relation_target_blooms: Box<[u64]>,- can_leave_scope: bool,- subject_can_leave_scope: bool,- atoms: PhantomData<A>,-}+ /// Return a sibling position from this scratch, building that sequence on its first ask.+ ///+ /// A broad matching batch asks many positional selectors about the same children. Counting from+ /// an end for every `(selector, child)` pair is quadratic in the sequence length and repeated+ /// across rules.+ pub(super) fn indexed_sibling_position<Children, TypeOf>(+ &mut self,+ position: NthPosition,+ node: StyleNodeID,+ source: SiblingSequenceSource<Children, TypeOf>,+ ) -> Result<Option<i64>, Incomplete>+ where+ Children: FnOnce(StyleNodeID) -> Vec<StyleNodeID>,+ TypeOf: FnMut(StyleNodeID) -> Result<(StyleAtomID, StyleAtomID), Incomplete>,+ {+ let SiblingSequenceSource {+ parent,+ children,+ mut type_of,+ } = source;+ let answer = |cached: SiblingPositions| {+ Ok(Some(i64::from(match position.from_end {+ true => cached.from_end,+ false => cached.from_start,+ })))+ };+ if let Some(cached) = self.sibling_position(node, position.of_type) {+ return answer(cached);+ }-impl<A: AtomSpace> SelectorProgram<A> {- pub(super) 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);+ let Some(parent) = parent else {+ if position.of_type {+ type_of(node)?;}+ return Ok(Some(1));};- for node in &self.nodes {- visited += 1;- match *node {- SelectorOp::Feature(FeatureTest::TagName(tag)) => {- insert(tag.written);- insert(tag.folded);- insert(tag.fold_in_namespace);- }- SelectorOp::Feature(FeatureTest::Id(atom) | FeatureTest::Class(atom))- | SelectorOp::Part(atom)- | SelectorOp::ValueState { value: atom, .. } => insert(atom),- SelectorOp::Feature(FeatureTest::Attribute(attribute)) => {- insert(attribute.name);- insert(attribute.folded);- insert(attribute.fold_in_namespace);- insert(attribute.value_atom);- if let AttributeCase::InsensitiveForNamespace(namespace) = attribute.case {- insert(namespace);- }- }- SelectorOp::Feature(FeatureTest::Namespace(NamespaceTest::Named(namespace))) => insert(namespace),- _ => {}- }+ if self.sibling_geometry.sibling_sequence(node).is_none() {+ self.sibling_geometry.insert_sequence(children(parent));+ }+ let siblings = self.sibling_geometry.sibling_sequence(node).unwrap();+ if siblings.is_empty() {+ return Ok(None);}- visited- }- /// The names of the attributes the program tests, by any operator.- pub fn tested_attribute_names(&self) -> impl Iterator<Item = StyleAtomID> + '_ {- self.nodes- .iter()- .filter_map(|node| match node {- SelectorOp::Feature(FeatureTest::Attribute(test)) => Some(test),- _ => None,- })- .flat_map(|test| {- [Some(test.name), (test.folded != test.name).then_some(test.folded)]- .into_iter()- .flatten()- })- }+ if position.of_type {+ let mut type_ids = HashMap::default();+ let mut sibling_types = Vec::with_capacity(siblings.len());+ let mut type_positions: SmallVec<[SiblingPositions; 1]> = SmallVec::new();+ for &sibling in siblings {+ let sibling_type = type_of(sibling)?;+ let next_type_id = u32::try_from(type_positions.len()).expect("sibling type space exhausted");+ let type_id = *type_ids.entry(sibling_type).or_insert_with(|| {+ type_positions.push(SiblingPositions {+ from_start: 0,+ from_end: 0,+ });+ next_type_id+ });+ sibling_types.push(type_id);+ type_positions[type_id as usize].from_end += 1;+ }+ let siblings = self.sibling_geometry.sibling_sequence(node).unwrap();+ let positions = &mut self.type_positions;+ for (&sibling, type_id) in siblings.iter().zip(sibling_types) {+ let position = &mut type_positions[type_id as usize];+ position.from_start += 1;+ positions.insert(+ sibling.element_index().expect("only elements have sibling positions") as usize,+ *position,+ );+ position.from_end -= 1;+ }+ }- /// Attribute names whose tests cannot be answered from the value atom alone.- pub fn attribute_value_text_names(&self) -> impl Iterator<Item = StyleAtomID> + '_ {- self.nodes- .iter()- .filter_map(|node| {- let SelectorOp::Feature(FeatureTest::Attribute(test)) = node else {- return None;- };- (test.operator != AttributeOperator::Presence- && (test.operator != AttributeOperator::Exact || test.case != AttributeCase::Sensitive))- .then_some(test)- })- .flat_map(|test| {- [Some(test.name), (test.folded != test.name).then_some(test.folded)]- .into_iter()- .flatten()- })+ match self.sibling_position(node, position.of_type) {+ Some(cached) => answer(cached),+ None => Ok(None),+ }}- #[must_use]- pub fn node(&self, id: SelectorNodeID) -> SelectorOp {- self.nodes[id.0 as usize]+ pub(super) fn sibling_position(&self, node: StyleNodeID, of_type: bool) -> Option<SiblingPositions> {+ match of_type {+ true => self.type_positions.get(node.element_index()? as usize),+ false => self.sibling_geometry.sibling_positions(node),+ }}- /// The dispatch-bloom bits a node evaluated against the compound at `id` must carry. Zero —- /// including for a program built without dispatch metadata — means no cheap requirement.- #[must_use]- fn relation_target_bloom(&self, id: SelectorNodeID) -> u64 {- self.relation_target_blooms.get(id.0 as usize).copied().unwrap_or(0)+ pub(super) fn relative_walks(&self) -> u64 {+ self.relative_walks}- #[must_use]- pub fn operands(&self, first: u32, count: u32) -> &[SelectorNodeID] {- &self.operands[first as usize..(first + count) as usize]+ pub(super) fn relative_answer(&self, key: &RelativeAnswerKey) -> Option<bool> {+ self.relative_answers.get(key).copied()}- #[must_use]- pub fn entries(&self) -> &[SelectorEntry] {- &self.entries+ pub(super) fn insert_relative_answer(&mut self, key: RelativeAnswerKey, answer: bool) {+ self.relative_walks += 1;+ self.relative_answers.insert(key, answer);}- /// Whether an entry matches nothing because its subject holds the test nothing satisfies, which is what the- /// compiler emits for an unsatisfiable compound.- #[must_use]- pub fn entry_never_matches(&self, entry: &SelectorEntry) -> bool {- let is_never = |id: SelectorNodeID| matches!(self.node(id), SelectorOp::Not(inner) if self.node(inner) == SelectorOp::Feature(FeatureTest::AnyElement));- match self.node(entry.root) {- SelectorOp::And { first, count } => self.operands(first, count).iter().any(|&operand| is_never(operand)),- _ => is_never(entry.root),+ /// The table of the walks `key` says.+ pub(super) fn sibling_table(&mut self, key: SiblingAnswerKey) -> SiblingAnswerTable {+ let next = u32::try_from(self.sibling_answers.len()).expect("sibling answer tables exhausted");+ let table = *self.sibling_tables.entry(key).or_insert(next);+ if table == next {+ self.sibling_answers.push(Vec::new());}+ SiblingAnswerTable(table)}- #[must_use]- pub fn contains_relational_selector(&self) -> bool {- // Every relative query is pushed together with the one RelativeExists node evaluating it.- !self.relative_queries.is_empty()- }-- /// Whether any node in this subtree tests sibling position. A retained witness for a- /// query containing one can go stale from a sibling mutation that never touches the- /// witness itself, so such witnesses cannot prove an anchor unchanged.- #[must_use]- pub fn subtree_tests_position(&self, root: SelectorNodeID) -> bool {- match self.node(root) {- SelectorOp::NthPosition(_) => true,- SelectorOp::And { first, count } | SelectorOp::Or { first, count } => self- .operands(first, count)- .iter()- .any(|&operand| self.subtree_tests_position(operand)),- SelectorOp::Where(inner)- | SelectorOp::Not(inner)- | SelectorOp::Parent(inner)- | SelectorOp::Ancestor(inner)- | SelectorOp::PreviousSibling(inner)- | SelectorOp::PrecedingSibling(inner)- | SelectorOp::BackingElement { inner, .. } => self.subtree_tests_position(inner),- SelectorOp::RelativeExists(query) => self.subtree_tests_position(self.relative_query(query).compound),- _ => false,+ pub(super) fn sibling_answer(&self, table: SiblingAnswerTable, node: StyleNodeID) -> Option<bool> {+ let slot = node.element_slot();+ let page = *self.sibling_answers[table.0 as usize].get(slot / SIBLING_ANSWER_PAGE)?;+ if page == NO_SIBLING_PAGE {+ return None;+ }+ match self.sibling_answer_pages[page as usize][slot % SIBLING_ANSWER_PAGE] {+ 1 => Some(false),+ 2 => Some(true),+ _ => None,}}- pub fn relative_query(&self, id: RelativeQueryID) -> RelativeQuery {- self.relative_queries[id.0 as usize]- }-- /// The query named by `id`, when a witness of it may be retained and later re-verified.- ///- /// Retention needs the query to be simple - one axis, one compound, a positive driving- /// feature - and the compound to read only facts the witness itself publishes, so that a- /// routing-time check can re-evaluate it with no scope, host, or anchor context. The bounds- /// check stands in for identity churn: a retained key can outlive the program version that- /// wrote it, and a key nothing answers for is not a proof of anything.- #[must_use]- pub(super) fn retainable_relative_query(&self, id: RelativeQueryID) -> Option<RelativeQuery> {- let query = self.relative_queries.get(id.0 as usize).copied()?;- (query.is_simple() && self.node_is_prefix_local(query.compound)).then_some(query)- }-- #[must_use]- pub fn literal(&self, offset: u32, length: u32) -> &[u16] {- &self.text[offset as usize..(offset + length) as usize]- }-- /// The extended language ranges one `:lang()` names.- pub fn language_ranges(&self, first: u32, count: u32) -> impl Iterator<Item = &[u16]> {- self.language_ranges[first as usize..(first + count) as usize]- .iter()- .map(|&(offset, length)| self.literal(offset, length))- }-- #[must_use]- pub fn node_count(&self) -> usize {- self.nodes.len()+ pub(super) fn insert_sibling_answer(&mut self, table: SiblingAnswerTable, node: StyleNodeID, answer: bool) {+ let slot = node.element_slot();+ let pages = &mut self.sibling_answers[table.0 as usize];+ if pages.len() <= slot / SIBLING_ANSWER_PAGE {+ pages.resize(slot / SIBLING_ANSWER_PAGE + 1, NO_SIBLING_PAGE);+ }+ let page = &mut pages[slot / SIBLING_ANSWER_PAGE];+ if *page == NO_SIBLING_PAGE {+ *page = u32::try_from(self.sibling_answer_pages.len()).expect("sibling answer pages exhausted");+ self.sibling_answer_pages.push([0; SIBLING_ANSWER_PAGE]);+ }+ self.sibling_answer_pages[*page as usize][slot % SIBLING_ANSWER_PAGE] = 1 + u8::from(answer);}}-/// Builds one selector program. C++ parses the selector text and drives this; the IR and its-/// ordering are decided here, while specificity comes from the immutable compiled selector.-#[derive(Default)]-pub struct SelectorProgramBuilder<A: AtomSpace = EngineAtoms> {- program: SelectorProgram<A>,-}--impl SelectorProgramBuilder {- #[must_use]- #[cfg(test)]- pub fn new() -> Self {- Self::default()+/// What matching the entries of the rule index asks of an evaluator, against whichever elements it+/// is matched against.+impl<S> SelectorEvaluator<S>+where+ S: SelectorSubject<Node = StyleNodeID, Incomplete = Incomplete>,+{+ /// Evaluate the rules attached to the shadow tree of `shadow_root` from here on, or the+ /// document's for none.+ pub(super) fn set_scope_shadow_root(&mut self, shadow_root: Option<StyleNodeID>) {+ self.bindings.scope_shadow_root = shadow_root;}}-impl<A: AtomSpace> SelectorProgramBuilder<A> {- /// The program as built so far, for a compiler that has to inspect what it just emitted.- #[must_use]- pub fn program(&self) -> &SelectorProgram<A> {- &self.program- }-- pub fn push(&mut self, op: SelectorOp) -> SelectorNodeID {- self.program.nodes.push(op);- SelectorNodeID(u32::try_from(self.program.nodes.len() - 1).expect("selector node space exhausted"))+/// `index` is a 1-based position; the test is whether it equals `step * n + offset` for some+/// non-negative integer `n`.+pub(super) fn matches_an_plus_b(step: i32, offset: i32, index: i64) -> bool {+ let step = i64::from(step);+ let offset = i64::from(offset);+ if step == 0 {+ return index == offset;}+ let difference = index - offset;+ difference % step == 0 && difference / step >= 0+}- pub fn push_feature(&mut self, test: FeatureTest) -> SelectorNodeID {- self.push(SelectorOp::Feature(test))+fn fold(unit: u16) -> u16 {+ if (u16::from(b'A')..=u16::from(b'Z')).contains(&unit) {+ return unit + u16::from(b'a' - b'A');}+ unit+}- /// Add a UTF-16 literal to the program and return its range. The representation is the same one- /// the C++ side holds, so nothing is converted crossing the boundary.- pub fn push_literal(&mut self, text: &[u16]) -> (u32, u32) {- let offset = u32::try_from(self.program.text.len()).expect("selector literal space exhausted");- self.program.text.extend_from_slice(text);- (- offset,- u32::try_from(text.len()).expect("selector literal space exhausted"),- )- }-- /// Add the extended language ranges of one `:lang()` and return their range.- pub fn push_language_ranges(&mut self, ranges: impl IntoIterator<Item = impl AsRef<[u16]>>) -> (u32, u32) {- let first = u32::try_from(self.program.language_ranges.len()).expect("language range space exhausted");- for range in ranges {- let literal = self.push_literal(range.as_ref());- self.program.language_ranges.push(literal);- }- (- first,- u32::try_from(self.program.language_ranges.len() - first as usize).expect("language range space exhausted"),- )- }-- /// Build a compound. Operands are sorted by static cost so evaluation rejects on the cheapest- /// discriminating test it has.- pub fn push_compound(&mut self, operands: &[SelectorNodeID]) -> SelectorNodeID {- assert!(!operands.is_empty(), "a compound needs at least one operand");- if operands.len() == 1 {- return operands[0];- }- // Conjunction is associative, and one compound is one node: routing reads a compound's- // operands to find what the selector says about the subject's parent, and an operand that- // is itself a conjunction would hide the rest of the compound from the walk that reads it.- let first = self.program.operands.len();- self.program.operands.reserve(operands.len());- for &operand in operands {- match self.program.node(operand) {- SelectorOp::And { first, count } => {- let start = first as usize;- self.program.operands.extend_from_within(start..start + count as usize);- }- _ => self.program.operands.push(operand),- }- }- let nodes = &self.program.nodes;- self.program.operands[first..].sort_by_key(|operand| nodes[operand.0 as usize].cost_rank());- self.push(SelectorOp::And {- first: u32::try_from(first).expect("selector operand space exhausted"),- count: u32::try_from(self.program.operands.len() - first).expect("selector operand space exhausted"),- })- }-- /// Add a relative query and return the operator that evaluates it.- pub fn push_relative_exists(&mut self, query: RelativeQuery) -> SelectorNodeID {- self.program.relative_queries.push(query);- let id = RelativeQueryID(- u32::try_from(self.program.relative_queries.len() - 1).expect("relative query space exhausted"),- );- self.push(SelectorOp::RelativeExists(id))- }-- /// Build a disjunction: a selector list argument, or `:is()`.- pub fn push_any_of(&mut self, operands: &[SelectorNodeID]) -> SelectorNodeID {- assert!(!operands.is_empty(), "a disjunction needs at least one operand");- // A disjunction of one is that one. It is worth collapsing rather than tidy, because- // absolutizing a nested rule wraps the parent selector in `:is()`, so every `&` in every- // stylesheet arrives here with a single branch - and a disjunction has no dispatch key, so- // leaving it wrapped puts every nested rule in front of every element in the document.- if let [only] = operands {- return *only;- }- let first = u32::try_from(self.program.operands.len()).expect("selector operand space exhausted");- self.program.operands.extend_from_slice(operands);- self.push(SelectorOp::Or {- first,- count: u32::try_from(operands.len()).expect("selector operand space exhausted"),- })- }-- /// Add an ancestor step: the subject has an ancestor satisfying `inner`.- #[cfg(test)]- pub fn push_ancestor(&mut self, inner: SelectorNodeID) -> SelectorNodeID {- self.push(SelectorOp::Ancestor(inner))- }-- /// Add a test nothing satisfies, which is what an unsatisfiable compound compiles to.- ///- /// It has to be a test rather than nothing at all: a compound with no operands constrains- /// nothing, and a compound that constrains nothing matches every element in the document.- pub fn push_never(&mut self) -> SelectorNodeID {- let anything = self.push_feature(FeatureTest::AnyElement);- self.push(SelectorOp::Not(anything))- }-- /// Name one element by identity, which is how an `@scope` with no `<scope-start>` says where it- /// roots.- pub fn push_is_node(&mut self, node: StyleNodeID) -> SelectorNodeID {- self.push(SelectorOp::IsNode(node))- }-- /// Name what the entry's `@scope` treats as a scoping root.- pub fn set_entry_scope_root(&mut self, entry: usize, scope_root: SelectorNodeID) {- self.program.entries[entry].scope_root = Some(scope_root);- }-- /// Replace an entry's root, as a scope does when it wraps everything the rule wrote.- pub fn set_entry_root(&mut self, entry: usize, root: SelectorNodeID) {- self.program.entries[entry].root = root;- }-- /// The node an entry's evaluation starts from.- #[must_use]- pub fn entry_root(&self, entry: usize) -> SelectorNodeID {- self.program.entries[entry].root- }-- /// Add one top-level complex selector to the rule's selector list.- pub fn push_entry(&mut self, root: SelectorNodeID) -> usize {- self.push_entry_for_pseudo(root, None)- }-- /// Add a top-level complex selector that targets a pseudo-element. The program still matches- /// the originating element; the target projects the result onto the pseudo style node.- pub fn push_entry_for_pseudo(- &mut self,- root: SelectorNodeID,- pseudo_element: Option<PseudoElementTarget>,- ) -> usize {- self.program.entries.push(SelectorEntry {- root,- specificity: Specificity::default(),- scope_root: None,- pseudo_element,- properties: SelectorEntryProperties::default(),- });- self.program.entries.len() - 1- }-- /// Attach the specificity computed from the immutable compiled selector. IR rewrites for- /// scopes and routing must not derive it again.- pub fn set_entry_specificity(&mut self, entry: usize, specificity: Specificity) {- self.program.entries[entry].specificity = specificity;- }-- #[must_use]- pub fn finish(mut self) -> SelectorProgram<A> {- self.program.cache_dispatch_metadata();- for index in 0..self.program.entries.len() {- let entry = &self.program.entries[index];- let unified_chain = self.program.dispatch_metadata(index).prefix_chain();- let properties = SelectorEntryProperties {- monotone_under_arrivals: self.program.entry_is_monotone_under_arrivals(entry.root),- can_use_before_sibling_relations: self.program.entry_can_use_before_sibling_relations(entry.root),- observes_sibling_relation: self.program.entry_observes_sibling_relation(entry.root),- has_prefix_chain: unified_chain.is_some(),- prefix_chain_has_only_local_facts: unified_chain.is_some_and(|chain| {- // A canonical positional step counts as local here: its truth rides the- // positional bits of every transition and completion key, so the retained- // walk answers it exactly like an interned fact.- chain- .iter()- .all(|step| self.program.prefix_local_has_canonical_form(step.local))- }),- };- self.program.entries[index].properties = properties;- }- self.program.can_leave_scope = self- .program- .entries- .iter()- .any(|entry| self.program.leaves_its_scope(entry.root));- self.program.subject_can_leave_scope = self- .program- .entries- .iter()- .any(|entry| self.program.subject_leaves_its_scope(entry.root));- // Finished programs never append nodes or entries. Release their construction headroom.- self.program.nodes.shrink_to_fit();- self.program.operands.shrink_to_fit();- self.program.text.shrink_to_fit();- self.program.entries.shrink_to_fit();- self.program.relative_queries.shrink_to_fit();- self.program.language_ranges.shrink_to_fit();- self.program- }-}--impl<A: AtomSpace> SelectorProgram<A> {- fn cache_dispatch_metadata(&mut self) {- // Only ancestor walks consult these blooms; other programs need no per-node array.- let target_count = if self.nodes.iter().any(|node| matches!(node, SelectorOp::Ancestor(_))) {- self.nodes.len()- } else {- 0- };- let mut relation_target_blooms = vec![0_u64; target_count];- for (id, target_bloom) in relation_target_blooms.iter_mut().enumerate() {- let node = SelectorNodeID(u32::try_from(id).unwrap_or(u32::MAX));- // Only a feature op standing directly in the compound is a test of the node itself.- // Anything deeper (a negation, a disjunction branch, a relative query's witness) may- // hold elsewhere, or not at all. And only the always-resident key kinds contribute —- // so a bit facts never set can't reject a node that matches.- let single = [node];- let operands = match self.node(node) {- SelectorOp::And { first, count } => self.operands(first, count),- _ => &single,- };- let mut bloom = 0_u64;- for &operand in operands {- if let SelectorOp::Feature(test) = self.node(operand) {- let key = dispatch_key_for_feature(test);- if matches!(- key,- DispatchKey::Id(_)- | DispatchKey::Class(_)- | DispatchKey::AttributeName(_)- | DispatchKey::TagName(_)- ) {- bloom |= dispatch_bloom_bit(key);- }- }- }- *target_bloom = bloom;- }- self.relation_target_blooms = relation_target_blooms.into_boxed_slice();- self.dispatch_metadata.0 = (0..self.entries.len())- .map(|entry| {- let selector_entry = &self.entries[entry];- let key = self.dispatch_key(selector_entry);- let subject_dispatch_keys = self.compute_subject_dispatch_keys(entry);- let subject_required_keys = self.compute_subject_required_keys(entry, &subject_dispatch_keys);- SelectorDispatchMetadata {- key,- required_attribute_value: match key {- DispatchKey::AttributeName(name) => self.required_attribute_value(selector_entry, name),- _ => StyleAtomID::NONE,- },- required_parent: self.subject_parent_dispatch_key(entry),- required_ancestor: self.subject_ancestor_dispatch_key(entry),- required_subject_bloom: subject_required_keys- .iter()- .copied()- .fold(0_u64, |bloom, key| bloom | dispatch_bloom_bit(key)),- subject_dispatch_keys: subject_dispatch_keys.into_boxed_slice(),- subject_required_keys: subject_required_keys.into_boxed_slice(),- prefix_chain: self.unified_chain(selector_entry).map(Vec::into_boxed_slice),- }- })- .collect();- }-- #[must_use]- pub(super) fn dispatch_metadata(&self, entry: usize) -> &SelectorDispatchMetadata {- &self.dispatch_metadata.0[entry]- }-- /// Decompose a selector whose tree relations are its linear chain over all four axes:- /// descendant, child, adjacent, and general sibling. This is the form the prefix automaton- /// registers.- ///- /// Logical operators are allowed inside one local compound as long as they stay local. A- /// combinator hidden inside `:is()` or `:not()` is not a linear chain and remains on the exact- /// match evaluator.- #[must_use]- pub(super) fn unified_chain(&self, entry: &SelectorEntry) -> Option<Vec<SelectorPrefixStep>> {- let mut chain = Vec::new();- self.append_chain(entry.root, &mut chain)?;- Some(chain)- }-- fn append_chain(&self, root: SelectorNodeID, chain: &mut Vec<SelectorPrefixStep>) -> Option<()> {- let mut relation = None;- let mut needs_canonical_form = false;- let operands = match self.node(root) {- SelectorOp::And { first, count } => self.operands(first, count),- _ => std::slice::from_ref(&root),- };- for &operand in operands {- match self.node(operand) {- SelectorOp::Parent(inner) => {- if relation.replace((operand, SelectorPrefixAxis::Child, inner)).is_some() {- return None;- }- }- SelectorOp::Ancestor(inner) => {- if relation- .replace((operand, SelectorPrefixAxis::Descendant, inner))- .is_some()- {- return None;- }- }- SelectorOp::PreviousSibling(inner) => {- if relation- .replace((operand, SelectorPrefixAxis::NextSibling, inner))- .is_some()- {- return None;- }- }- SelectorOp::PrecedingSibling(inner) => {- if relation- .replace((operand, SelectorPrefixAxis::FollowingSibling, inner))- .is_some()- {- return None;- }- }- _ if self.node_is_prefix_local(operand) => {}- // Anything else is admissible only through the canonical form below: structural- // tests become truth bits, and everything the canonical collector rejects keeps- // the compound on the exact match evaluator. The fallback program predicate- // must never carry a structural test, because it would intern one answer per- // fact cohort for truth that is per index or per child list.- _ => {- needs_canonical_form = true;- }- }- }-- let local = SelectorPrefixLocal {- root,- relation: relation.map(|(relation, _, _)| relation),- };- if needs_canonical_form && !self.prefix_local_has_canonical_form(local) {- return None;- }-- let axis = match relation {- Some((_, axis, inner)) => {- self.append_chain(inner, chain)?;- axis- }- None => SelectorPrefixAxis::Root,- };- chain.push(SelectorPrefixStep { local, axis });- Some(())- }-- fn node_is_prefix_local(&self, id: SelectorNodeID) -> bool {- match self.node(id) {- SelectorOp::And { first, count } | SelectorOp::Or { first, count } => self- .operands(first, count)- .iter()- .all(|&operand| self.node_is_prefix_local(operand)),- SelectorOp::Where(inner) | SelectorOp::Not(inner) => self.node_is_prefix_local(inner),- SelectorOp::Feature(_)- | SelectorOp::State(_)- | SelectorOp::Root- | SelectorOp::ValueState { .. }- | SelectorOp::Language { .. }- | SelectorOp::Heading(_) => true,- SelectorOp::Parent(_)- | SelectorOp::Ancestor(_)- | SelectorOp::PreviousSibling(_)- | SelectorOp::PrecedingSibling(_)- | SelectorOp::NthPosition(_)- | SelectorOp::RelativeExists(_)- | SelectorOp::Host(_)- | SelectorOp::Slotted(_)- | SelectorOp::Part(_)- | SelectorOp::ExposedToHost { .. }- | SelectorOp::BackingElement { .. }- | SelectorOp::Empty- | SelectorOp::Scope- | SelectorOp::IsNode(_)- | SelectorOp::AssignedSlot(_)- | SelectorOp::ScopeRootInstance- | SelectorOp::RelativeAnchorInstance- | SelectorOp::InScope { .. } => false,- }- }-- #[must_use]- pub(super) fn prefix_dispatch_key(&self, local: SelectorPrefixLocal) -> DispatchKey {- match self.node(local.root) {- SelectorOp::And { first, count } => self- .operands(first, count)- .iter()- .copied()- .filter(|&operand| Some(operand) != local.relation)- .map(|operand| self.dispatch_key_of(operand))- .min_by_key(|key| dispatch_selectivity(*key))- .unwrap_or(DispatchKey::Universal),- _ => self.dispatch_key_of(local.root),- }- }-- pub(super) fn prefix_local_predicate(&self, local: SelectorPrefixLocal) -> SelectorPrefixPredicate {- fn conjunction(mut operands: Vec<SelectorPrefixPredicate>) -> SelectorPrefixPredicate {- if operands.len() == 1 {- operands.pop().unwrap()- } else {- SelectorPrefixPredicate::And(operands.into_boxed_slice())- }- }- fn predicate<A: AtomSpace>(program: &SelectorProgram<A>, node: SelectorNodeID) -> SelectorPrefixPredicate {- match program.node(node) {- SelectorOp::And { first, count } => conjunction(- program- .operands(first, count)- .iter()- .map(|&node| predicate(program, node))- .collect(),- ),- SelectorOp::Or { first, count } => SelectorPrefixPredicate::Or(- program- .operands(first, count)- .iter()- .map(|&node| predicate(program, node))- .collect(),- ),- SelectorOp::Where(inner) => predicate(program, inner),- SelectorOp::Not(inner) => SelectorPrefixPredicate::Not(Box::new(predicate(program, inner))),- SelectorOp::Language { first, count } => {- SelectorPrefixPredicate::Language(program.language_ranges(first, count).map(Box::from).collect())- }- SelectorOp::Feature(FeatureTest::Attribute(mut test)) => {- let text = match test.operator {- AttributeOperator::Presence => {- test.value_atom = StyleAtomID::NONE;- test.case = AttributeCase::Sensitive;- &[][..]- }- AttributeOperator::Exact- if test.case == AttributeCase::Sensitive && !test.value_atom.is_none() =>- {- &[]- }- _ => program.literal(test.value_offset, test.value_length),- };- test.value_offset = 0;- test.value_length = 0;- SelectorPrefixPredicate::Attribute(test, text.into())- }- leaf @ (SelectorOp::Feature(_)- | SelectorOp::State(_)- | SelectorOp::Root- | SelectorOp::ValueState { .. }- | SelectorOp::Heading(_)) => SelectorPrefixPredicate::Leaf(leaf),- _ => unreachable!("only local predicates can share a prefix compound"),- }- }- match self.node(local.root) {- SelectorOp::And { first, count } => conjunction(- self.operands(first, count)- .iter()- .filter(|&&node| Some(node) != local.relation)- .map(|&node| predicate(self, node))- .collect(),- ),- _ => predicate(self, local.root),- }- }-- pub(super) fn visit_prefix_local_features(&self, local: SelectorPrefixLocal, visit: &mut impl FnMut(FeatureTest)) {- let mut pending = vec![local.root];- while let Some(node) = pending.pop() {- if Some(node) == local.relation {- continue;- }- match self.node(node) {- SelectorOp::Feature(feature) => visit(feature),- SelectorOp::And { first, count } | SelectorOp::Or { first, count } => {- pending.extend_from_slice(self.operands(first, count));- }- SelectorOp::Where(inner) | SelectorOp::Not(inner) => pending.push(inner),- _ => {}- }- }- }-- /// The canonical feature list of one prefix step's local compound, plus at most one- /// positional test. Positional truth is a pure function of the visit index and the- /// sequence length, both of which the rightward walk knows, so a step carrying one stays- /// automaton-expressible without entering state identity.- ///- /// Program-relative text offsets are irrelevant to presence tests and atom-exact comparisons,- /// so clearing them lets equivalent compounds in different programs share one prefix step.- pub(super) fn canonical_prefix_features_and_position(- &self,- local: SelectorPrefixLocal,- ) -> Option<(Vec<FeatureTest>, Vec<PrefixStructuralTest>)> {- let mut features = Vec::new();- let mut structural_tests = Vec::new();- let operands = match self.node(local.root) {- SelectorOp::And { first, count } => self.operands(first, count),- _ => std::slice::from_ref(&local.root),- };- for &operand in operands {- if Some(operand) == local.relation {- continue;- }- self.visit_canonical_prefix_operand(operand, &mut |feature| features.push(feature), &mut |test| {- structural_tests.push(test);- })?;- }- features.sort_unstable();- features.dedup();- Some((features, structural_tests))- }-- fn prefix_local_has_canonical_form(&self, local: SelectorPrefixLocal) -> bool {- let operands = match self.node(local.root) {- SelectorOp::And { first, count } => self.operands(first, count),- _ => std::slice::from_ref(&local.root),- };- for &operand in operands {- if Some(operand) == local.relation {- continue;- }- if self- .visit_canonical_prefix_operand(operand, &mut |_| {}, &mut |_| {})- .is_none()- {- return false;- }- }- true- }-- /// Fold one conjunctive prefix operand into the canonical form: feature tests answered- /// from interned facts and structural tests answered as truth bits. `:where()` is- /// match-transparent, and nested conjunctions arise from pseudo-classes that compile to- /// several tests, `:only-of-type` being a first-of-type and a last-of-type in one. An- /// an+b test with an of-selector evaluates an arbitrary program against every sibling,- /// so it is not canonical, and neither is anything disjunctive or negated.- fn visit_canonical_prefix_operand(- &self,- operand: SelectorNodeID,- visit_feature: &mut impl FnMut(FeatureTest),- visit_structural_test: &mut impl FnMut(PrefixStructuralTest),- ) -> Option<()> {- let feature = match self.node(operand) {- SelectorOp::And { first, count } => {- for &inner in self.operands(first, count) {- self.visit_canonical_prefix_operand(inner, visit_feature, visit_structural_test)?;- }- return Some(());- }- SelectorOp::Where(inner) => {- return self.visit_canonical_prefix_operand(inner, visit_feature, visit_structural_test);- }- // Every an+b test without an of-selector is canonical: its truth is one bit per node- // that the convergence walk re-compares for every child of a touched sequence. A- // step-bearing test flips truth across a whole moved side at once, so it costs the- // walk more transitions than a step-free one, but the sequence router's alternative- // - routing each moved child through every entry its origin compound admits, then- // narrowing and exactly evaluating each (child, entry) pair - was measured at several- // times that cost on nth-heavy documents.- SelectorOp::NthPosition(nth) if nth.of_selector.is_none() => {- visit_structural_test(PrefixStructuralTest::Nth(nth));- return Some(());- }- SelectorOp::Empty => {- visit_structural_test(PrefixStructuralTest::Empty);- return Some(());- }- SelectorOp::Feature(feature) => feature,- _ => return None,- };- let mut feature = feature;- if let FeatureTest::Attribute(ref mut attribute) = feature {- match attribute.operator {- AttributeOperator::Presence => {- attribute.value_atom = StyleAtomID::NONE;- attribute.value_offset = 0;- attribute.value_length = 0;- attribute.case = AttributeCase::Sensitive;- }- AttributeOperator::Exact- if attribute.case == AttributeCase::Sensitive && !attribute.value_atom.is_none() =>- {- attribute.value_offset = 0;- attribute.value_length = 0;- }- _ => return None,- }- }- visit_feature(feature);- Some(())- }-- /// The rightmost distinguishing feature of one entry: the most selective local fact its subject- /// compound requires.- ///- /// Only the subject's own features count. A combinator operand constrains an ancestor or a- /// sibling, not the candidate, so bucketing by it would send candidates to rules that cannot- /// match them and - worse - would miss candidates that can.- #[must_use]- pub fn dispatch_key(&self, entry: &SelectorEntry) -> DispatchKey {- self.dispatch_key_of(entry.root)- }-- /// The exact attribute value this entry's subject requires, when it requires one by identity.- ///- /// An attribute bucket holds every rule naming that attribute, and a page where one attribute- /// is on every element hands the evaluator all of them. A rule that tests the value exactly and- /// case-sensitively against an interned literal can be rejected by comparing two atoms, which- /// is what this is for: it is only ever read for an entry whose dispatch key is that attribute.- #[must_use]- pub fn required_attribute_value(&self, entry: &SelectorEntry, name: StyleAtomID) -> StyleAtomID {- self.required_attribute_value_of(entry.root, name)- }-- fn required_attribute_value_of(&self, id: SelectorNodeID, name: StyleAtomID) -> StyleAtomID {- match self.node(id) {- SelectorOp::Feature(FeatureTest::Attribute(test))- if test.name == name- && test.operator == AttributeOperator::Exact- && test.case == AttributeCase::Sensitive =>- {- test.value_atom- }- // Every operand of a conjunction has to hold, so a value one of them requires is- // required. A disjunction or a negation requires nothing.- SelectorOp::And { first, count } => self- .operands(first, count)- .iter()- .map(|&operand| self.required_attribute_value_of(operand, name))- .find(|value| !value.is_none())- .unwrap_or(StyleAtomID::NONE),- SelectorOp::Where(inner) => self.required_attribute_value_of(inner, name),- _ => StyleAtomID::NONE,- }- }-- /// How far into a sibling sequence this entry's subjects can be.- ///- /// A positional test with no step names a bounded prefix or suffix of the sequence, which is- /// the only thing left to narrow a child region by when the compound has no feature.- #[must_use]- pub fn subject_position(&self, entry: usize) -> SubjectPosition {- self.position_of(self.entries()[entry].root)- }-- fn position_of(&self, id: SelectorNodeID) -> SubjectPosition {- match self.node(id) {- SelectorOp::NthPosition(position) if position.step == 0 && position.offset >= 0 => SubjectPosition {- from_end: position.from_end,- bound: position.offset as u32,- },- SelectorOp::Where(inner) => self.position_of(inner),- // Every operand of a conjunction is necessary, so the tightest bound any of them names- // bounds the whole. Descending rather than reading one level is what keeps the bound- // from depending on how deeply the compound happens to be nested.- SelectorOp::And { first, count } => self- .operands(first, count)- .iter()- .map(|&operand| self.position_of(operand))- .min_by_key(|position| position.bound)- .unwrap_or(SubjectPosition::UNBOUNDED),- _ => SubjectPosition::UNBOUNDED,- }- }-- /// What the subject's parent must be, when the entry says so with a child combinator.- ///- /// A positional selector often has nothing on its subject to enumerate by - the user-agent- /// sheet is full of `mfrac > :nth-child(2)` - but it does say what the parent is, and a whole- /// sibling sequence shares one parent. So one lookup rejects the sequence outright.- #[must_use]- pub fn subject_parent_dispatch(&self, entry: usize) -> Vec<DispatchKey> {- let mut keys = Vec::new();- self.dispatch_analysis(- self.entries()[entry].root,- DispatchRelation::Parent,- DispatchQuery::Alternatives,- &mut keys,- );- keys- }-- /// The one key the subject's parent must carry, when a child combinator names exactly one.- ///- /// A set of more than one key is a disjunction - `:is(ol, ul) > .item` names three - and the- /// parent has to carry some member of it rather than any particular one, so no single key- /// rejects soundly and the entry keeps no filter at all.- #[must_use]- pub fn subject_parent_dispatch_key(&self, entry: usize) -> Option<DispatchKey> {- match self.subject_parent_dispatch(entry).as_slice() {- [key] => Some(*key),- _ => None,- }- }-- /// What some ancestor of the subject must be, when the entry says so with a descendant- /// combinator.- ///- /// Weaker than the parent constraint and used only when there is none: it bounds the subject to- /// a subtree rather than to a child list. `.preview :not(ol)` has nothing on its subject to- /// enumerate by, but every element it can match is under a `.preview`.- #[must_use]- pub fn subject_ancestor_dispatch(&self, entry: usize) -> Vec<DispatchKey> {- let mut keys = Vec::new();- self.dispatch_analysis(- self.entries()[entry].root,- DispatchRelation::Ancestor,- DispatchQuery::Alternatives,- &mut keys,- );- keys- }-- /// The one key some ancestor of the subject must carry. Disjunctions keep no filter, for the- /// reason `subject_parent_dispatch_key` gives.- #[must_use]- pub fn subject_ancestor_dispatch_key(&self, entry: usize) -> Option<DispatchKey> {- match self.subject_ancestor_dispatch(entry).as_slice() {- [key] => Some(*key),- _ => None,- }- }-- /// The witnesses of a relative query the subject has to satisfy, and the axis they stand on.- ///- /// A subject that is nothing but `:has(.error)` has no feature to enumerate by, but it can only- /// match an anchor of that query - and the witness compound does have a posting. The axis is what- /// turns a set of witnesses back into the set of anchors that can see them.- ///- /// Only a query the subject must satisfy bounds it. A negation says the opposite (an element with- /// no `.error` under it is not bounded by the `.error` elements) and a disjunction is satisfied by- /// branches this one knows nothing about, so neither is descended into.- #[must_use]- pub fn subject_relative_anchor(&self, entry: usize) -> Option<(RelativeAxis, Vec<DispatchKey>)> {- let root = self.entries()[entry].root;- let operands = match self.node(root) {- SelectorOp::And { first, count } => self.operands(first, count),- _ => std::slice::from_ref(&root),- };- for &operand in operands {- let id = match self.node(operand) {- SelectorOp::RelativeExists(id) => id,- SelectorOp::Where(inner) => match self.node(inner) {- SelectorOp::RelativeExists(id) => id,- _ => continue,- },- _ => continue,- };- let query = self.relative_query(id);- let mut keys = Vec::new();- if !self.dispatch_keys_of(query.compound, &mut keys) {- continue;- }- return Some((query.axis, keys));- }- None- }-- /// Whether this entry's subject can only ever be the document's root element.- ///- /// `:root` has no feature to enumerate by, so it dispatches universally and a rule carrying it- /// would otherwise be answered with the whole document - when it names exactly one element.- #[must_use]- pub fn subject_is_only_the_root(&self, entry: usize) -> bool {- self.subject_is_the_document_root(self.entries()[entry].root)- }-- fn subject_is_the_document_root(&self, id: SelectorNodeID) -> bool {- match self.node(id) {- SelectorOp::Root => true,- SelectorOp::Where(inner) => self.subject_is_the_document_root(inner),- SelectorOp::And { first, count } => self- .operands(first, count)- .iter()- .any(|&operand| self.subject_is_the_document_root(operand)),- _ => false,- }- }-- /// The same, as the set of keys the subject can be reached by. Empty means it has none.- #[must_use]- pub fn subject_dispatch_keys(&self, entry: usize) -> &[DispatchKey] {- &self.dispatch_metadata.0[entry].subject_dispatch_keys- }-- fn compute_subject_dispatch_keys(&self, entry: usize) -> Vec<DispatchKey> {- let mut keys = Vec::new();- if !self.dispatch_keys_of(self.entries()[entry].root, &mut keys) {- keys.clear();- }- keys- }-- /// The independently necessary keys a compound requires beyond its candidate dispatch.- ///- /// Dispatch keys are a disjunction used to find candidates: either key of `:is(.a, .b)` admits- /// one. A compound is also a conjunction, though, and every directly conjoined feature is a- /// separate necessary condition. Retaining the remaining conditions lets transpose routing- /// reject a `div` candidate for `span.target` after finding it through `.target`.- ///- /// Operators that cannot express one independently necessary key contribute nothing. That is- /// the conservative direction: the candidate survives and the exact matcher settles it.- #[must_use]- pub fn subject_required_keys(&self, entry: usize) -> &[DispatchKey] {- &self.dispatch_metadata.0[entry].subject_required_keys- }-- fn compute_subject_required_keys(&self, entry: usize, dispatch: &[DispatchKey]) -> Vec<DispatchKey> {- let mut keys = Vec::new();- self.required_dispatch_keys_of(self.entries()[entry].root, &mut keys);- if let [already_required] = dispatch {- keys.retain(|key| key != already_required);- }- keys.sort_unstable();- keys.dedup();- keys.sort_unstable_by_key(|&key| dispatch_selectivity(key));- keys.truncate(MAX_REQUIRED_DISPATCH_KEYS);- keys- }-- fn dispatch_analysis(- &self,- id: SelectorNodeID,- relation: DispatchRelation,- query: DispatchQuery,- out: &mut Vec<DispatchKey>,- ) -> bool {- self.dispatch_analysis_excluding(id, relation, query, out, None)- }-- fn dispatch_analysis_excluding(- &self,- id: SelectorNodeID,- relation: DispatchRelation,- query: DispatchQuery,- out: &mut Vec<DispatchKey>,- excluded: Option<DispatchKey>,- ) -> bool {- if relation != DispatchRelation::Subject {- let operands = match self.node(id) {- SelectorOp::And { first, count } => self.operands(first, count),- _ => std::slice::from_ref(&id),- };- for &operand in operands {- match (relation, self.node(operand)) {- (DispatchRelation::Parent, SelectorOp::Parent(inner)) => {- if self.mentions_the_host(inner) {- if query == DispatchQuery::Required {- continue;- }- return false;- }- return self.dispatch_analysis_excluding(- inner,- DispatchRelation::Subject,- query,- out,- excluded,- );- }- (- DispatchRelation::Parent,- SelectorOp::PreviousSibling(inner) | SelectorOp::PrecedingSibling(inner),- ) => {- let start = out.len();- self.dispatch_analysis_excluding(inner, relation, query, out, excluded);- if query != DispatchQuery::Required && out.len() != start {- return true;- }- }- (DispatchRelation::Ancestor, SelectorOp::Parent(inner) | SelectorOp::Ancestor(inner))- if query == DispatchQuery::Required =>- {- if self.mentions_the_host(inner) {- continue;- }- self.dispatch_analysis_excluding(inner, DispatchRelation::Subject, query, out, excluded);- self.dispatch_analysis_excluding(inner, relation, query, out, excluded);- }- (DispatchRelation::Ancestor, SelectorOp::Ancestor(inner)) => {- if self.mentions_the_host(inner) {- return false;- }- return self.dispatch_analysis_excluding(- inner,- DispatchRelation::Subject,- query,- out,- excluded,- );- }- (- DispatchRelation::Ancestor,- SelectorOp::Parent(inner)- | SelectorOp::PreviousSibling(inner)- | SelectorOp::PrecedingSibling(inner),- ) => {- let start = out.len();- self.dispatch_analysis_excluding(inner, relation, query, out, excluded);- if out.len() != start {- return true;- }- }- _ => {}- }- }- return query == DispatchQuery::Required;- }-- match self.node(id) {- SelectorOp::Feature(test) => {- let key = Self::dispatch_key_for_feature(test);- if excluded == Some(key) {- return query == DispatchQuery::Required;- }- match query {- DispatchQuery::Alternatives | DispatchQuery::Required if key == DispatchKey::Universal => {- return query == DispatchQuery::Required;- }- DispatchQuery::Alternatives | DispatchQuery::Required => out.push(key),- }- true- }- SelectorOp::And { first, count } => match query {- DispatchQuery::Required => {- for &operand in self.operands(first, count) {- self.dispatch_analysis_excluding(operand, relation, query, out, excluded);- }- true- }- DispatchQuery::Alternatives => {- let mut best: Option<Vec<DispatchKey>> = None;- let mut candidate = Vec::new();- for &operand in self.operands(first, count) {- candidate.clear();- if !self.dispatch_analysis_excluding(operand, relation, query, &mut candidate, excluded) {- continue;- }- if best- .as_ref()- .is_none_or(|current| dispatch_set_cost(&candidate) < dispatch_set_cost(current))- {- match &mut best {- Some(best) => std::mem::swap(best, &mut candidate),- None => best = Some(std::mem::take(&mut candidate)),- }- }- }- let Some(keys) = best else {- return false;- };- out.extend_from_slice(&keys);- true- }- },- SelectorOp::Or { first, count } => match query {- DispatchQuery::Alternatives => {- let start = out.len();- for &operand in self.operands(first, count) {- if !self.dispatch_analysis_excluding(operand, relation, query, out, excluded)- || out.len() - start > MAX_DISPATCH_KEYS- {- out.truncate(start);- return false;- }- }- out[start..].sort_unstable();- let mut unique_end = start;- for read_index in start..out.len() {- if unique_end == start || out[read_index] != out[unique_end - 1] {- out[unique_end] = out[read_index];- unique_end += 1;- }- }- out.truncate(unique_end);- true- }- DispatchQuery::Required => {- let mut keys = Vec::new();- if self.dispatch_analysis_excluding(id, relation, DispatchQuery::Alternatives, &mut keys, excluded)- && keys.len() == 1- {- out.push(keys[0]);- }- true- }- },- SelectorOp::Where(inner)- | SelectorOp::Host(inner)- | SelectorOp::Slotted(inner)- | SelectorOp::ExposedToHost { parts: inner, .. } => {- self.dispatch_analysis_excluding(inner, relation, query, out, excluded)- }- SelectorOp::InScope { inner, .. } if query != DispatchQuery::Required => {- self.dispatch_analysis_excluding(inner, relation, query, out, excluded)- }- SelectorOp::Part(part) => {- out.push(DispatchKey::Part(part));- true- }- SelectorOp::ValueState {- kind: ValueStateTestKind::CustomState,- value,- } => {- out.push(DispatchKey::CustomState(value));- true- }- SelectorOp::ValueState {- kind: ValueStateTestKind::Directionality,- value,- } => {- out.push(DispatchKey::Directionality(value));- true- }- // A state is a necessary feature of any compound testing it, and one with a posting- // also names the compound's candidates: the focused element, the hovered chain. A state- // without one names nothing, and admitting it as a candidate key would take the- // compound away from names that do.- SelectorOp::State(state) if query == DispatchQuery::Required || state.has_selector_posting() => {- if excluded == Some(DispatchKey::State(state)) {- return query == DispatchQuery::Required;- }- out.push(DispatchKey::State(state));- true- }- _ => query == DispatchQuery::Required,- }- }-- fn dispatch_key_of(&self, id: SelectorNodeID) -> DispatchKey {- match self.node(id) {- SelectorOp::Feature(test) => Self::dispatch_key_for_feature(test),- SelectorOp::And { first, count } => self- .operands(first, count)- .iter()- .map(|&operand| self.dispatch_key_of(operand))- .min_by_key(|&key| dispatch_selectivity(key))- .unwrap_or(DispatchKey::Universal),- SelectorOp::Where(inner)- | SelectorOp::InScope { inner, .. }- | SelectorOp::ExposedToHost { parts: inner, .. } => self.dispatch_key_of(inner),- SelectorOp::Part(part) => DispatchKey::Part(part),- SelectorOp::ValueState {- kind: ValueStateTestKind::CustomState,- value,- } => DispatchKey::CustomState(value),- SelectorOp::ValueState {- kind: ValueStateTestKind::Directionality,- value,- } => DispatchKey::Directionality(value),- SelectorOp::Root => DispatchKey::Root,- SelectorOp::State(state) => DispatchKey::State(state),- SelectorOp::Heading(_) => DispatchKey::Heading,- _ => DispatchKey::Universal,- }- }-- /// How many siblings back of this node's subject a leading adjacent chain reaches.- ///- /// Asked of a relative argument's compound, it counts the argument's own adjacent steps on top of- /// the axis it starts on. A `~` step in that chain reaches every preceding sibling, so the answer- /// is unbounded.- fn adjacent_reach(&self, compound: SelectorNodeID) -> u32 {- let operands = match self.node(compound) {- SelectorOp::And { first, count } => self.operands(first, count),- _ => std::slice::from_ref(&compound),- };- for &operand in operands {- match self.node(operand) {- SelectorOp::PreviousSibling(inner) => return self.adjacent_reach(inner).saturating_add(1),- SelectorOp::PrecedingSibling(_) => return u32::MAX,- _ => {}- }- }- 1- }-- /// Whether the compound written before a `::part()` names the host of the tree its rule is in.- ///- /// A rule reaches the parts of the trees hosted below its own, and one written `:host::part(p)`- /// reaches the parts of its own tree as well - those are the ones an inner tree forwarded out- /// through `exportparts`. Which of the two a rule asks for is what its compound says.- #[must_use]- pub(super) fn mentions_the_host(&self, id: SelectorNodeID) -> bool {- match self.node(id) {- SelectorOp::Host(_) => true,- SelectorOp::And { first, count } | SelectorOp::Or { first, count } => self- .operands(first, count)- .iter()- .any(|&operand| self.mentions_the_host(operand)),- SelectorOp::Where(inner) | SelectorOp::Not(inner) => self.mentions_the_host(inner),- _ => false,- }- }-- /// Whether satisfying this node requires the subject to carry a fact it would publish.- ///- /// Every fact an element has is published as it connects, so a compound resting on one is- /// reached from that fact and needs nothing from the tree delta. A negation is satisfied by- /// absence and `*` by existence alone; a step leads away from the subject and says nothing about- /// it. A disjunction rests on a fact only when every branch does, since any branch can be the- /// one that holds.- fn tests_a_published_fact(&self, id: SelectorNodeID) -> bool {- match self.node(id) {- // Neither is a fact an arrival can be recognised by. `*` names none, and a namespace- // routes from nothing: an element's is fixed when it is created, so no input ever moves- // it and no entry point registers under it.- SelectorOp::Feature(FeatureTest::AnyElement | FeatureTest::Namespace(_)) => false,- // A position is not a fact the element carries: the child sequence decides it, and an- // element arriving publishes nothing that says where in one it landed.- SelectorOp::NthPosition(_) => false,- SelectorOp::State(fact) => state_is_published_on_arrival(fact),- SelectorOp::IsNode(_) | SelectorOp::ScopeRootInstance | SelectorOp::RelativeAnchorInstance => false,- // A scope bounds where the subject is; whether the subject is recognisable on arrival is- // what the rule writes inside it.- SelectorOp::InScope { inner, .. } => self.tests_a_published_fact(inner),- SelectorOp::Feature(_)- | SelectorOp::ValueState { .. }- | SelectorOp::Language { .. }- | SelectorOp::Heading(_)- | SelectorOp::Part(_)- | SelectorOp::Root- | SelectorOp::Empty- | SelectorOp::Scope => true,- SelectorOp::And { first, count } => self- .operands(first, count)- .iter()- .any(|&operand| self.tests_a_published_fact(operand)),- SelectorOp::Or { first, count } => self- .operands(first, count)- .iter()- .all(|&operand| self.tests_a_published_fact(operand)),- SelectorOp::Where(inner) | SelectorOp::Host(inner) | SelectorOp::Slotted(inner) => {- self.tests_a_published_fact(inner)- }- // The names were conjuncts of the enclosing compound before they moved under this op,- // where a published fact anywhere in it answered for the whole.- SelectorOp::ExposedToHost { host, parts } => {- self.tests_a_published_fact(host) || self.tests_a_published_fact(parts)- }- SelectorOp::Not(_)- | SelectorOp::Parent(_)- | SelectorOp::Ancestor(_)- | SelectorOp::PreviousSibling(_)- | SelectorOp::PrecedingSibling(_)- | SelectorOp::AssignedSlot(_)- | SelectorOp::BackingElement { .. }- | SelectorOp::RelativeExists(_) => false,- }- }-- /// Whether one selector IR node can be evaluated from only the changed element's fact row.- ///- /// Routing uses this for origin compounds. Tree position, relative queries, shadow-tree- /// crossings, and scope bindings stay on the conservative path.- pub(crate) fn selector_node_reads_only_local_facts(&self, id: SelectorNodeID) -> bool {- match self.node(id) {- SelectorOp::Feature(_)- | SelectorOp::State(_)- | SelectorOp::Part(_)- | SelectorOp::ValueState { .. }- | SelectorOp::Language { .. }- | SelectorOp::Heading(_) => true,- SelectorOp::And { first, count } | SelectorOp::Or { first, count } => self- .operands(first, count)- .iter()- .all(|&operand| self.selector_node_reads_only_local_facts(operand)),- SelectorOp::Where(inner) | SelectorOp::Not(inner) => self.selector_node_reads_only_local_facts(inner),- _ => false,- }- }-- /// Whether nothing an element publishes as it arrives can turn this entry's answer off.- ///- /// An arriving element is routed from the facts it publishes, and for most shapes those facts- /// can only add a match: the entry either did not hold before and holds now, or held all along.- /// Three shapes break that and have to be answered on both sides like any other change. A- /// negation is satisfied by the absence of what arrived; `:empty` stops holding on the parent an- /// element arrives under; and a positional test moves under every element placed beside the one- /// it counts. `:has()` is not one of them - a witness arriving can only add one - so its- /// argument is descended into rather than refused.- #[must_use]- fn entry_is_monotone_under_arrivals(&self, id: SelectorNodeID) -> bool {- match self.node(id) {- SelectorOp::Not(_) | SelectorOp::Empty | SelectorOp::NthPosition(_) => false,- SelectorOp::And { first, count } | SelectorOp::Or { first, count } => self- .operands(first, count)- .iter()- .all(|&operand| self.entry_is_monotone_under_arrivals(operand)),- SelectorOp::Where(inner)- | SelectorOp::Parent(inner)- | SelectorOp::Ancestor(inner)- | SelectorOp::PreviousSibling(inner)- | SelectorOp::PrecedingSibling(inner)- | SelectorOp::Host(inner)- | SelectorOp::Slotted(inner)- | SelectorOp::AssignedSlot(inner)- | SelectorOp::BackingElement { inner, .. } => self.entry_is_monotone_under_arrivals(inner),- SelectorOp::ExposedToHost { host, parts } => {- self.entry_is_monotone_under_arrivals(host) && self.entry_is_monotone_under_arrivals(parts)- }- SelectorOp::RelativeExists(query) => {- self.entry_is_monotone_under_arrivals(self.relative_query(query).compound)- }- // A scope's limit excludes what matches it, which is a negation by another name, and- // which root a subject resolves through is what binds `:scope`. Neither is worth- // proving here.- SelectorOp::InScope { .. } => false,- SelectorOp::Feature(_)- | SelectorOp::State(_)- | SelectorOp::Part(_)- | SelectorOp::Root- | SelectorOp::Scope- | SelectorOp::ScopeRootInstance- | SelectorOp::RelativeAnchorInstance- | SelectorOp::IsNode(_)- | SelectorOp::ValueState { .. }- | SelectorOp::Language { .. }- | SelectorOp::Heading(_) => true,- }- }-- /// Whether the transaction view carries every before-side tree relation this entry can observe.- ///- /// The before side reconstructs old parent and sibling relations, not departed subtrees, shadow- /// relations, positional state, or scope instances. Restrict exact old-side evaluation to the- /// operators whose complete inputs it therefore holds.- #[must_use]- fn entry_can_use_before_sibling_relations(&self, id: SelectorNodeID) -> bool {- match self.node(id) {- SelectorOp::And { first, count } | SelectorOp::Or { first, count } => self- .operands(first, count)- .iter()- .all(|&operand| self.entry_can_use_before_sibling_relations(operand)),- SelectorOp::Where(inner)- | SelectorOp::Parent(inner)- | SelectorOp::Ancestor(inner)- | SelectorOp::PreviousSibling(inner)- | SelectorOp::PrecedingSibling(inner) => self.entry_can_use_before_sibling_relations(inner),- SelectorOp::NthPosition(position) => position- .of_selector- .is_none_or(|selector| self.entry_can_use_before_sibling_relations(selector)),- SelectorOp::Feature(_)- | SelectorOp::State(_)- | SelectorOp::Root- | SelectorOp::IsNode(_)- | SelectorOp::Heading(_) => true,- SelectorOp::Not(_)- | SelectorOp::RelativeExists(_)- | SelectorOp::Host(_)- | SelectorOp::Slotted(_)- | SelectorOp::Part(_)- | SelectorOp::ExposedToHost { .. }- | SelectorOp::BackingElement { .. }- | SelectorOp::Empty- | SelectorOp::Scope- | SelectorOp::AssignedSlot(_)- | SelectorOp::ScopeRootInstance- | SelectorOp::RelativeAnchorInstance- | SelectorOp::ValueState { .. }- | SelectorOp::Language { .. }- | SelectorOp::InScope { .. } => false,- }- }-- #[must_use]- fn entry_observes_sibling_relation(&self, id: SelectorNodeID) -> bool {- match self.node(id) {- SelectorOp::And { first, count } | SelectorOp::Or { first, count } => self- .operands(first, count)- .iter()- .any(|&operand| self.entry_observes_sibling_relation(operand)),- SelectorOp::PreviousSibling(_) | SelectorOp::PrecedingSibling(_) => true,- SelectorOp::Where(inner)- | SelectorOp::Not(inner)- | SelectorOp::Parent(inner)- | SelectorOp::Ancestor(inner)- | SelectorOp::Host(inner)- | SelectorOp::Slotted(inner)- | SelectorOp::AssignedSlot(inner)- | SelectorOp::BackingElement { inner, .. } => self.entry_observes_sibling_relation(inner),- SelectorOp::ExposedToHost { host, parts } => {- self.entry_observes_sibling_relation(host) || self.entry_observes_sibling_relation(parts)- }- SelectorOp::RelativeExists(query) => {- self.entry_observes_sibling_relation(self.relative_query(query).compound)- }- SelectorOp::NthPosition(_) => true,- SelectorOp::InScope { root, limit, inner, .. } => {- self.entry_observes_sibling_relation(inner)- || self.entry_observes_sibling_relation(root)- || limit.is_some_and(|limit| self.entry_observes_sibling_relation(limit))- }- SelectorOp::Feature(_)- | SelectorOp::State(_)- | SelectorOp::Part(_)- | SelectorOp::Root- | SelectorOp::Empty- | SelectorOp::Scope- | SelectorOp::ScopeRootInstance- | SelectorOp::RelativeAnchorInstance- | SelectorOp::IsNode(_)- | SelectorOp::ValueState { .. }- | SelectorOp::Language { .. }- | SelectorOp::Heading(_) => false,- }- }-- /// Whether this node's subject can lie outside the scope its rule is attached to.- ///- /// `:host`, `::slotted()` and `::part()` are the constructs a scope reaches out of - a sheet in a- /// shadow root styles its host and the nodes slotted into it through them, and nothing else. A- /// program with none of them decides only inside its own scope, which is what lets a shadow- /// sheet's rules be narrowed to the scope instead of to every element in the document carrying- /// the same class.- fn leaves_its_scope(&self, id: SelectorNodeID) -> bool {- match self.node(id) {- SelectorOp::Host(_) | SelectorOp::Slotted(_) | SelectorOp::ExposedToHost { .. } => true,- SelectorOp::Part(_) => true,- SelectorOp::Language { .. } => false,- SelectorOp::ScopeRootInstance | SelectorOp::RelativeAnchorInstance => false,- // The step lands on the slot, which is inside the scope; what stands outside it is the- // subject, and the `::slotted()` beside this says so.- SelectorOp::AssignedSlot(_) => false,- // The element backing a pseudo-element stands in the shadow tree its host hosts, which- // is a tree of its own.- SelectorOp::BackingElement { .. } => true,- // An implicit scoping root is the parent of its sheet's owner node, which for a sheet- // that is a direct child of a shadow root is the host - outside the tree. Which element- // it is is not a property of the program, so this is the widest of the two answers and- // the evaluation settles it.- SelectorOp::IsNode(_) => true,- // A scope can be rooted outside the tree its sheet is in - `@scope (:host)` roots at the- // host - and then everything inside it decides for an element the scope does not hold.- SelectorOp::InScope { root, limit, inner, .. } => {- self.leaves_its_scope(inner)- || self.leaves_its_scope(root)- || limit.is_some_and(|limit| self.leaves_its_scope(limit))- }- SelectorOp::And { first, count } | SelectorOp::Or { first, count } => self- .operands(first, count)- .iter()- .any(|&operand| self.leaves_its_scope(operand)),- SelectorOp::Where(inner)- | SelectorOp::Not(inner)- | SelectorOp::Parent(inner)- | SelectorOp::Ancestor(inner)- | SelectorOp::PreviousSibling(inner)- | SelectorOp::PrecedingSibling(inner) => self.leaves_its_scope(inner),- SelectorOp::RelativeExists(query) => self.leaves_its_scope(self.relative_query(query).compound),- SelectorOp::NthPosition(position) => position- .of_selector- .is_some_and(|selector| self.leaves_its_scope(selector)),- SelectorOp::Feature(_)- | SelectorOp::State(_)- | SelectorOp::Root- | SelectorOp::Empty- | SelectorOp::Scope- | SelectorOp::ValueState { .. }- | SelectorOp::Heading(_) => false,- }- }-- /// Whether this node's subject itself can lie outside the scope its rule is attached to.- ///- /// `leaves_its_scope` answers whether the program reads anything outside the scope, and a- /// `:host()` under a combinator does: the host's facts decide the rule. Its subject still stays- /// inside the tree, because a shadow sheet's combinators never reach the host's light-DOM- /// children. So only a `:host`, `::slotted()` or `::part()` in subject position, and the- /// implicit scoping root that can be the host, move the subject out; a combinator step, a- /// relative selector and an `of` selector all constrain something other than the subject.- fn subject_leaves_its_scope(&self, id: SelectorNodeID) -> bool {- match self.node(id) {- SelectorOp::Host(_) | SelectorOp::Slotted(_) | SelectorOp::ExposedToHost { .. } => true,- SelectorOp::Part(_) => true,- SelectorOp::IsNode(_) => true,- SelectorOp::InScope { root, limit, inner, .. } => {- self.subject_leaves_its_scope(inner)- || self.leaves_its_scope(root)- || limit.is_some_and(|limit| self.leaves_its_scope(limit))- }- SelectorOp::And { first, count } | SelectorOp::Or { first, count } => self- .operands(first, count)- .iter()- .any(|&operand| self.subject_leaves_its_scope(operand)),- SelectorOp::Where(inner) | SelectorOp::Not(inner) => self.subject_leaves_its_scope(inner),- SelectorOp::Parent(_)- | SelectorOp::Ancestor(_)- | SelectorOp::PreviousSibling(_)- | SelectorOp::PrecedingSibling(_)- | SelectorOp::RelativeExists(_)- | SelectorOp::NthPosition(_)- | SelectorOp::AssignedSlot(_)- | SelectorOp::BackingElement { .. }- | SelectorOp::Language { .. }- | SelectorOp::ScopeRootInstance- | SelectorOp::RelativeAnchorInstance- | SelectorOp::Feature(_)- | SelectorOp::State(_)- | SelectorOp::Root- | SelectorOp::Empty- | SelectorOp::Scope- | SelectorOp::ValueState { .. }- | SelectorOp::Heading(_) => false,- }- }-- /// Whether any of this program's entries can decide outside the scope it is attached to.- #[must_use]- pub fn can_leave_its_scope(&self) -> bool {- self.can_leave_scope- }-- /// Whether any of this program's entries can have a subject outside the scope it is attached- /// to. Narrower than `can_leave_its_scope`: a program whose `:host()` only constrains an- /// ancestor reads the host but names subjects inside its own tree.- #[must_use]- pub fn subject_can_leave_its_scope(&self) -> bool {- self.subject_can_leave_scope- }-- /// Whether the host itself is a subject of this program, rather than only a step on the way to- /// one. `:host` selects the host; `:host *` selects its descendants and says nothing about it.- #[must_use]- pub fn host_is_a_subject(&self) -> bool {- self.entries().iter().any(|entry| self.subject_is_the_host(entry.root))- }-- /// Whether this compound's own subject is the shadow host. Combinators are not descended into: a- /// `:host` beneath one constrains something else, not the subject.- pub fn subject_is_the_host(&self, id: SelectorNodeID) -> bool {- match self.node(id) {- SelectorOp::Host(_) => true,- // An implicit scoping root can be the host, and nothing in the program says whether- // this one is. Asking the host is the widest of the two answers.- SelectorOp::IsNode(_) => true,- // `:scope` is explicitly allowed to match a featureless host when that host is the- // scoping root. The inner selector otherwise decides which element is the subject.- SelectorOp::InScope {- root,- inner,- names_the_scope,- ..- } => self.subject_is_the_host(inner) || (names_the_scope && self.subject_is_the_host(root)),- // Every simple selector in a compound has to be allowed to match a featureless host.- // `:has()` is the one exception: it is allowed when another simple selector in the- // compound is allowed, so it does not disqualify an otherwise valid host compound.- SelectorOp::And { first, count } => {- let operands = self.operands(first, count);- operands.iter().any(|&operand| {- !matches!(- self.node(operand),- SelectorOp::Feature(FeatureTest::AnyElement) | SelectorOp::RelativeExists(_)- ) && self.subject_is_the_host(operand)- }) && operands.iter().all(|&operand| {- matches!(- self.node(operand),- SelectorOp::Feature(FeatureTest::AnyElement) | SelectorOp::RelativeExists(_)- ) || self.subject_is_the_host(operand)- })- }- SelectorOp::Or { first, count } => self- .operands(first, count)- .iter()- .any(|&operand| self.subject_is_the_host(operand)),- SelectorOp::Where(inner) | SelectorOp::Not(inner) => self.subject_is_the_host(inner),- SelectorOp::ScopeRootInstance => true,- _ => false,- }- }-- /// Whether this entry's own subject is a node slotted into the rule's tree.- ///- /// A shadow tree reaches a slotted element through `::slotted()` and through nothing else: its- /// ordinary selectors decide inside the tree, and the slotted element is not in it. So a pass- /// that asks a tree's rules of an element slotted into it asks only these.- #[must_use]- pub fn subject_is_slotted(&self, id: SelectorNodeID) -> bool {- match self.node(id) {- SelectorOp::Slotted(_) => true,- SelectorOp::InScope { inner, .. } => self.subject_is_slotted(inner),- SelectorOp::And { first, count } | SelectorOp::Or { first, count } => self- .operands(first, count)- .iter()- .any(|&operand| self.subject_is_slotted(operand)),- SelectorOp::Where(inner) | SelectorOp::Not(inner) => self.subject_is_slotted(inner),- _ => false,- }- }-- /// Whether this entry's own subject is a part exposed out of the rule's tree.- ///- /// A scope outside a shadow tree reaches into it through `::part()` and through nothing else,- /// so a pass that asks an outer scope's rules of a part asks only these.- #[must_use]- pub fn subject_is_a_part(&self, id: SelectorNodeID) -> bool {- match self.node(id) {- SelectorOp::Part(_) | SelectorOp::ExposedToHost { .. } => true,- SelectorOp::InScope { inner, .. } => self.subject_is_a_part(inner),- SelectorOp::And { first, count } | SelectorOp::Or { first, count } => self- .operands(first, count)- .iter()- .any(|&operand| self.subject_is_a_part(operand)),- SelectorOp::Where(inner) | SelectorOp::Not(inner) => self.subject_is_a_part(inner),- _ => false,- }- }-- /// How many sibling relations reaching this node's subject passes through.- ///- /// Asked of a relative argument's compound, it says whether a change to a child sequence can flip- /// the argument's truth for a witness that did not itself change - once the step the axis itself- /// contributes is discounted. A nested `:has()` cannot occur, so its argument is not descended- /// into.- fn count_sibling_steps(&self, id: SelectorNodeID) -> usize {- match self.node(id) {- SelectorOp::PreviousSibling(inner) | SelectorOp::PrecedingSibling(inner) => {- 1 + self.count_sibling_steps(inner)- }- SelectorOp::Language { .. }- | SelectorOp::IsNode(_)- | SelectorOp::AssignedSlot(_)- | SelectorOp::ScopeRootInstance- | SelectorOp::RelativeAnchorInstance => 0,- SelectorOp::InScope { inner, .. } => self.count_sibling_steps(inner),- SelectorOp::And { first, count } | SelectorOp::Or { first, count } => self- .operands(first, count)- .iter()- .map(|&operand| self.count_sibling_steps(operand))- .max()- .unwrap_or(0),- SelectorOp::Where(inner)- | SelectorOp::Not(inner)- | SelectorOp::Parent(inner)- | SelectorOp::Ancestor(inner)- | SelectorOp::Host(inner)- | SelectorOp::Slotted(inner)- | SelectorOp::BackingElement { inner, .. } => self.count_sibling_steps(inner),- SelectorOp::ExposedToHost { host, parts } => {- self.count_sibling_steps(host).max(self.count_sibling_steps(parts))- }- SelectorOp::NthPosition(position) => position- .of_selector- .map_or(0, |selector| self.count_sibling_steps(selector)),- SelectorOp::Feature(_)- | SelectorOp::State(_)- | SelectorOp::RelativeExists(_)- | SelectorOp::Part(_)- | SelectorOp::Root- | SelectorOp::Empty- | SelectorOp::Scope- | SelectorOp::ValueState { .. }- | SelectorOp::Heading(_) => 0,- }- }-- /// The set of dispatch keys a compound can be reached by, or `false` when no useful set exists.- ///- /// A single key cannot describe a disjunction. `:is(button, select):hover` is satisfied by- /// either branch, so the only sound single key for it is the universal one - and a compound- /// that dispatches universally rejects nothing, which is how a user-agent rule about buttons- /// ends up routed from a hover on a paragraph. A set describes it exactly: an element carrying- /// none of these keys cannot satisfy the compound.- ///- /// The set is bounded. Past [`MAX_DISPATCH_KEYS`] the membership checks cost more than the- /// rejections save, and the compound is universal again.- fn dispatch_keys_of(&self, id: SelectorNodeID, out: &mut Vec<DispatchKey>) -> bool {- self.dispatch_analysis(id, DispatchRelation::Subject, DispatchQuery::Alternatives, out)- }-- fn required_dispatch_keys_of(&self, id: SelectorNodeID, out: &mut Vec<DispatchKey>) {- self.dispatch_analysis(id, DispatchRelation::Subject, DispatchQuery::Required, out);- }-- fn dispatch_key_for_feature(test: FeatureTest) -> DispatchKey {- dispatch_key_for_feature(test)- }-}--/// The key a feature test dispatches on.-#[must_use]-fn dispatch_key_for_feature(test: FeatureTest) -> DispatchKey {- match test {- FeatureTest::Id(id) => DispatchKey::Id(id),- FeatureTest::Class(class) => DispatchKey::Class(class),- FeatureTest::Attribute(attribute) => DispatchKey::AttributeName(attribute.folded),- // Dispatch on the folded form, because that is the one every element the test can match is- // reachable by: an element's own facts carry both forms when they differ.- FeatureTest::TagName(tag) => DispatchKey::TagName(tag.folded),- // A namespace constrains a name rather than distinguishing an element, and every element- // carries one, so it buckets with the universal selector and rejects in the compound.- FeatureTest::AnyElement | FeatureTest::Namespace(_) => DispatchKey::Universal,- }-}--/// How many keys a compound may carry before checking them all costs more than the rejections save.-const MAX_DISPATCH_KEYS: usize = 8;--/// How many independent compound requirements transpose routing retains.-const MAX_REQUIRED_DISPATCH_KEYS: usize = 8;--/// How much a whole key set costs to check, so the cheapest of a conjunction's operands wins.-fn dispatch_set_cost(keys: &[DispatchKey]) -> u32 {- keys.iter().map(|&key| u32::from(dispatch_selectivity(key)) + 1).sum()-}--/// How selective a dispatch key is expected to be, lowest first. An ID names at most a handful of-/// elements; the universal bucket names all of them.-fn dispatch_selectivity(key: DispatchKey) -> u8 {- match key {- DispatchKey::Part(_) => 0,- DispatchKey::CustomState(_) => 0,- DispatchKey::Id(_) => 0,- DispatchKey::Class(_) => 1,- DispatchKey::AttributeName(_) => 2,- DispatchKey::TagName(_) => 3,- // A document usually resolves to one direction, so this names most of it.- DispatchKey::Directionality(_) => 4,- // These three are ranked behind every name a compound can carry, even though `:root` names- // one element and most states name none. A name has a posting to enumerate from and most- // of these do not, so preferring one would trade a tighter reaction batch for a dispatch- // that is no more selective in practice: `a:hover` is as well found in the `a` bucket.- // What they are for is the compound that carries no name at all, which is where a bare- // `:root` or `:hover` rule would otherwise sit in front of every element in the document.- DispatchKey::Root => 5,- DispatchKey::State(_) => 5,- DispatchKey::Heading => 5,- DispatchKey::Universal => 6,- _ => unreachable!("non-dispatch feature key"),- }-}--struct SharedSelectorProgram {- program: SelectorProgram,- hash: u64,- /// The document and rule that routed the program first, as `transpose_router` packs them, or- /// `UNROUTED` before any did.- first_transpose_router: std::sync::atomic::AtomicU64,- /// Each entry's transpose entry points, walked once a second rule or document routes the program. Routing copies- /// the sites it visits, so keeping them only pays off for a program that more than one rule or document routes.- transpose_sites: std::sync::OnceLock<TransposeSites>,-}--/// The transpose entry points of each entry of a shared program, charged to the process's program pools.-struct TransposeSites {- by_entry: Box<[Box<[OwnedTransposeSite]>]>,-}--/// A transpose entry point kept beside the program it was walked from.-struct OwnedTransposeSite {- key: RoutingKey,- node: SelectorNodeID,- origin: SelectorNodeID,- path: Box<[InverseStep]>,- anchor: Option<RelativeAnchor>,- origin_dispatch: Box<[DispatchKey]>,- origin_required: Box<[DispatchKey]>,- parent_dispatch: Box<[DispatchKey]>,- waypoints: Box<[DispatchKey]>,-}--impl OwnedTransposeSite {- fn new(site: TransposeSite<'_>) -> Self {- Self {- key: site.key,- node: site.node,- origin: site.origin,- path: site.path.into(),- anchor: site.anchor,- origin_dispatch: site.origin_dispatch.into(),- origin_required: site.origin_required.into(),- parent_dispatch: site.parent_dispatch.into(),- waypoints: site.waypoints.into(),- }- }-- fn site(&self) -> TransposeSite<'_> {- TransposeSite {- key: self.key,- node: self.node,- origin: self.origin,- path: &self.path,- anchor: self.anchor,- origin_dispatch: &self.origin_dispatch,- origin_required: &self.origin_required,- parent_dispatch: &self.parent_dispatch,- waypoints: &self.waypoints,- }- }-}--/// A selector program interned for the whole process, which a document attaches without compiling it.-#[derive(Clone)]-pub(super) struct ProcessSelectorProgram(Arc<SharedSelectorProgram>);--impl ProcessSelectorProgram {- pub(super) fn share(program: SelectorProgram) -> Self {- let hash = SelectorPrograms::program_hash(&program);- Self(share_selector_program(- program,- hash,- &mut selector_program_pools().programs,- ))- }-- pub(super) fn program(&self) -> &SelectorProgram {- &self.0.program- }-}--/// A strong identity for an interned selector. Keeping the payload alive prevents an-/// address from being recycled while a dispatch sharing key still refers to it.-#[derive(Clone)]-pub(super) struct SharedSelectorIdentity(Arc<SharedSelectorProgram>);--impl PartialEq for SharedSelectorIdentity {- fn eq(&self, other: &Self) -> bool {- Arc::ptr_eq(&self.0, &other.0)- }-}--impl Eq for SharedSelectorIdentity {}--impl Hash for SharedSelectorIdentity {- fn hash<H: Hasher>(&self, state: &mut H) {- Arc::as_ptr(&self.0).hash(state);- }-}--fn share_selector_program(- program: SelectorProgram,- hash: u64,- pool: &mut WeakPool<SharedSelectorProgram>,-) -> Arc<SharedSelectorProgram> {- if let Some(found) = pool.find(hash, |candidate| candidate.program == program) {- return found;- }-- let program = Arc::new(SharedSelectorProgram {- program,- hash,- first_transpose_router: std::sync::atomic::AtomicU64::new(UNROUTED),- transpose_sites: std::sync::OnceLock::new(),- });- pool.insert(hash, &program);- program-}--#[derive(Clone)]-enum SelectorProgramStorage {- Document(Arc<SelectorProgram>),- Process(Arc<SharedSelectorProgram>),-}--impl PartialEq for SelectorProgramStorage {- fn eq(&self, other: &Self) -> bool {- match (self, other) {- (Self::Document(first), Self::Document(second)) => Arc::ptr_eq(first, second),- (Self::Process(first), Self::Process(second)) => Arc::ptr_eq(first, second),- _ => false,- }- }-}--impl Eq for SelectorProgramStorage {}--impl Hash for SelectorProgramStorage {- fn hash<H: Hasher>(&self, state: &mut H) {- std::mem::discriminant(self).hash(state);- match self {- Self::Document(program) => Arc::as_ptr(program).hash(state),- Self::Process(program) => Arc::as_ptr(program).hash(state),- }- }-}--impl SelectorProgramStorage {- fn program(&self) -> &SelectorProgram {- match self {- Self::Document(program) => program,- Self::Process(program) => &program.program,- }- }-- fn hash(&self) -> u64 {- match self {- Self::Document(program) => SelectorPrograms::program_hash(program),- Self::Process(program) => program.hash,- }- }-}--#[derive(Clone, Copy, Default)]-enum SelectorProgramScope {- #[default]- Document,- Process,-}--/// Entry IDs normally form a consecutive run. Keep that run inline, and share an explicit-/// list only when recycling vacant entries gives a program nonconsecutive identities.-#[derive(Clone, PartialEq, Eq, Hash)]-pub(super) enum SelectorEntryIDs {- Consecutive { first: EntryID, count: u32 },- // Keep a thin pointer here: an Arc slice would enlarge every inline consecutive range.- Explicit(Arc<Box<[EntryID]>>),-}--impl SelectorEntryIDs {- fn from_entries(entries: Vec<EntryID>) -> Self {- if entries- .windows(2)- .all(|pair| pair[0].0.checked_add(1) == Some(pair[1].0))- {- Self::Consecutive {- first: entries.first().copied().unwrap_or(EntryID(0)),- count: u32::try_from(entries.len()).expect("selector program entry space exhausted"),- }- } else {- Self::Explicit(Arc::new(entries.into_boxed_slice()))- }- }-- fn len(&self) -> usize {- match self {- Self::Consecutive { count, .. } => *count as usize,- Self::Explicit(entries) => entries.len(),- }- }-- fn get(&self, index: usize) -> EntryID {- assert!(index < self.len());- match self {- Self::Consecutive { first, .. } => EntryID(first.0 + index as u32),- Self::Explicit(entries) => entries[index],- }- }-- fn iter(&self) -> impl ExactSizeIterator<Item = EntryID> + '_ {- (0..self.len()).map(|index| self.get(index))- }-}--/// The process's pools for selector programs and their attachments, shared by every engine.-#[derive(Default)]-struct SelectorProgramPools {- programs: WeakPool<SharedSelectorProgram>,- entry_attachments: SharedVectorPool<Option<SelectorEntryIDs>>,- program_attachments: SharedVectorPool<Option<SelectorProgramStorage>>,- program_indices: SharedVectorPool<Option<NonZeroU32>>,- entry_locations: SharedVectorPool<Option<(NonZeroU32, u32)>>,-}--fn selector_program_pools() -> MutexGuard<'static, SelectorProgramPools> {- // Every engine interns through the same pools, from whichever thread runs it. Values never- // reach back into a pool when they are dropped, so the lock is only held while interning.- static SELECTOR_PROGRAM_POOLS: OnceLock<Mutex<SelectorProgramPools>> = OnceLock::new();- SELECTOR_PROGRAM_POOLS.get_or_init(Mutex::default).lock().unwrap()-}--const UNROUTED: u64 = u64::MAX;--fn next_document_router() -> u32 {- static NEXT: std::sync::atomic::AtomicU32 = std::sync::atomic::AtomicU32::new(0);- NEXT.fetch_add(1, std::sync::atomic::Ordering::Relaxed)-}--/// One document's attachments to compiled selector programs.-///-/// The immutable program payloads are interned in the process's pool. Entry identities,-/// attached rules, and every selector-result materialization remain document-local.-#[derive(Clone)]-pub struct SelectorPrograms {- programs: SharedVector<Option<SelectorProgramStorage>>,- vacant_programs: Vec<SelectorProgramID>,- entry_ids_by_program: SharedVector<Option<SelectorEntryIDs>>,- entry_locations: SharedVector<Option<(NonZeroU32, u32)>>,- vacant_entries: Vec<EntryID>,- /// Open-addressed structural interning table. Reclamation rebuilds it, so lookup never has to- /// carry tombstones for vacant program identities.- program_index: SharedVector<Option<NonZeroU32>>,- /// What the programs themselves reserve, accumulated as they arrive. A program is immutable- /// once compiled, so this is settled by the one place that can move it - which matters because- /// compiling a rule settles the charge, and deriving it by walking the list would make a sheet- /// cost a pass over every rule already in the document for each rule it adds.- scope: SelectorProgramScope,- /// Tells this document's routing of a process-shared program apart from other documents'.- router: u32,-}--impl Default for SelectorPrograms {- fn default() -> Self {- Self {- programs: SharedVector::default(),- vacant_programs: Vec::new(),- entry_ids_by_program: SharedVector::default(),- entry_locations: SharedVector::default(),- vacant_entries: Vec::new(),- program_index: SharedVector::default(),-- scope: SelectorProgramScope::Document,- router: next_document_router(),- }- }-}--impl SelectorPrograms {- pub(super) fn collect_atoms(&self, atoms: &mut HashSet<StyleAtomID>) -> u64 {- self.programs- .iter()- .flatten()- .map(|program| program.program().collect_atoms(atoms))- .sum()- }-- #[must_use]- #[cfg(test)]- pub fn new() -> Self {- Self::default()- }-- pub(super) fn for_live_engine() -> Self {- Self {- #[cfg(not(test))]- scope: SelectorProgramScope::Process,- ..Self::default()- }- }-- /// Programs shared with every other document's, as a live engine's are outside tests.- #[cfg(test)]- pub(super) fn shared_across_documents() -> Self {- Self {- scope: SelectorProgramScope::Process,- ..Self::default()- }- }-- pub fn add(&mut self, program: SelectorProgram) -> SelectorProgramID {- self.add_with_status(program).0- }-- pub(super) fn add_with_status(&mut self, program: SelectorProgram) -> (SelectorProgramID, bool) {- let hash = Self::program_hash(&program);- let bucket = match self.find(hash, &program) {- Ok(id) => return (id, false),- Err(bucket) => bucket,- };- let program = match self.scope {- SelectorProgramScope::Document => SelectorProgramStorage::Document(Arc::new(program)),- SelectorProgramScope::Process => SelectorProgramStorage::Process(share_selector_program(- program,- hash,- &mut selector_program_pools().programs,- )),- };- (self.insert(bucket, program), true)- }-- /// Attach a program the process already holds, neither compiling nor hashing it again.- pub(super) fn add_process_program(&mut self, program: &ProcessSelectorProgram) -> SelectorProgramID {- match self.find(program.0.hash, &program.0.program) {- Ok(id) => id,- Err(bucket) => self.insert(bucket, SelectorProgramStorage::Process(program.0.clone())),- }- }-- /// The program equal to `program`, or the index bucket it would take.- fn find(&mut self, hash: u64, program: &SelectorProgram) -> Result<SelectorProgramID, usize> {- let live_program_count = self.programs.len() - self.vacant_programs.len();- if self.program_index.is_empty() || (live_program_count + 1) * 2 > self.program_index.len() {- self.rebuild_program_index();- }- let mut bucket = hash as usize & (self.program_index.len() - 1);- loop {- match self.program_index[bucket] {- Some(id) if self.get(SelectorProgramID(id.get() - 1)) == program => {- return Ok(SelectorProgramID(id.get() - 1));- }- Some(_) => bucket = (bucket + 1) & (self.program_index.len() - 1),- None => return Err(bucket),- }- }- }-- fn insert(&mut self, bucket: usize, program: SelectorProgramStorage) -> SelectorProgramID {- let entry_count = program.program().entries().len();- let id = self.vacant_programs.last().copied().unwrap_or_else(|| {- SelectorProgramID(u32::try_from(self.programs.len()).expect("selector program space exhausted"))- });- let stored_id = Self::stored_program_id(id);- self.vacant_programs.pop();-- if id.0 as usize == self.programs.len() {- self.programs.make_mut().push(Some(program));- } else {- self.programs.make_mut()[id.0 as usize] = Some(program);- }- let recycled_count = entry_count.min(self.vacant_entries.len());- let entries = if recycled_count == 0 {- let first = EntryID(u32::try_from(self.entry_locations.len()).expect("selector entry space exhausted"));- let count = u32::try_from(entry_count).expect("selector program entry space exhausted");- first.0.checked_add(count).expect("selector entry space exhausted");- self.entry_locations- .make_mut()- .extend((0..count).map(|index| Some((stored_id, index))));- SelectorEntryIDs::Consecutive {- first: if count == 0 { EntryID(0) } else { first },- count,- }- } else {- let mut recycled_entries = self- .vacant_entries- .split_off(self.vacant_entries.len() - recycled_count);- recycled_entries.sort_unstable();- let mut recycled_entries = recycled_entries.into_iter();- let entries = (0..entry_count)- .map(|index| {- let entry = recycled_entries.next().unwrap_or_else(|| {- EntryID(u32::try_from(self.entry_locations.len()).expect("selector entry space exhausted"))- });- let location = Some((- stored_id,- u32::try_from(index).expect("selector program entry space exhausted"),- ));- if entry.0 as usize == self.entry_locations.len() {- self.entry_locations.make_mut().push(location);- } else {- self.entry_locations.make_mut()[entry.0 as usize] = location;- }- entry- })- .collect();- SelectorEntryIDs::from_entries(entries)- };- if self.entry_ids_by_program.len() <= id.0 as usize {- self.entry_ids_by_program- .make_mut()- .resize_with(id.0 as usize + 1, || None);- }- self.entry_ids_by_program.make_mut()[id.0 as usize] = Some(entries);- self.program_index.make_mut()[bucket] = Some(Self::stored_program_id(id));- id- }-- fn rebuild_program_index(&mut self) {- let capacity = ((self.programs.len() + 1) * 4).next_power_of_two().max(16);- self.program_index.clear();- self.program_index.make_mut().resize(capacity, None);- for (index, program) in self- .programs- .iter()- .enumerate()- .filter_map(|(index, program)| program.as_ref().map(|program| (index, program)))- {- let id = SelectorProgramID(u32::try_from(index).expect("selector program space exhausted"));- let mut bucket = program.hash() as usize & (capacity - 1);- while self.program_index[bucket].is_some() {- bucket = (bucket + 1) & (capacity - 1);- }- self.program_index.make_mut()[bucket] = Some(Self::stored_program_id(id));- }- }-- fn stored_program_id(id: SelectorProgramID) -> NonZeroU32 {- NonZeroU32::new(id.0.checked_add(1).expect("selector program space exhausted")).unwrap()- }-- pub(super) fn share_indices(&mut self) {- if matches!(self.scope, SelectorProgramScope::Process) {- self.programs.share(&mut selector_program_pools().program_attachments);- }- let mut pools = selector_program_pools();- self.program_index.share(&mut pools.program_indices);- self.entry_locations.share(&mut pools.entry_locations);- self.entry_ids_by_program.share(&mut pools.entry_attachments);- drop(pools);- }-- fn program_hash(program: &SelectorProgram) -> u64 {- let mut hasher = fast_hasher();- program.hash(&mut hasher);- hasher.finish()- }-- #[must_use]- pub fn get(&self, id: SelectorProgramID) -> &SelectorProgram {- self.programs[id.0 as usize]- .as_ref()- .expect("a selector program identity must remain live while referenced")- .program()- }-- /// Visit the transpose entry points of one entry of a program that `rule` routes, as- /// `SelectorProgram::collect_transpose_entry_points` does. A program the whole process shares- /// is walked once for every later rule or document that routes it.- pub fn for_each_transpose_entry_point(- &self,- program: SelectorProgramID,- entry: usize,- rule: RuleID,- mut visit: impl FnMut(TransposeSite<'_>),- ) {- match self.programs[program.0 as usize]- .as_ref()- .expect("a selector program identity must remain live while referenced")- {- SelectorProgramStorage::Process(shared) => {- // NB: A document rebuilding its routing routes the same rules again, which does not- // make keeping the sites pay off.- let router = (u64::from(self.router) << 32) | u64::from(rule.0);- if shared.transpose_sites.get().is_none() {- let first = match shared.first_transpose_router.compare_exchange(- UNROUTED,- router,- std::sync::atomic::Ordering::Relaxed,- std::sync::atomic::Ordering::Relaxed,- ) {- Ok(_) => router,- Err(first) => first,- };- if first == router {- shared.program.collect_transpose_entry_points(entry, visit);- return;- }- }- let sites = shared.transpose_sites.get_or_init(|| {- let by_entry: Box<[Box<[OwnedTransposeSite]>]> = (0..shared.program.entries().len())- .map(|entry| {- let mut sites = Vec::new();- shared.program.collect_transpose_entry_points(entry, |site| {- sites.push(OwnedTransposeSite::new(site));- });- sites.into_boxed_slice()- })- .collect();- TransposeSites { by_entry }- });- for site in &sites.by_entry[entry] {- visit(site.site());- }- }- SelectorProgramStorage::Document(compiled) => compiled.collect_transpose_entry_points(entry, visit),- }- }-- #[must_use]- pub fn entry_id(&self, program: SelectorProgramID, entry: u32) -> EntryID {- self.entry_ids_by_program[program.0 as usize]- .as_ref()- .expect("a live selector program must have entry identities")- .get(entry as usize)- }-- pub(super) fn shared_dispatch_identity(- &self,- program: SelectorProgramID,- ) -> Option<(SharedSelectorIdentity, SelectorEntryIDs)> {- let SelectorProgramStorage::Process(shared) = self.programs[program.0 as usize].as_ref()? else {- return None;- };- Some((- SharedSelectorIdentity(Arc::clone(shared)),- self.entry_ids_by_program[program.0 as usize].as_ref()?.clone(),- ))- }-- #[must_use]- pub fn entry_location(&self, entry: EntryID) -> (SelectorProgramID, u32) {- let (program, index) =- self.entry_locations[entry.0 as usize].expect("a referenced selector entry identity must remain live");- (SelectorProgramID(program.get() - 1), index)- }-- #[must_use]- pub fn entry(&self, entry: EntryID) -> (&SelectorProgram, &SelectorEntry) {- let (program, index) = self.entry_location(entry);- let program = self.get(program);- (program, &program.entries()[index as usize])- }-- #[must_use]- pub fn entry_capacity(&self) -> usize {- self.entry_locations.len()- }-- pub fn sweep_unreferenced(&mut self, referenced: &[bool]) {- self.vacant_programs.clear();- for (index, slot) in self.programs.make_mut().iter_mut().enumerate() {- if referenced.get(index).copied().unwrap_or(false) {- assert!(slot.is_some(), "a referenced selector program must remain live");- continue;- }- *slot = None;- if let Some(entries) = self.entry_ids_by_program.make_mut()[index].take() {- for entry in entries.iter() {- self.entry_locations.make_mut()[entry.0 as usize] = None;- self.vacant_entries.push(entry);- }- }- self.vacant_programs.push(SelectorProgramID(- u32::try_from(index).expect("selector program space exhausted"),- ));- }- self.rebuild_program_index();- }-- #[must_use]- pub(super) fn has_unreferenced_programs(&self, referenced: &[bool]) -> bool {- self.programs- .iter()- .enumerate()- .any(|(index, program)| program.is_some() && !referenced.get(index).copied().unwrap_or(false))- }-- #[must_use]- #[cfg(test)]- pub fn len(&self) -> usize {- self.programs.len()- }-}--// -- Transpose direction -------------------------------------------------------------------------/// One inverse relation step: from an element where a selector input occurs, towards the subjects-/// whose match truth that input can change.-///-/// A transpose program may over-approximate but must never omit a subject, so each step names the-/// widest set the corresponding combinator can reach. Resulting subjects are checked by the match-/// program before any selector-truth delta is emitted, which is what keeps over-approximation a-/// cost rather than a correctness problem.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]-pub enum InverseStep {- /// `A B` from A: descendants of the changed element.- Descendants,- /// `A > B` from A: element children of the changed element.- Children,- /// `A + B` from A: the immediately following element sibling.- NextSibling,- /// `A ~ B` from A: following element siblings.- FollowingSiblings,- /// A change inside a positional argument moves indices within the whole child sequence.- SiblingSequence,- /// From a shadow host to the tree it hosts. Deliberately not a descendant step: a generic- /// descendant walk does not pierce a shadow root.- HostedTree,- /// From a shadow host to every tree nested below the one it hosts, shadow roots included.- ///- /// `exportparts` carries a part name outwards through any number of hosts, so the element a- /// `::part()` rule names can sit several shadow roots below the host its outer compound- /// describes - past boundaries `HostedTree` stops at.- HostedTrees,- /// From an element backing a pseudo-element to the shadow host it stands for it on.- ShadowHost,- /// From a slotted node to the slot it is assigned to, and thence into the shadow tree.- SlotAssignment,- /// From a slot to the light-DOM elements it assigns.- SlotAssignees,-}--/// The semantic feature a transpose route is routed from.-pub type RoutingKey = FeatureKey;--/// How a possible witness reaches the anchors whose relational truth it can flip.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]-pub struct RelativeAnchor {- pub axis: RelativeAxis,- /// Which of the program's relative queries this is, which is how a candidate anchor's- /// retained witness is looked up before the anchor is routed.- pub query: RelativeQueryID,- /// The rightmost distinguishing feature of the compound the `:has()` sits in. An ancestor that- /// does not carry it is not an anchor of this query, which is what keeps the anchor set small.- pub anchor_dispatch: DispatchKey,- /// The distinguishing feature of the query's own compound: what a witness of it must carry.- pub witness_dispatch: DispatchKey,- /// Whether the input occurs on the witness itself.- ///- /// The anchors are normally found by walking the inverse of the query's axis from the changed- /// element, which only works while that element is a possible witness. `:has(#d:is(.a .b))`- /// puts `.a` a step away from one, and that step can leave the anchor's subtree entirely - the- /// element carrying `.a` is then an *ancestor* of the anchor, and no walk from it finds one.- pub input_is_on_the_witness: bool,- /// Whether the input occurs on the anchor itself.- ///- /// In `:has(> :is(.active > li))`, `.active` is reached from the possible `li` witness by- /// exactly the inverse of the query's child axis. A change to that class already names the- /// anchor, so routing through every possible `li` witness would only rediscover it many times.- pub input_is_on_the_anchor: bool,- /// How many siblings back of a witness this query's anchor can be, on an adjacent axis.- ///- /// `X:has(+ B)` anchors on the element beside the witness and `X:has(+ A + B)` two beside it, so- /// an element landing in a long sequence asks that many of the elements before it whether they- /// are anchors, and not all of them. A `~` step anywhere in the chain unbounds the reach.- pub adjacent_reach: u32,- /// Whether the query's own compound has no fact for an arriving element to be named by.- ///- /// An element publishes every fact that holds on it as it connects - its tag, its id, its- /// classes, its attributes, the states it arrives in - so a witness compound that tests any of- /// those is reached from the fact. `:has(:not(.test))` and `:has(*)` test nothing an element can- /// publish, and a query like that is invisible to an arrival unless the arrival is asked.- pub witness_is_featureless: bool,- /// Whether the argument reaches a witness across a sibling relation of its own, past the axis it- /// starts on.- ///- /// `:has(#d:is(.p + .c ~ .d .e))` holds because of an adjacency two levels away from anything the- /// query names, and any element landing in that sequence breaks it while carrying nothing at all.- /// Such a query cannot be reached from the features of a tree change, so it is asked directly- /// whenever a child sequence moves. An argument whose own steps are all ancestral needs none of- /// that: an element arriving does not change what anything else is a descendant of.- pub argument_spans_siblings: bool,- /// See `RelativeQuery::match_in_shadow_tree`. The axis was walked from a shadow root, so walking- /// it back from a witness arrives at that root and the anchor is whatever hosts it.- pub match_in_shadow_tree: bool,-}--/// How to get from one semantic input in a selector entry to the subjects it can affect.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub struct TransposeRoute {- pub rule: RuleID,- pub entry: EntryID,- /// The structural operator for a structural route, or the locally evaluable origin compound for- /// an attribute route.- pub selector_node: Option<SelectorNodeID>,- /// Set when the input is a possible relational witness, in which case the path applies from an- /// anchor rather than from the changed node.- pub anchor: Option<RelativeAnchor>,-}--#[derive(Clone, Copy, PartialEq, Eq, Hash)]-struct RouteRange {- offset: u32,- length: u32,-}--#[derive(PartialEq, Eq)]-struct FlatRouteDirectoryData {- ranges: HashMap<RoutingKey, RouteRange>,- routes: Vec<RouteID>,-}--struct SharedFlatRouteDirectory {- data: FlatRouteDirectoryData,-}--fn share_flat_route_directory(- data: FlatRouteDirectoryData,- pool: &mut WeakPool<SharedFlatRouteDirectory>,-) -> Option<Arc<SharedFlatRouteDirectory>> {- if data.ranges.is_empty() {- debug_assert!(data.routes.is_empty());- return None;- }- let mut ranges_hash = 0_u64;- for (key, range) in &data.ranges {- let mut hasher = fast_hasher();- key.hash(&mut hasher);- range.hash(&mut hasher);- ranges_hash ^= hasher.finish();- }- let mut hasher = fast_hasher();- ranges_hash.hash(&mut hasher);- data.ranges.len().hash(&mut hasher);- data.routes.hash(&mut hasher);- let hash = hasher.finish();- if let Some(found) = pool.find(hash, |candidate| candidate.data == data) {- return Some(found);- }-- let shared = Arc::new(SharedFlatRouteDirectory { data });- pool.insert(hash, &shared);- Some(shared)-}--#[derive(Clone)]--enum RouteDirectory {- BuildingAfterIdle(HashMap<RoutingKey, Vec<RouteID>>),- BuildingAfterChange(HashMap<RoutingKey, Vec<RouteID>>),- BuildingIdleAfterChange(HashMap<RoutingKey, Vec<RouteID>>),- FlatAfterIdle {- data: Option<Arc<SharedFlatRouteDirectory>>,- },- FlatAfterChange {- data: Option<Arc<SharedFlatRouteDirectory>>,- },-}--impl Default for RouteDirectory {- fn default() -> Self {- Self::FlatAfterIdle { data: None }- }-}--impl RouteDirectory {- fn reopen(data: Option<Arc<SharedFlatRouteDirectory>>) -> HashMap<RoutingKey, Vec<RouteID>> {- let Some(data) = data else { return HashMap::default() };- let mut building = HashMap::with_capacity_and_hasher(data.data.ranges.len(), Default::default());- for (&key, range) in &data.data.ranges {- building.insert(- key,- data.data.routes[range.offset as usize..(range.offset + range.length) as usize].to_vec(),- );- }- building- }-- fn push(&mut self, key: RoutingKey, route: RouteID) {- match std::mem::take(self) {- Self::FlatAfterIdle { data } => {- *self = Self::BuildingAfterIdle(Self::reopen(data));- }- Self::FlatAfterChange { data } => {- *self = Self::BuildingAfterChange(Self::reopen(data));- }- Self::BuildingIdleAfterChange(building) => {- *self = Self::BuildingAfterChange(building);- }- state => *self = state,- }- let building = match self {- Self::BuildingAfterIdle(building)- | Self::BuildingAfterChange(building)- | Self::BuildingIdleAfterChange(building) => building,- Self::FlatAfterIdle { .. } | Self::FlatAfterChange { .. } => unreachable!(),- };- let routes = building.entry(key).or_default();- if routes.last() != Some(&route) {- routes.push(route);- }- }-- fn get(&self, key: RoutingKey) -> &[RouteID] {- match self {- Self::BuildingAfterIdle(building)- | Self::BuildingAfterChange(building)- | Self::BuildingIdleAfterChange(building) => building.get(&key).map_or(&[], Vec::as_slice),- Self::FlatAfterIdle { data } | Self::FlatAfterChange { data } => data.as_ref().map_or(&[], |data| {- data.data.ranges.get(&key).map_or(&[], |range| {- &data.data.routes[range.offset as usize..(range.offset + range.length) as usize]- })- }),- }- }-- #[cfg(test)]- fn len(&self) -> usize {- match self {- Self::BuildingAfterIdle(building)- | Self::BuildingAfterChange(building)- | Self::BuildingIdleAfterChange(building) => building.len(),- Self::FlatAfterIdle { data } | Self::FlatAfterChange { data } => {- data.as_ref().map_or(0, |data| data.data.ranges.len())- }- }- }-- fn is_empty(&self) -> bool {- match self {- Self::BuildingAfterIdle(building)- | Self::BuildingAfterChange(building)- | Self::BuildingIdleAfterChange(building) => building.is_empty(),- Self::FlatAfterIdle { data } | Self::FlatAfterChange { data } => data.is_none(),- }- }-- /// Whether this directory is the flat directory `other` is, which nothing has been pushed to since.- fn is_flat_copy_of(&self, other: &Self) -> bool {- let (- Self::FlatAfterIdle { data } | Self::FlatAfterChange { data },- Self::FlatAfterIdle { data: other } | Self::FlatAfterChange { data: other },- ) = (self, other)- else {- return false;- };- match (data, other) {- (None, None) => true,- (Some(data), Some(other)) => Arc::ptr_eq(data, other),- _ => false,- }- }-- fn finish(&mut self, pool: &mut WeakPool<SharedFlatRouteDirectory>) -> bool {- match std::mem::take(self) {- Self::FlatAfterIdle { data } | Self::FlatAfterChange { data } => {- *self = Self::FlatAfterIdle { data };- false- }- Self::BuildingAfterChange(building) => {- *self = Self::BuildingIdleAfterChange(building);- true- }- Self::BuildingAfterIdle(building) => {- *self = Self::flatten(building, true, pool);- true- }- Self::BuildingIdleAfterChange(building) => {- *self = Self::flatten(building, false, pool);- true- }- }- }-- /// Flatten the directory now, however recently it changed.- fn flatten_now(&mut self, pool: &mut WeakPool<SharedFlatRouteDirectory>) {- *self = match std::mem::take(self) {- Self::BuildingAfterIdle(building)- | Self::BuildingAfterChange(building)- | Self::BuildingIdleAfterChange(building) => Self::flatten(building, false, pool),- flat => flat,- };- }-- fn flatten(- building: HashMap<RoutingKey, Vec<RouteID>>,- after_change: bool,- pool: &mut WeakPool<SharedFlatRouteDirectory>,- ) -> Self {- let route_count = building.values().map(Vec::len).sum();- let mut ranges = HashMap::with_capacity_and_hasher(building.len(), Default::default());- let mut flat_routes = Vec::with_capacity(route_count);- for (key, routes) in building {- let offset = u32::try_from(flat_routes.len()).expect("routing directory space exhausted");- flat_routes.extend_from_slice(&routes);- ranges.insert(- key,- RouteRange {- offset,- length: u32::try_from(routes.len()).expect("routing directory space exhausted"),- },- );- }- let data = share_flat_route_directory(- FlatRouteDirectoryData {- ranges,- routes: flat_routes,- },- pool,- );- if after_change {- Self::FlatAfterChange { data }- } else {- Self::FlatAfterIdle { data }- }- }-}--#[derive(Clone, Default, PartialEq, Eq)]-struct RouteColumnData {- headers: Vec<RouteHeader>,- paths: SharedVector<RouteRange>,- origins: SharedVector<RouteRange>,- origin_requirements: SharedVector<RouteRange>,- parents: SharedVector<RouteRange>,- waypoints: SharedVector<RouteRange>,- anchors: Vec<RelativeAnchor>,- entry_facts: Vec<Option<EntryRouteFacts>>,- inverse_steps: Vec<InverseStep>,- keys: Vec<DispatchKey>,- /// Routes inside relational arguments, needed when departure removes their input facts.- relational: Vec<RouteID>,- /// Non-relational routes that can leave a departing subtree through a sibling step.- sibling_first: Vec<RouteID>,- canonical_route_heads: HashMap<(RuleID, EntryID), RouteID>,- canonical_next: Vec<Option<RouteID>>,-}--impl Hash for RouteColumnData {- fn hash<H: Hasher>(&self, state: &mut H) {- self.headers.hash(state);- self.paths.hash(state);- self.origins.hash(state);- self.origin_requirements.hash(state);- self.parents.hash(state);- self.waypoints.hash(state);- self.anchors.hash(state);- self.entry_facts.hash(state);- self.inverse_steps.hash(state);- self.keys.hash(state);- self.relational.hash(state);- self.sibling_first.hash(state);- self.canonical_next.hash(state);- // The canonical heads follow from the ordered headers. Equality still compares the map.- self.canonical_route_heads.len().hash(state);- }-}--// Route columns contain immutable selector descriptors and integer identities. Equal contents-// can be shared even when documents interpret the identities through different selector programs.-// A later stylesheet edit detaches the columns before appending routes.-#[derive(Clone)]-enum RouteColumns {- Owned(Box<RouteColumnData>),- Shared(Arc<SharedRouteColumns>),-}--impl Default for RouteColumns {- fn default() -> Self {- Self::Owned(Box::default())- }-}--impl std::ops::Deref for RouteColumns {- type Target = RouteColumnData;-- fn deref(&self) -> &Self::Target {- match self {- Self::Owned(data) => data,- Self::Shared(shared) => &shared.data,- }- }-}--struct SharedRouteColumns {- data: RouteColumnData,-}--/// The process's pools for routing registries, shared by every engine.-#[derive(Default)]-struct RoutingPools {- route_columns: WeakPool<SharedRouteColumns>,- route_ranges: SharedVectorPool<RouteRange>,- flat_route_directories: WeakPool<SharedFlatRouteDirectory>,- sibling_entry_maps: SharedVectorPool<u32>,-}--fn routing_pools() -> MutexGuard<'static, RoutingPools> {- // Shared like the selector program pools; see selector_program_pools().- static ROUTING_POOLS: OnceLock<Mutex<RoutingPools>> = OnceLock::new();- ROUTING_POOLS.get_or_init(Mutex::default).lock().unwrap()-}--impl RouteColumns {- fn make_mut(&mut self) -> &mut RouteColumnData {- if matches!(self, Self::Shared(_)) {- let Self::Shared(shared) = std::mem::take(self) else {- unreachable!()- };- let data = match Arc::try_unwrap(shared) {- Ok(mut shared) => std::mem::take(&mut shared.data),- Err(shared) => shared.data.clone(),- };- let Self::Owned(owned) = self else { unreachable!() };- **owned = data;- }- let Self::Owned(data) = self else { unreachable!() };- data- }-- fn push(&mut self, header: RouteHeader, ranges: RouteRanges) {- self.make_mut().push(header, ranges);- }-- fn share(&mut self, pools: &mut RoutingPools) {- if matches!(self, Self::Shared(_)) || self.is_empty() {- return;- }- let Self::Owned(mut data) = std::mem::take(self) else {- unreachable!()- };- let mut hasher = fast_hasher();- data.hash(&mut hasher);- let hash = hasher.finish();- let shared = match pools.route_columns.find(hash, |candidate| candidate.data == *data) {- Some(found) => found,- None => {- // Offsets and lengths can agree even when route keys or rule bindings differ.- // Share each immutable range column independently of the complete registry.- data.paths.share(&mut pools.route_ranges);- data.origins.share(&mut pools.route_ranges);- data.origin_requirements.share(&mut pools.route_ranges);- data.parents.share(&mut pools.route_ranges);- data.waypoints.share(&mut pools.route_ranges);-- let shared = Arc::new(SharedRouteColumns { data: *data });- pools.route_columns.insert(hash, &shared);- shared- }- };- *self = Self::Shared(shared);- }-}--const NO_ROUTE_INDEX: u32 = u32::MAX;--#[derive(Clone, Copy, PartialEq, Eq, Hash)]-struct RouteHeader {- rule: RuleID,- entry: EntryID,- selector_node: u32,- anchor_index: u32,-}--struct RouteRanges {- path: RouteRange,- origin: RouteRange,- origin_requirements: RouteRange,- parent: RouteRange,- waypoints: RouteRange,-}--impl RouteColumnData {- fn push(&mut self, header: RouteHeader, ranges: RouteRanges) {- self.headers.push(header);- self.paths.make_mut().push(ranges.path);- self.origins.make_mut().push(ranges.origin);- self.origin_requirements.make_mut().push(ranges.origin_requirements);- self.parents.make_mut().push(ranges.parent);- self.waypoints.make_mut().push(ranges.waypoints);- }-- fn len(&self) -> usize {- self.headers.len()- }-- fn is_empty(&self) -> bool {- self.headers.is_empty()- }-}--/// Subject-side facts shared by every transpose route of one selector entry.-#[derive(Clone, Copy, PartialEq, Eq, Hash)]-struct EntryRouteFacts {- /// Whether prefix matching applies, and whether its compounds read only local facts.- flags: u8,- /// The subject's bounded position in its sibling sequence, when it has one.- subject_position: SubjectPosition,- /// Distinguishing subject features used to enumerate candidates within a region.- subject_offset: u32,- subject_length: u32,- /// Independently necessary features of the subject compound.- subject_required_offset: u32,- subject_required_length: u32,-}--const ENTRY_HAS_PREFIX_CHAIN: u8 = 1 << 0;-const ENTRY_PREFIX_CHAIN_HAS_ONLY_LOCAL_FACTS: u8 = 1 << 1;--/// Stable identity of one canonical transpose route.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash, PartialOrd, Ord)]-pub struct RouteID(NonZeroU32);--impl RouteID {- fn from_index(index: usize) -> Self {- let one_based = u32::try_from(index)- .expect("transpose route space exhausted")- .checked_add(1)- .expect("transpose route space exhausted");- Self(NonZeroU32::new(one_based).unwrap())- }-- pub(super) fn index(self) -> usize {- (self.0.get() - 1) as usize- }-}--/// The identity of one live sibling-first route.-#[derive(Clone, Copy)]-pub(super) struct SiblingEntry {- pub(super) route: RouteID,-}--#[derive(Clone, Copy)]-pub(super) struct LiveRelationalRoute {- pub(super) route: RouteID,- pub(super) program: SelectorProgramID,- pub(super) anchor: RelativeAnchor,-}--/// The complete semantic identity of one transpose route.-///-/// All variable-length fields borrow the registry's canonical arenas or the compiler's temporary-/// slices. Looking up this value therefore allocates and copies nothing.-#[derive(Clone, Copy, PartialEq, Eq, Hash)]-struct RouteDescriptor<'a> {- rule: RuleID,- entry: EntryID,- selector_node: Option<SelectorNodeID>,- origin_dispatch: &'a [DispatchKey],- origin_required: &'a [DispatchKey],- parent_dispatch: &'a [DispatchKey],- waypoints: &'a [DispatchKey],- anchor: Option<RelativeAnchor>,- path: &'a [InverseStep],-}--impl<A: AtomSpace> SelectorProgram<A> {- /// Walk one entry and report every semantic input it mentions, with the inverse path from that- /// input to the entry's subjects.- ///- /// The path is produced in application order: walking down the IR collects the combinators- /// outermost first, and going back up applies them innermost first, so the collected steps are- /// reversed before being handed out.- pub fn collect_transpose_entry_points(&self, entry: usize, mut visit: impl FnMut(TransposeSite<'_>)) {- let root = self.entries()[entry].root;- let mut walk = TransposeWalk::default();- self.walk_transpose(root, root, None, &mut walk, &mut visit);- }-- fn walk_transpose(- &self,- id: SelectorNodeID,- enclosing: SelectorNodeID,- anchor: Option<(RelativeAnchor, usize)>,- walk: &mut TransposeWalk,- visit: &mut impl FnMut(TransposeSite<'_>),- ) {- let emit = |walk: &mut TransposeWalk, key: RoutingKey, visit: &mut dyn FnMut(TransposeSite<'_>)| {- walk.origin_dispatch.clear();- // NB: The hover bit changes at the origin. Use its other features to find possible origins even before- // anything is hovered, including alternatives inside :is() and :where().- if !self.dispatch_analysis_excluding(- enclosing,- DispatchRelation::Subject,- DispatchQuery::Alternatives,- &mut walk.origin_dispatch,- (key == RoutingKey::State(StateFact::Hover)).then_some(key),- ) {- walk.origin_dispatch.clear();- }- walk.origin_required.clear();- self.required_dispatch_keys_of(enclosing, &mut walk.origin_required);- if let [already_required] = walk.origin_dispatch.as_slice() {- walk.origin_required.retain(|key| key != already_required);- }- walk.origin_required.sort_unstable();- walk.origin_required.dedup();- walk.origin_required- .sort_unstable_by_key(|&key| dispatch_selectivity(key));- walk.origin_required.truncate(MAX_REQUIRED_DISPATCH_KEYS);- walk.parent_dispatch.clear();- self.dispatch_analysis(- enclosing,- DispatchRelation::Parent,- DispatchQuery::Alternatives,- &mut walk.parent_dispatch,- );- // Steps taken inside a relative argument lead from the anchor to a possible witness,- // not from the anchor to the entry's subjects. Only the steps already on the stack when- // the query was entered describe that, so the rest are dropped: keeping them would send- // `.red:has(#d:is(.a .b))` looking for its own subject among its descendants.- let depth = anchor.map_or(walk.path.len(), |(_, depth)| depth);- walk.applied_path.clear();- walk.applied_path.extend(walk.path[..depth].iter().rev().copied());- let anchor = anchor.map(|(anchor, depth)| {- let relative_path = &walk.path[depth..];- let input_is_on_the_anchor = matches!(- (anchor.axis, relative_path),- (RelativeAxis::Child, [InverseStep::Children])- );- RelativeAnchor {- input_is_on_the_witness: relative_path.is_empty(),- input_is_on_the_anchor,- ..anchor- }- });- // The waypoints were collected subject-first, like the path, and the last one is the- // subject's own compound rather than an intermediate. Reversed alongside the path, each- // one constrains the node the step of the same index lands on, and `Universal` means- // that compound constrains nothing.- walk.applied_waypoints.clear();- if depth == walk.path.len() {- walk.applied_waypoints.extend(- walk.waypoints[..depth]- .iter()- .rev()- .map(|key| key.unwrap_or(DispatchKey::Universal)),- );- }- visit(TransposeSite {- key,- node: id,- origin: enclosing,- path: &walk.applied_path,- anchor,- origin_dispatch: &walk.origin_dispatch,- origin_required: &walk.origin_required,- parent_dispatch: &walk.parent_dispatch,- waypoints: &walk.applied_waypoints,- });- };-- match self.node(id) {- SelectorOp::Feature(test) => {- let key = dispatch_key_for_feature(test);- if key != RoutingKey::Universal {- emit(walk, key, visit);- } else if anchor.is_some() {- // `*` names no fact, so as a subject it needs no key: the only thing that can- // change it is the element appearing or disappearing, which its own tree delta- // names. As the witness of a `:has()` it is not the element that moved - the- // anchor is somewhere above or beside it, and its answer flips the moment- // anything at all arrives. The shape of the tree is what moved, so that is what- // the query registers under, which is also the key the arrival is routed by.- emit(walk, RoutingKey::Structural, visit);- }- }- SelectorOp::State(fact) => emit(walk, RoutingKey::State(fact), visit),- SelectorOp::And { first, count } | SelectorOp::Or { first, count } => {- // A compound naming `:host` is reached at the shadow root and describes the host one- // crossing beyond it, so every other conjunct's facts sit on the host too and the way- // back to the subject has to cross into the tree exactly as `:host` itself does.- // Without it `:host:has(.x) .y` and `:host:hover .y` route from the host through its- // light-DOM descendants, which hold no subject of theirs, and reach nothing.- //- // An empty path means the subject is the host, so there is nothing to cross.- let crosses_to_the_host = matches!(self.node(id), SelectorOp::And { .. })- && !walk.path.is_empty()- && self- .operands(first, count)- .iter()- .any(|&operand| self.mentions_the_host(operand));- for index in 0..count {- let operand = self.operands(first, count)[index as usize];- // Operands of a compound share it: it is the constraint their subject carries.- // An alternative of a disjunction is not a compound of its own, and a relative- // query anchors on the compound the disjunction sits in. `a:has(> p, > div)` is- // one query per argument, and each one's anchor still has to be an `a`.- let operand_enclosing = match self.node(id) {- SelectorOp::Or { .. } if matches!(self.node(operand), SelectorOp::RelativeExists(_)) => {- enclosing- }- _ => id,- };- match crosses_to_the_host && !self.mentions_the_host(operand) {- // `:host` applies the step for its own operand already.- true => self.walk_step(operand, id, InverseStep::HostedTree, anchor, walk, visit),- false => self.walk_transpose(operand, operand_enclosing, anchor, walk, visit),- }- }- }- SelectorOp::Where(inner) | SelectorOp::Not(inner) => {- self.walk_transpose(inner, enclosing, anchor, walk, visit);- }- SelectorOp::Parent(inner) => self.walk_step(inner, enclosing, InverseStep::Children, anchor, walk, visit),- SelectorOp::Ancestor(inner) => {- self.walk_step(inner, enclosing, InverseStep::Descendants, anchor, walk, visit);- }- SelectorOp::PreviousSibling(inner) => {- self.walk_step(inner, enclosing, InverseStep::NextSibling, anchor, walk, visit);- }- SelectorOp::PrecedingSibling(inner) => {- self.walk_step(inner, enclosing, InverseStep::FollowingSiblings, anchor, walk, visit);- }- SelectorOp::NthPosition(position) => {- // The position itself depends on the child sequence, not on any local fact.- emit(walk, RoutingKey::Structural, visit);- if let Some(selector) = position.of_selector {- self.walk_step(selector, enclosing, InverseStep::SiblingSequence, anchor, walk, visit);- }- }- // A change to a possible witness does not fold into the path. Folding it would compose- // "the ancestors of the changed node" with whatever the outer selector adds, and that- // composition degenerates: ancestors-then-descendants is the document. The anchor step- // is recorded separately so routing can resolve the anchors first and continue the- // remaining path from each one that can actually flip.- SelectorOp::RelativeExists(query) => {- let compiled = self.relative_query(query);- let anchor = RelativeAnchor {- axis: compiled.axis,- query,- witness_dispatch: self.dispatch_key_of(compiled.compound),- input_is_on_the_witness: true,- input_is_on_the_anchor: false,- // The anchor has to satisfy the compound the `:has()` sits in, which is what- // separates the handful of real anchors from every ancestor of the witness.- anchor_dispatch: self.dispatch_key_of(enclosing),- adjacent_reach: self.adjacent_reach(compiled.compound),- witness_is_featureless: !self.tests_a_published_fact(compiled.compound),- // A witness under a sibling reaches its anchor through a sibling step inside the- // compound, which is the axis itself and not a step of the argument's own.- argument_spans_siblings: self.count_sibling_steps(compiled.compound)- > usize::from(matches!(- compiled.axis,- RelativeAxis::NextSiblingSubtree | RelativeAxis::FollowingSiblingSubtree- )),- match_in_shadow_tree: compiled.match_in_shadow_tree,- };- self.walk_transpose(- compiled.compound,- compiled.compound,- Some((anchor, walk.path.len())),- walk,- visit,- );- }- // `:host()` is a guard on the host, not a combinator: the match program tests the- // same node it was reached on. Which node that is depends on where the guard sits. In- // `:host(.x)` the subject is the host itself, so a change to `.x` reaches the host and- // no step applies. In `:host(.x) .y` a combinator has already been taken, and the- // subject is inside the shadow tree, which a DOM-ancestry step cannot reach - so the- // step to the hosted tree is what carries it there.- SelectorOp::Host(inner) => {- if walk.path.is_empty() {- self.walk_transpose(inner, enclosing, anchor, walk, visit);- } else {- self.walk_step(inner, enclosing, InverseStep::HostedTree, anchor, walk, visit);- }- }- // `::slotted()` likewise tests the assigned element itself, which is the subject.- // A change on the slot reaches the elements assigned to it, which is the same relation- // `::slotted()` steps through.- SelectorOp::AssignedSlot(inner) => {- self.walk_step(inner, enclosing, InverseStep::SlotAssignees, anchor, walk, visit);- }- SelectorOp::Slotted(inner) => {- if walk.path.is_empty() {- self.walk_transpose(inner, enclosing, anchor, walk, visit);- } else {- self.walk_step(inner, enclosing, InverseStep::SlotAssignment, anchor, walk, visit);- }- }- SelectorOp::Part(part) => emit(walk, RoutingKey::Part(part), visit),- // A change on the host reaches the elements exposing parts inside the trees it hosts.- // `exportparts` forwards a name outwards, so the element the rule names can sit any- // number of shadow roots below the host rather than in the one tree it hosts directly,- // and the step has to pierce them all.- //- // The names are walked without a step: they are facts about the subject itself, and a- // change to one reaches the rule from the element that publishes it.- SelectorOp::ExposedToHost { host, parts } => {- self.walk_step(host, enclosing, InverseStep::HostedTrees, anchor, walk, visit);- self.walk_transpose(parts, enclosing, anchor, walk, visit);- }- // A change on the element backing a pseudo-element reaches the host it stands for it on,- // whose match carries the pseudo-element's rules.- SelectorOp::BackingElement { inner, .. } => {- self.walk_step(inner, enclosing, InverseStep::ShadowHost, anchor, walk, visit);- }- // Root, emptiness, scope membership and the place of a named element all change with- // the shape of the tree.- SelectorOp::Root- | SelectorOp::Empty- | SelectorOp::Scope- | SelectorOp::IsNode(_)- | SelectorOp::ScopeRootInstance => {- emit(walk, RoutingKey::Structural, visit);- }- // Which element is the anchor is not a fact anything publishes, and the relation the- // chain steps through is not one an input moves: a mutation that reshapes it is a tree- // delta, which routing sees through the relations it records rather than through a key.- // The compounds of the chain carry the keys the query is reachable by.- SelectorOp::RelativeAnchorInstance => {}- SelectorOp::ValueState { kind, value } => {- emit(- walk,- match kind.routing_kind() {- ValueStateKind::Directionality => RoutingKey::Directionality(value),- ValueStateKind::CustomState => RoutingKey::CustomState(value),- },- visit,- );- }- // The subject is reached through what the rule writes inside the scope, so that is the- // path. An element becoming or ceasing to be a scoping root moves the scope of- // everything below it, and an element becoming a scoping limit takes itself and- // everything under it out - so both are walked through a descendant step, and the limit- // as a subject as well, since it leaves the scope itself.- SelectorOp::InScope { root, limit, inner, .. } => {- self.walk_transpose(inner, enclosing, anchor, walk, visit);- // The subject can be the root itself as well as below it, so an element becoming or- // ceasing to be one reaches itself and its descendants.- self.walk_transpose(root, enclosing, anchor, walk, visit);- self.walk_step(root, enclosing, InverseStep::Descendants, anchor, walk, visit);- if let Some(limit) = limit {- self.walk_transpose(limit, enclosing, anchor, walk, visit);- self.walk_step(limit, enclosing, InverseStep::Descendants, anchor, walk, visit);- }- }- // A range is not a name, so every `:lang()` registers under one key and a resolved- // language moving reaches all of them.- SelectorOp::Language { .. } => emit(walk, RoutingKey::Language, visit),- SelectorOp::Heading(_) => emit(walk, RoutingKey::Structural, visit),- }- }-- fn walk_step(- &self,- inner: SelectorNodeID,- enclosing: SelectorNodeID,- step: InverseStep,- anchor: Option<(RelativeAnchor, usize)>,- walk: &mut TransposeWalk,- visit: &mut impl FnMut(TransposeSite<'_>),- ) {- // The compound being stepped away from is what a subject reached through this step had to- // satisfy at this point of the selector. A compound whose set is not a single key describes- // no requirement that a subject's ancestor walk can check one lookup at a time.- walk.origin_dispatch.clear();- let waypoint =- match self.dispatch_keys_of(enclosing, &mut walk.origin_dispatch) && walk.origin_dispatch.len() == 1 {- true => Some(walk.origin_dispatch[0]),- false => None,- };- walk.path.push(step);- walk.waypoints.push(waypoint);- self.walk_transpose(inner, inner, anchor, walk, visit);- walk.waypoints.pop();- walk.path.pop();- }-}--/// The stack a transpose walk carries: the inverse steps taken from the input so far and, for each-/// one, the single distinguishing key of the compound it stepped away from.-#[derive(Default)]-struct TransposeWalk {- path: Vec<InverseStep>,- waypoints: Vec<Option<DispatchKey>>,- applied_path: Vec<InverseStep>,- applied_waypoints: Vec<DispatchKey>,- origin_dispatch: Vec<DispatchKey>,- origin_required: Vec<DispatchKey>,- parent_dispatch: Vec<DispatchKey>,-}--/// One semantic input a selector entry mentions, with everything routing needs to transpose it.-pub struct TransposeSite<'a> {- pub key: RoutingKey,- /// The IR node the input occurs at.- pub node: SelectorNodeID,- /// The compound whose truth controls whether the input can reach this route.- pub origin: SelectorNodeID,- /// The inverse path from the input to the entry's subjects.- pub path: &'a [InverseStep],- /// Set when the input is a possible relational witness.- pub anchor: Option<RelativeAnchor>,- /// The distinguishing features of the compound the input occurs in.- pub origin_dispatch: &'a [DispatchKey],- /// Independently necessary features of the compound containing the input.- pub origin_required: &'a [DispatchKey],- /// What the selector says the parent of the compound the input occurs in must be.- pub parent_dispatch: &'a [DispatchKey],- /// One key per intermediate compound of a purely ancestral path, in origin-to-subject order.- pub waypoints: &'a [DispatchKey],-}--/// Whether an element publishes this state as it connects.-///-/// A state that arrives with the element reaches whatever rests on it through the publication, so a-/// `:has()` witness testing one needs nothing from the tree delta. A state that is only published-/// when it later moves cannot be reached that way: the element was already in it when it arrived and-/// nothing said so, which is why an arrival has to be asked about those directly.-///-/// This mirrors what `record_element_initial_features` says on the C++ side. A state missing from-/// there and listed here would be silently unreachable on arrival; the safe direction is to leave a-/// state out of this list, which costs the question and answers it.-#[must_use]-fn state_is_published_on_arrival(fact: StateFact) -> bool {- matches!(- fact,- StateFact::AnyLink- | StateFact::Checked- | StateFact::Defined- | StateFact::Disabled- | StateFact::Enabled- | StateFact::Focus- | StateFact::FocusVisible- | StateFact::FocusWithin- | StateFact::Invalid- | StateFact::Link- | StateFact::LocalLink- | StateFact::Optional- | StateFact::Required- | StateFact::Unchecked- | StateFact::UserInvalid- | StateFact::UserValid- | StateFact::Valid- | StateFact::Visited- )-}--/// Maps each semantic input key to the canonical transpose routes that mention it.-///-/// This is required program state, not an optional view. Scanning every selector header for every-/// ordinary mutation would change the hot path's asymptotics, so routing has to be an index.-/// Feature postings may accelerate subject enumeration on top of it, but a missing posting never-/// changes which routes run.-const LIVENESS_LOCK: &str = "the routing liveness view is never held across a panic";--#[derive(Clone)]--pub struct RoutingRegistry {- routes: RouteColumns,- /// Sibling-first routes indexed by a distinguishing feature of their left compound.- sibling_first_by_origin: HashMap<DispatchKey, Vec<RouteID>>,- by_input: RouteDirectory,- arrival_by_input: RouteDirectory,- /// The liveness view, rebuilt by `prepare_route_liveness` whenever the program's routing- /// liveness version moves and read-only after that. Plain fields, not cells: the registry is- /// on the read side an evaluation step borrows, which has to be `Sync`.- route_liveness: BitColumn,- live_relational_routes: Vec<LiveRelationalRoute>,- live_sibling_entries: Vec<SiblingEntry>,- live_sequence_entries: Vec<SequenceEntry>,- /// The two members of the view a routing pass mutates as it runs. Each is taken once per- /// pass, never per route, so the lock is a formality that makes the registry shareable.- live_sibling_workspace: crate::fork::ForkLocked<SiblingCandidateWorkspace>,- live_sequence_index: crate::fork::ForkLocked<SequenceEntryIndex>,- /// The live routes whose rules may move layout geometry, part of the liveness view.- geometry_routes: BitColumn,- route_liveness_version: Option<u64>,-}--impl Default for RoutingRegistry {- fn default() -> Self {- Self {- routes: RouteColumns::default(),- sibling_first_by_origin: HashMap::default(),- by_input: RouteDirectory::default(),- arrival_by_input: RouteDirectory::default(),- route_liveness: BitColumn::default(),- live_relational_routes: Vec::new(),- live_sibling_entries: Vec::new(),- live_sequence_entries: Vec::new(),- live_sibling_workspace: crate::fork::ForkLocked::new(SiblingCandidateWorkspace::new(- &[],- &mut routing_pools().sibling_entry_maps,- )),- live_sequence_index: crate::fork::ForkLocked::new(SequenceEntryIndex::default()),- geometry_routes: BitColumn::default(),- route_liveness_version: None,- }- }-}--impl RoutingRegistry {- #[must_use]- pub fn new() -> Self {- Self::default()- }-- fn insert(&mut self, key: RoutingKey, descriptor: RouteDescriptor<'_>) -> RouteID {- let starts_through_a_sibling = descriptor.anchor.is_none()- && matches!(- descriptor.path.first(),- Some(InverseStep::NextSibling | InverseStep::FollowingSiblings)- );- let canonical_key = (descriptor.rule, descriptor.entry);- let mut candidate = self.routes.canonical_route_heads.get(&canonical_key).copied();- let mut canonical_route = None;- while let Some(route) = candidate {- if self.route_descriptor(route) == descriptor {- canonical_route = Some(route);- break;- }- candidate = self.routes.canonical_next[route.index()];- }- let RouteDescriptor {- rule,- entry,- selector_node,- origin_dispatch,- origin_required,- parent_dispatch,- waypoints,- anchor,- path,- } = descriptor;- let route = canonical_route.unwrap_or_else(|| {- let route = RouteID::from_index(self.routes.len());- let path_offset = u32::try_from(self.routes.inverse_steps.len()).expect("transpose path space exhausted");- self.routes.make_mut().inverse_steps.extend_from_slice(path);- let origin_offset = u32::try_from(self.routes.keys.len()).expect("dispatch key space exhausted");- self.routes.make_mut().keys.extend_from_slice(origin_dispatch);- let origin_required_offset = u32::try_from(self.routes.keys.len()).expect("dispatch key space exhausted");- self.routes.make_mut().keys.extend_from_slice(origin_required);- let parent_offset = u32::try_from(self.routes.keys.len()).expect("dispatch key space exhausted");- self.routes.make_mut().keys.extend_from_slice(parent_dispatch);- let waypoint_offset = u32::try_from(self.routes.keys.len()).expect("dispatch key space exhausted");- self.routes.make_mut().keys.extend_from_slice(waypoints);- let anchor_index = anchor.map(|anchor| {- let index = u32::try_from(self.routes.anchors.len()).expect("relative anchor space exhausted");- assert_ne!(index, NO_ROUTE_INDEX, "relative anchor space exhausted");- self.routes.make_mut().anchors.push(anchor);- index- });- let selector_node = selector_node.map_or(NO_ROUTE_INDEX, |node| {- assert_ne!(node.0, NO_ROUTE_INDEX, "selector node space exhausted");- node.0- });- self.routes.push(- RouteHeader {- rule,- entry,- selector_node,- anchor_index: anchor_index.unwrap_or(NO_ROUTE_INDEX),- },- RouteRanges {- path: RouteRange {- offset: path_offset,- length: u32::try_from(path.len()).expect("transpose path space exhausted"),- },- origin: RouteRange {- offset: origin_offset,- length: u32::try_from(origin_dispatch.len()).expect("dispatch key space exhausted"),- },- origin_requirements: RouteRange {- offset: origin_required_offset,- length: u32::try_from(origin_required.len()).expect("dispatch key space exhausted"),- },- parent: RouteRange {- offset: parent_offset,- length: u32::try_from(parent_dispatch.len()).expect("dispatch key space exhausted"),- },- waypoints: RouteRange {- offset: waypoint_offset,- length: u32::try_from(waypoints.len()).expect("dispatch key space exhausted"),- },- },- );- self.route_liveness_version = None;- if anchor.is_some() {- self.routes.make_mut().relational.push(route);- }- if starts_through_a_sibling {- self.routes.make_mut().sibling_first.push(route);- if origin_dispatch.is_empty() {- let routes = self.sibling_first_by_origin.entry(DispatchKey::Universal).or_default();- routes.push(route);- } else {- for &origin in origin_dispatch {- let routes = self.sibling_first_by_origin.entry(origin).or_default();- routes.push(route);- }- }- }- let previous = self- .routes- .make_mut()- .canonical_route_heads- .insert(canonical_key, route);- self.routes.make_mut().canonical_next.push(previous);- route- });-- if anchor.is_some() || starts_through_a_sibling {- self.arrival_by_input.push(key, route);- }- self.by_input.push(key, route);- route- }-- fn route_descriptor(&self, route: RouteID) -> RouteDescriptor<'_> {- let point = self.route(route);- RouteDescriptor {- rule: point.rule,- entry: point.entry,- selector_node: point.selector_node,- origin_dispatch: self.origin_dispatch_of(route),- origin_required: self.origin_required_of(route),- parent_dispatch: self.parent_dispatch_of(route),- waypoints: self.waypoints_of(route),- anchor: point.anchor,- path: self.path_of(route),- }- }-- /// Every route inside a relational argument, in a stable order.- #[must_use]- pub fn relational_routes(&self) -> &[RouteID] {- &self.routes.relational- }-- /// Every route whose path steps to a sibling first, in a stable order.- #[must_use]- pub fn sibling_first_routes(&self) -> &[RouteID] {- &self.routes.sibling_first- }-- /// Sibling-first routes whose left compound can match a node carrying `origin`.- #[must_use]- pub fn sibling_first_routes_for_origin(&self, origin: DispatchKey) -> &[RouteID] {- self.sibling_first_by_origin.get(&origin).map_or(&[], Vec::as_slice)- }-- /// Routes reached from one semantic input, in a stable order.- #[must_use]- pub fn routes_for(&self, key: RoutingKey) -> &[RouteID] {- self.by_input.get(key)- }-- /// Routes for which an arriving element's facts can affect nodes outside its subtree.- #[must_use]- pub fn arrival_routes_for(&self, key: RoutingKey) -> &[RouteID] {- self.arrival_by_input.get(key)- }-- #[must_use]- pub fn route(&self, route: RouteID) -> TransposeRoute {- let index = route.index();- let header = self.routes.headers[index];- TransposeRoute {- rule: header.rule,- entry: header.entry,- selector_node: (header.selector_node != NO_ROUTE_INDEX).then_some(SelectorNodeID(header.selector_node)),- anchor: (header.anchor_index != NO_ROUTE_INDEX).then(|| self.routes.anchors[header.anchor_index as usize]),- }- }-- #[must_use]- pub fn rule_of(&self, route: RouteID) -> RuleID {- self.routes.headers[route.index()].rule- }-- #[must_use]- pub fn entry_of(&self, route: RouteID) -> EntryID {- self.routes.headers[route.index()].entry- }-- pub(super) fn route_is_live(- &self,- route: RouteID,- program: &StyleSheetProgram,- programs: &SelectorPrograms,- ) -> bool {- // The view the last transaction prepared answers until the program's routing liveness moves.- if self.route_liveness_version == Some(program.routing_liveness_version()) {- return self.route_liveness.contains(route.index());- }- let header = self.routes.headers[route.index()];- let (selector_program, _) = programs.entry_location(header.entry);- program.rule_can_decide(header.rule)- && program.rule_version(header.rule).selector_program == Some(selector_program)- }-- /// Whether a live route `key` reaches belongs to a rule a match of which may move layout geometry. The view the- /// last transaction prepared answers until the program's routing liveness moves; after that each route is looked up.- pub(super) fn key_may_affect_layout_geometry(- &self,- key: RoutingKey,- program: &StyleSheetProgram,- programs: &SelectorPrograms,- ) -> bool {- let routes = self.routes_for(key);- if self.route_liveness_version == Some(program.routing_liveness_version()) {- return routes.iter().any(|route| self.geometry_routes.contains(route.index()));- }- routes.iter().copied().any(|route| {- self.route_is_live(route, program, programs) && program.rule_may_affect_layout_geometry(self.rule_of(route))- })- }-- /// Rebuild the liveness view when the program's routing liveness version moves.- ///- /// This takes `&mut self` so the view itself needs no interior mutability: the registry is on- /// the read side, and a walk reads it without being able to rebuild it.- pub(super) fn prepare_route_liveness(&mut self, program: &StyleSheetProgram, programs: &SelectorPrograms) {- let version = program.routing_liveness_version();- if self.route_liveness_version == Some(version) {- return;- }- let mut liveness = std::mem::take(&mut self.route_liveness);- let mut geometry_routes = std::mem::take(&mut self.geometry_routes);- for index in 0..self.routes.headers.len() {- let header = self.routes.headers[index];- let (selector_program, _) = programs.entry_location(header.entry);- let live = program.rule_can_decide(header.rule)- && program.rule_version(header.rule).selector_program == Some(selector_program);- liveness.set(index, live);- geometry_routes.set(index, live && program.rule_may_affect_layout_geometry(header.rule));- }- let mut live_relational_routes = std::mem::take(&mut self.live_relational_routes);- live_relational_routes.clear();- live_relational_routes.extend(self.routes.relational.iter().copied().filter_map(|route| {- if !liveness.contains(route.index()) {- return None;- }- let point = self.route(route);- let (program, _) = programs.entry_location(point.entry);- Some(LiveRelationalRoute {- route,- program,- anchor: point.anchor.expect("a relational route must carry an anchor"),- })- }));- let mut live_sibling_entries = std::mem::take(&mut self.live_sibling_entries);- live_sibling_entries.clear();- live_sibling_entries.extend(- self.routes- .sibling_first- .iter()- .copied()- .filter(|route| liveness.contains(route.index()))- .map(|route| SiblingEntry { route }),- );- let sibling_workspace =- SiblingCandidateWorkspace::new(&live_sibling_entries, &mut routing_pools().sibling_entry_maps);- let mut live_sequence_entries = std::mem::take(&mut self.live_sequence_entries);- live_sequence_entries.clear();- for &route in self.routes_for(RoutingKey::Structural) {- if !liveness.contains(route.index()) {- continue;- }- let point = self.route(route);- let (program, entry) = programs.entry_location(point.entry);- let compiled = programs.get(program);- let selector_entry = compiled.entries()[entry as usize];- let operator = compiled.node(point.selector_node.expect("structural route has no operator"));- if !matches!(operator, SelectorOp::Empty | SelectorOp::NthPosition(_)) {- continue;- }- live_sequence_entries.push(SequenceEntry {- route,- operator,- can_compare_exactly: selector_entry.can_use_before_sibling_relations()- && selector_entry.observes_sibling_relation(),- });- }- let sequence_index = SequenceEntryIndex::build(&live_sequence_entries, self);- self.route_liveness = liveness;- self.geometry_routes = geometry_routes;- self.live_relational_routes = live_relational_routes;- self.live_sibling_entries = live_sibling_entries;- self.live_sequence_entries = live_sequence_entries;- *self.live_sibling_workspace.get_mut().expect(LIVENESS_LOCK) = sibling_workspace;- *self.live_sequence_index.get_mut().expect(LIVENESS_LOCK) = sequence_index;- self.route_liveness_version = Some(version);- }-- #[must_use]- pub(super) fn route_liveness(&self, program: &StyleSheetProgram) -> &BitColumn {- debug_assert_eq!(self.route_liveness_version, Some(program.routing_liveness_version()));- &self.route_liveness- }-- #[must_use]- pub(super) fn live_relational_routes(&self, program: &StyleSheetProgram) -> &[LiveRelationalRoute] {- debug_assert_eq!(self.route_liveness_version, Some(program.routing_liveness_version()));- &self.live_relational_routes- }-- #[must_use]- pub(super) fn live_sibling_entries(&self, program: &StyleSheetProgram) -> &[SiblingEntry] {- debug_assert_eq!(self.route_liveness_version, Some(program.routing_liveness_version()));- &self.live_sibling_entries- }-- pub(super) fn live_sibling_workspace(- &self,- program: &StyleSheetProgram,- ) -> MutexGuard<'_, SiblingCandidateWorkspace> {- debug_assert_eq!(self.route_liveness_version, Some(program.routing_liveness_version()));- self.live_sibling_workspace.lock().expect(LIVENESS_LOCK)- }-- #[must_use]- pub(super) fn live_sequence_entries(&self, program: &StyleSheetProgram) -> &[SequenceEntry] {- debug_assert_eq!(self.route_liveness_version, Some(program.routing_liveness_version()));- &self.live_sequence_entries- }-- pub(super) fn live_sequence_index(&self, program: &StyleSheetProgram) -> MutexGuard<'_, SequenceEntryIndex> {- debug_assert_eq!(self.route_liveness_version, Some(program.routing_liveness_version()));- self.live_sequence_index.lock().expect(LIVENESS_LOCK)- }-- fn entry_facts_of(&self, route: RouteID) -> EntryRouteFacts {- self.routes.entry_facts[self.routes.headers[route.index()].entry.0 as usize]- .expect("a route must reference registered entry facts")- }-- #[must_use]- pub fn entry_has_prefix_chain(&self, route: RouteID) -> bool {- self.entry_facts_of(route).flags & ENTRY_HAS_PREFIX_CHAIN != 0- }-- #[must_use]- pub fn entry_prefix_chain_has_only_local_facts(&self, route: RouteID) -> bool {- self.entry_facts_of(route).flags & ENTRY_PREFIX_CHAIN_HAS_ONLY_LOCAL_FACTS != 0- }-- #[must_use]- pub fn path_of(&self, route: RouteID) -> &[InverseStep] {- let range = self.routes.paths[route.index()];- &self.routes.inverse_steps[range.offset as usize..(range.offset + range.length) as usize]- }-- /// The features the element an input happened to must carry for this route to be reachable.- ///- /// Hovering a paragraph cannot change anything through `.action:hover *`, because the- /// paragraph is not an `.action`. Rejecting it here costs one posting lookup instead of a- /// subtree walk. Empty means the compound distinguishes nothing and rejects nothing.- #[must_use]- pub fn origin_dispatch_of(&self, route: RouteID) -> &[DispatchKey] {- let range = self.routes.origins[route.index()];- &self.routes.keys[range.offset as usize..(range.offset + range.length) as usize]- }-- /// Independently necessary features of the compound containing the input.- #[must_use]- pub fn origin_required_of(&self, route: RouteID) -> &[DispatchKey] {- let range = self.routes.origin_requirements[route.index()];- &self.routes.keys[range.offset as usize..(range.offset + range.length) as usize]- }-- /// What the parent of the compound an input occurs in must be.- ///- /// A positional test names a place in one child sequence, so- /// `#list > .row:first-child .leaf` is rejected for every sequence whose parent is not the- /// list, however far the subject is from the test. Empty means it rejects nothing.- #[must_use]- pub fn parent_dispatch_of(&self, route: RouteID) -> &[DispatchKey] {- let range = self.routes.parents[route.index()];- &self.routes.keys[range.offset as usize..(range.offset + range.length) as usize]- }-- /// How far into a sibling sequence the entry's subjects can be, when a positional test says so.- ///- /// `:first-child` names one element however long the sequence is, including when its compound- /// has no feature by which to enumerate it.- #[must_use]- pub fn subject_position_of(&self, route: RouteID) -> SubjectPosition {- self.entry_facts_of(route).subject_position- }-- /// The features the entry's subjects carry, which is what a region is narrowed to.- ///- /// `.guard:hover .target` reaches a whole subtree through its combinator, but only `.target`- /// elements can change. Empty means the subjects have no feature by which to enumerate them.- #[must_use]- pub fn subject_dispatch_of(&self, route: RouteID) -> &[DispatchKey] {- let facts = self.entry_facts_of(route);- &self.routes.keys[facts.subject_offset as usize..(facts.subject_offset + facts.subject_length) as usize]- }-- /// Independently necessary features of the entry's subject compound.- #[must_use]- pub fn subject_required_of(&self, route: RouteID) -> &[DispatchKey] {- let facts = self.entry_facts_of(route);- &self.routes.keys[facts.subject_required_offset as usize- ..(facts.subject_required_offset + facts.subject_required_length) as usize]- }-- /// Keys some ancestor of a subject must carry for this route to reach it.- ///- /// `[data-active] [class] span` reaches every `span` below the changed element, but only one- /// with a `[class]` ancestor can match. These necessary keys reject the rest without changing- /// the answer. Empty means a non-ancestral step or indistinct compound prevents that proof.- #[must_use]- pub fn waypoints_of(&self, route: RouteID) -> &[DispatchKey] {- let range = self.routes.waypoints[route.index()];- &self.routes.keys[range.offset as usize..(range.offset + range.length) as usize]- }-- #[must_use]- #[cfg(test)]- pub fn len(&self) -> usize {- self.routes.len()- }-- #[must_use]- #[cfg(test)]- pub fn routed_input_count(&self) -> usize {- self.by_input.len()- }-- pub(super) fn finish_directories(&mut self) -> bool {- let mut pools = routing_pools();- let changed = self.by_input.finish(&mut pools.flat_route_directories)- | self.arrival_by_input.finish(&mut pools.flat_route_directories);- self.routes.share(&mut pools);- changed- }-- /// Flatten the directories and share the route columns now, for a registry other engines take copies of.- pub(super) fn finish_for_sharing(&mut self) {- let mut pools = routing_pools();- self.by_input.flatten_now(&mut pools.flat_route_directories);- self.arrival_by_input.flatten_now(&mut pools.flat_route_directories);- self.routes.share(&mut pools);- }-- /// Whether no rule has been routed.- pub(super) fn is_empty(&self) -> bool {- self.routes.is_empty() && self.by_input.is_empty() && self.arrival_by_input.is_empty()- }-- /// Whether this registry holds the finished routes of `other` and has routed nothing since: every route either- /// joins the route columns or is pushed to a directory, and either one stops sharing it.- pub(super) fn is_finished_copy_of(&self, other: &Self) -> bool {- matches!(- (&self.routes, &other.routes),- (RouteColumns::Shared(routes), RouteColumns::Shared(other)) if Arc::ptr_eq(routes, other)- ) && self.by_input.is_flat_copy_of(&other.by_input)- && self.arrival_by_input.is_flat_copy_of(&other.arrival_by_input)- }-- /// A copy of the routes for another engine, whose liveness view is prepared again before it is read: the view- /// was prepared for this engine's program, whose liveness version the other's may share.- pub(super) fn copy_for_another_engine(&self) -> Self {- Self {- route_liveness_version: None,- ..self.clone()- }- }-- /// Whether this registry routes what `other` routes, to the same routes.- #[cfg(test)]- pub(super) fn has_routes_of(&self, other: &Self) -> bool {- fn directory(directory: &RouteDirectory) -> HashMap<RoutingKey, Vec<RouteID>> {- match directory {- RouteDirectory::BuildingAfterIdle(building)- | RouteDirectory::BuildingAfterChange(building)- | RouteDirectory::BuildingIdleAfterChange(building) => building.clone(),- RouteDirectory::FlatAfterIdle { data } | RouteDirectory::FlatAfterChange { data } => {- RouteDirectory::reopen(data.clone())- }- }- }- *self.routes == *other.routes- && self.sibling_first_by_origin == other.sibling_first_by_origin- && directory(&self.by_input) == directory(&other.by_input)- && directory(&self.arrival_by_input) == directory(&other.arrival_by_input)- }-- #[cfg(test)]- fn directories_are_flat(&self) -> bool {- matches!(- self.by_input,- RouteDirectory::FlatAfterIdle { .. } | RouteDirectory::FlatAfterChange { .. }- ) && matches!(- self.arrival_by_input,- RouteDirectory::FlatAfterIdle { .. } | RouteDirectory::FlatAfterChange { .. }- )- }-- fn register_entry_facts(- &mut self,- entry: EntryID,- selector_entry: SelectorEntry,- subject_dispatch: &[DispatchKey],- subject_required: &[DispatchKey],- subject_position: SubjectPosition,- ) {- let index = entry.0 as usize;- if self.routes.entry_facts.len() <= index {- self.routes.make_mut().entry_facts.resize(index + 1, None);- }- let mut flags = 0;- if selector_entry.has_prefix_chain() {- flags |= ENTRY_HAS_PREFIX_CHAIN;- }- if selector_entry.prefix_chain_has_only_local_facts() {- flags |= ENTRY_PREFIX_CHAIN_HAS_ONLY_LOCAL_FACTS;- }- if let Some(facts) = self.routes.entry_facts[index] {- debug_assert_eq!(facts.flags, flags);- debug_assert_eq!(facts.subject_position, subject_position);- debug_assert_eq!(- &self.routes.keys- [facts.subject_offset as usize..(facts.subject_offset + facts.subject_length) as usize],- subject_dispatch- );- debug_assert_eq!(- &self.routes.keys[facts.subject_required_offset as usize- ..(facts.subject_required_offset + facts.subject_required_length) as usize],- subject_required- );- return;- }- let subject_offset = u32::try_from(self.routes.keys.len()).expect("dispatch key space exhausted");- self.routes.make_mut().keys.extend_from_slice(subject_dispatch);- let subject_required_offset = u32::try_from(self.routes.keys.len()).expect("dispatch key space exhausted");- self.routes.make_mut().keys.extend_from_slice(subject_required);- self.routes.make_mut().entry_facts[index] = Some(EntryRouteFacts {- flags,- subject_position,- subject_offset,- subject_length: u32::try_from(subject_dispatch.len()).expect("dispatch key space exhausted"),- subject_required_offset,- subject_required_length: u32::try_from(subject_required.len()).expect("dispatch key space exhausted"),- });- }-- /// Add every transpose route of one attached rule.- pub fn add_rule(&mut self, rule: RuleID, program: SelectorProgramID, programs: &SelectorPrograms) {- let compiled = programs.get(program);- for entry in 0..compiled.entries().len() {- let entry_id = programs.entry_id(program, u32::try_from(entry).expect("selector entry space exhausted"));- let selector_entry = compiled.entries()[entry];- let subject_dispatch = compiled.subject_dispatch_keys(entry);- let subject_required = compiled.subject_required_keys(entry);- let subject_position = compiled.subject_position(entry);- let mut entry_registered = false;- programs.for_each_transpose_entry_point(program, entry, rule, |site| {- if !entry_registered {- self.register_entry_facts(- entry_id,- selector_entry,- subject_dispatch,- subject_required,- subject_position,- );- entry_registered = true;- }- self.insert(- site.key,- RouteDescriptor {- rule,- entry: entry_id,- selector_node: match compiled.node(site.node) {- SelectorOp::Feature(FeatureTest::Attribute(attribute))- if attribute.operator == AttributeOperator::Presence- || (attribute.operator == AttributeOperator::Exact- && attribute.case == AttributeCase::Sensitive- && !attribute.value_atom.is_none()) =>- {- Some(site.node)- }- SelectorOp::Feature(FeatureTest::Attribute(_)) => Some(site.origin),- _ if site.key == RoutingKey::Structural => Some(site.node),- _ => None,- },- origin_dispatch: site.origin_dispatch,- origin_required: site.origin_required,- parent_dispatch: site.parent_dispatch,- waypoints: site.waypoints,- anchor: site.anchor,- path: site.path,- },- );- });- }- }-}--/// Why a match evaluation could not produce an exact answer.-#[derive(Clone, Copy, Debug, PartialEq, Eq, Hash)]-#[expect(clippy::enum_variant_names, reason = "each variant names the facts that are missing")]-pub enum Incomplete {- /// The fact batch does not cover a style node the evaluation had to read. This is never a- /// negative answer: the caller widens the batch or asks a different question.- MissingFacts(StyleNodeID),- /// A descendant scan reached a row the fact batch does not cover. Every node from `first`- /// through the remainder of `root`'s preorder is the range the scan can still read.- MissingDescendantFacts { root: StyleNodeID, first: StyleNodeID },- /// A sibling scan reached a row the fact batch does not cover. Every node from `first` up to,- /// but not including, `last_exclusive` is the remaining range that scan can read.- MissingSiblingFacts {- first: StyleNodeID,- last_exclusive: Option<StyleNodeID>,- },-}--impl Incomplete {- #[must_use]- pub fn first_missing_node(self) -> StyleNodeID {- match self {- Self::MissingFacts(node) => node,- Self::MissingDescendantFacts { first, .. } => first,- Self::MissingSiblingFacts { first, .. } => first,- }- }-}--impl TransactionFactView {- pub(super) fn insert_before_sibling_sequence(&mut self, parent: StyleNodeID, children: Vec<StyleNodeID>) {- let (sequence, _, _) = self.before_sibling_geometry.insert_sequence(children);- debug_assert_eq!(sequence as usize, self.before_sibling_parents_by_sequence.len());- self.before_sibling_sequence_by_parent.push((parent, sequence));- self.before_sibling_parents_by_sequence.push(parent);- }-- pub(super) fn mark_before_absent(&mut self, node: StyleNodeID) {- self.before_absent_nodes.push(node);- }-- pub(super) fn finish_before_sibling_relations(&mut self) {- self.before_sibling_sequence_by_parent- .sort_unstable_by_key(|&(parent, _)| parent);- debug_assert!(- self.before_sibling_sequence_by_parent- .windows(2)- .all(|entries| entries[0].0 != entries[1].0)- );- self.before_absent_nodes.sort_unstable();- self.before_absent_nodes.dedup();- self.before_sibling_relations_available = true;- }-- pub(super) fn is_present(&self, tree: &StyleNodeTree, side: TransactionFactSide, node: StyleNodeID) -> bool {- match side {- TransactionFactSide::Before => {- debug_assert!(self.before_sibling_relations_available);- self.before_absent_nodes.binary_search(&node).is_err()- }- TransactionFactSide::After => tree.is_live(node),- }- }-- fn parent_of(&self, tree: &StyleNodeTree, side: TransactionFactSide, node: StyleNodeID) -> Option<StyleNodeID> {- if matches!(side, TransactionFactSide::After) {- return tree.parent(node);- }- debug_assert!(self.before_sibling_relations_available);- if !self.is_present(tree, side, node) {- return None;- }- // A captured membership names the parent the node started under, which the live tree- // cannot: a node that moved between parents is live under its new one.- self.before_sibling_geometry- .memberships- .get(node.element_index()? as usize)- .and_then(|membership| {- self.before_sibling_parents_by_sequence- .get(membership.sequence as usize)- .copied()- })- .or_else(|| tree.parent(node))- }-- fn previous_sibling_of(- &self,- tree: &StyleNodeTree,- side: TransactionFactSide,- node: StyleNodeID,- ) -> Option<StyleNodeID> {- if matches!(side, TransactionFactSide::After) {- return tree.previous_element_sibling(node);- }- self.parent_of(tree, side, node)?;- let Some((sequence, ordinal)) = self.before_sibling_geometry.sequence_and_ordinal(node) else {- return tree.previous_element_sibling(node);- };- ordinal.checked_sub(1).map(|previous| sequence[previous as usize])- }-- fn next_sibling_of(- &self,- tree: &StyleNodeTree,- side: TransactionFactSide,- node: StyleNodeID,- ) -> Option<StyleNodeID> {- if matches!(side, TransactionFactSide::After) {- return tree.next_element_sibling(node);- }- self.parent_of(tree, side, node)?;- let Some((sequence, ordinal)) = self.before_sibling_geometry.sequence_and_ordinal(node) else {- return tree.next_element_sibling(node);- };- sequence.get(ordinal as usize + 1).copied()- }-- fn children_of<'a>(- &'a self,- tree: &'a StyleNodeTree,- side: TransactionFactSide,- parent: StyleNodeID,- ) -> SiblingChildren<'a> {- if matches!(side, TransactionFactSide::After) {- return SiblingChildren::Live(tree.children(parent));- }- debug_assert!(self.before_sibling_relations_available);- if !self.is_present(tree, side, parent) {- return SiblingChildren::Overlay([].iter().copied());- }- match self- .before_sibling_sequence_by_parent- .binary_search_by_key(&parent, |&(candidate, _)| candidate)- {- Ok(index) => {- let sequence = self.before_sibling_sequence_by_parent[index].1;- SiblingChildren::Overlay(- self.before_sibling_geometry.sequences[sequence as usize]- .iter()- .copied(),- )- }- Err(_) => SiblingChildren::Live(tree.children(parent)),- }- }-- fn sibling_positions(&self, side: TransactionFactSide, node: StyleNodeID) -> Option<SiblingPositions> {- match side {- TransactionFactSide::Before => self.before_sibling_geometry.sibling_positions(node),- TransactionFactSide::After => None,- }- }-- fn sibling_sequence(&self, side: TransactionFactSide, node: StyleNodeID) -> Option<&[StyleNodeID]> {- match side {- TransactionFactSide::Before => self.before_sibling_geometry.sibling_sequence(node),- TransactionFactSide::After => None,- }- }-}--enum SiblingChildren<'a> {- Live(super::tree::Children<'a>),- Overlay(std::iter::Copied<std::slice::Iter<'a, StyleNodeID>>),-}--impl Iterator for SiblingChildren<'_> {- type Item = StyleNodeID;-- fn next(&mut self) -> Option<Self::Item> {- match self {- Self::Live(children) => children.next(),- Self::Overlay(children) => children.next(),- }- }-}--/// Evaluates match programs against the live tree and a batch of local facts.-#[derive(Clone, Copy)]-pub(crate) struct MatchFactRow<'a> {- pub(super) facts: &'a StyleNodeFacts,- pub(super) row: u32,-}--impl<'a> ElementFeatures for MatchFactRow<'a> {- type Attribute = (&'a StyleNodeFacts, super::index::AttributeFact);-- #[inline]- fn local_name_is(&self, name: StyleAtomID) -> bool {- self.facts.tag_of(self.row) == name- }-- #[inline]- fn namespace_is(&self, namespace: StyleAtomID) -> bool {- self.facts.namespace_of(self.row) == namespace- }-- #[inline]- fn has_id(&self, id: StyleAtomID) -> bool {- self.facts.id_of(self.row) == id- }-- #[inline]- fn has_class(&self, class: StyleAtomID) -> bool {- self.facts.classes_of(self.row).contains(&class)- }-- /// `[*|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 = (&'a StyleNodeFacts, super::index::AttributeFact)> + '_ {- let facts = self.facts;- facts- .attributes_of(self.row)- .iter()- .filter(move |attribute| match any_namespace {- false => attribute.name == name,- true => facts.attribute_name_forms(attribute.name).local == name,- })- .map(move |&attribute| (facts, attribute))- }-}--/// Which positional tests an evaluator answers from its workspace's shared sibling index.-#[derive(Clone, Copy, Debug, PartialEq, Eq)]-pub(super) enum PositionalIndexPolicy {- /// Every test, and every answer is memoized. A traversal that styles whole sequences asks- /// many programs about the same children, which amortizes building each index.- All,- /// Only tests with a step, which have to count the whole sequence anyway, and no memo. A- /// bounded test such as `:first-child` stops at its near end, so a narrow exact ask over- /// scattered candidates answers it more cheaply than materializing every sequence it walks- /// through - and asks the same test about the same node too rarely for a memo to pay for- /// its insertion.- SteppedOnly,-}--/// The style engine's elements, as a selector program is evaluated against them: its tree, its fact-/// rows, and the workspace its accelerations keep their answers in.-pub struct EngineSubject<'a> {- tree: &'a StyleNodeTree,- facts: &'a StyleNodeFacts,- transaction_fact_view: Option<(&'a TransactionFactView, 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, MatchEvaluationSide)>,- positional_index_policy: PositionalIndexPolicy,- transitive_relation_program: Option<SelectorProgramID>,- /// Where a completed simple relational evaluation records its outcome, when the caller is- /// evaluating the live tree and current facts. See `MatchEvaluator::observing_witnesses`.- witnesses: Option<&'a mut Vec<WitnessEffect>>,-}--/// Evaluates match programs against the style engine's tree and a batch of local facts.-pub(crate) type MatchEvaluator<'a> = SelectorEvaluator<EngineSubject<'a>>;--/// Transaction-local answers for repeated match-program relations.-///-/// Exact invalidation evaluates the same selector entry over a region. In tree order, an ancestor-/// or preceding-sibling relation differs from the preceding candidate by one edge, so retaining-/// that answer turns repeated prefix walks into a dynamic program.-#[derive(Clone, Default)]-struct MatchRelationCache {- answers: MatchRelationAnswers,- preceding_sibling_parent_ids: HashMap<StyleNodeID, PrecedingSiblingParentID>,- preceding_sibling_prefixes: PrecedingSiblingPrefixes,-}--#[derive(Clone, Default)]-struct MatchRelationAnswers {- columns: ProgramRelationColumns<RelationAnswerColumn>,-}--#[derive(Clone, Copy, Debug, PartialEq, Eq)]-struct MatchRelationAnswerGap {- program: SelectorProgramID,- relation: SelectorNodeID,- node: StyleNodeID,-}--/// Prefix progress indexed by dense program, relation, and transaction-local parent identities.-///-/// Only a small subset of document parents normally owns a sibling sequence under evaluation.-/// Intern those parents once at the cache boundary, then keep every compiled relation's repeatedly-/// updated prefix state in a direct column rather than repeating the three identities in a hash key.-#[derive(Clone, Default)]-struct PrecedingSiblingPrefixes {- columns: ProgramRelationColumns<PrecedingSiblingPrefixColumn>,-}--define_id! { pub(crate) struct PrecedingSiblingParentID(); }--type PrecedingSiblingPrefix = super::selector_evaluation::PrecedingSiblingPrefix<StyleNodeID>;--#[derive(Clone)]--struct ProgramRelationColumns<C> {- programs: Column<Option<Box<ProgramColumns<C>>>>,-}--impl<C> Default for ProgramRelationColumns<C> {- fn default() -> Self {- Self {- programs: Column::default(),- }- }-}--#[derive(Clone, Default)]-struct ProgramColumns<C> {- relations: Column<Option<C>>,-}--impl<C: Default> ProgramRelationColumns<C> {- fn get(&self, program: SelectorProgramID, relation: SelectorNodeID) -> Option<&C> {- self.programs- .get(program.0 as usize)?- .as_ref()?- .relations- .get(relation.0 as usize)?- .as_ref()- }-- fn column_mut(&mut self, program: SelectorProgramID, relation: SelectorNodeID) -> (&mut C, bool) {- let program_index = program.0 as usize;- self.programs.ensure(program_index);- let program_columns = self.programs[program_index].get_or_insert_with(Box::default);- let relation_index = relation.0 as usize;- program_columns.relations.ensure(relation_index);- let column_was_absent = program_columns.relations[relation_index].is_none();- (- program_columns.relations[relation_index].get_or_insert_with(C::default),- column_was_absent,- )- }-}--const RELATION_ANSWER_PAGE_SHIFT: usize = 9;-const RELATION_ANSWER_PAGE_BITS: usize = 1 << RELATION_ANSWER_PAGE_SHIFT;-const RELATION_ANSWER_PAGE_WORDS: usize = RELATION_ANSWER_PAGE_BITS / u64::BITS as usize;--/// A sparse two-bit answer column for one compiled transitive relation.-///-/// Element identities are dense, so a page needs only a known bit and an answer bit per identity.-/// Program and relation identities index directly into the outer tables instead of being repeated-/// in every answer.-type RelationAnswerColumn = PagedColumn<RelationAnswerPage>;--#[derive(Clone, Default)]-struct RelationAnswerPage {- known: [u64; RELATION_ANSWER_PAGE_WORDS],- answers: [u64; RELATION_ANSWER_PAGE_WORDS],-}--impl PagedColumnPage for RelationAnswerPage {- type Value = bool;-- const SHIFT: usize = RELATION_ANSWER_PAGE_SHIFT;-- fn get(&self, index: usize) -> Option<bool> {- let word = index / u64::BITS as usize;- let mask = 1 << (index % u64::BITS as usize);- if self.known[word] & mask == 0 {- None- } else {- Some(self.answers[word] & mask != 0)- }- }-- fn insert(&mut self, index: usize, answer: bool) {- let word = index / u64::BITS as usize;- let mask = 1 << (index % u64::BITS as usize);- self.known[word] |= mask;- match answer {- true => self.answers[word] |= mask,- false => self.answers[word] &= !mask,- }- }-}--impl MatchRelationAnswers {- fn lookup(- &self,- program: SelectorProgramID,- relation: SelectorNodeID,- node: StyleNodeID,- ) -> Lookup<(), MatchRelationAnswerGap> {- let gap = MatchRelationAnswerGap {- program,- relation,- node,- };- let Some(column) = self.columns.get(program, relation) else {- return Lookup::Missing(gap);- };- match column.get(node.element_index().unwrap() as usize) {- Some(true) => Lookup::Known(()),- Some(false) => Lookup::KnownAbsent,- None => Lookup::Missing(gap),- }- }-- /// Publish one answer and report whether this created a relation column and a node page.- fn insert(- &mut self,- program: SelectorProgramID,- relation: SelectorNodeID,- node: StyleNodeID,- answer: bool,- ) -> (bool, bool) {- let (column, column_was_absent) = self.columns.column_mut(program, relation);- let page_was_absent = column.insert(node.element_index().unwrap() as usize, answer).1;- (column_was_absent, page_was_absent)- }-}--impl PrecedingSiblingPrefixes {- fn get(- &self,- program: SelectorProgramID,- relation: SelectorNodeID,- parent: PrecedingSiblingParentID,- ) -> Option<PrecedingSiblingPrefix> {- self.columns.get(program, relation)?.get(parent.0 as usize)- }-- fn insert(- &mut self,- program: SelectorProgramID,- relation: SelectorNodeID,- parent: PrecedingSiblingParentID,- prefix: PrecedingSiblingPrefix,- ) {- let (column, _) = self.columns.column_mut(program, relation);- column.insert(parent.0 as usize, prefix);- }-}--#[derive(Clone, Copy, Debug, Default, PartialEq, Eq, Hash)]-pub(super) struct SiblingPositions {- pub(super) from_start: u32,- pub(super) from_end: u32,-}--#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]-struct SiblingSequenceMembership {- sequence: u32,- ordinal: u32,-}--const VALUE_PAGE_SHIFT: usize = 6;-const VALUE_PAGE_SIZE: usize = 1 << VALUE_PAGE_SHIFT;--#[derive(Clone)]--struct ValuePage<T: Copy + Default> {- known: u64,- values: [T; VALUE_PAGE_SIZE],-}--impl<T: Copy + Default> Default for ValuePage<T> {- fn default() -> Self {- Self {- known: 0,- values: [T::default(); VALUE_PAGE_SIZE],- }- }-}--impl<T: Copy + Default> PagedColumnPage for ValuePage<T> {- type Value = T;-- const SHIFT: usize = 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;- }-}--type PrecedingSiblingPrefixColumn = PagedColumn<ValuePage<PrecedingSiblingPrefix>>;-type SiblingPositionColumn = PagedColumn<ValuePage<SiblingPositions>>;-type SiblingSequenceMembershipColumn = PagedColumn<ValuePage<SiblingSequenceMembership>>;--#[derive(Clone, Default)]-pub(super) struct SiblingSequenceGeometry {- sequences: Vec<Arc<[StyleNodeID]>>,- memberships: SiblingSequenceMembershipColumn,- /// Bytes held by the sequences themselves, kept running so `capacity_bytes` is O(1) on the- /// per-candidate before-and-after accounting path.- sequence_bytes: usize,-}--impl SiblingSequenceGeometry {- fn insert_sequence(&mut self, children: Vec<StyleNodeID>) -> (u32, Arc<[StyleNodeID]>, usize) {- u32::try_from(children.len()).expect("sibling sequence space exhausted");- let children: Arc<[StyleNodeID]> = children.into();- let sequence = u32::try_from(self.sequences.len()).expect("sibling sequence index space exhausted");- self.sequence_bytes += children.len() * size_of::<StyleNodeID>() + 2 * size_of::<usize>();- self.sequences.push(children.clone());- let mut pages = 0;- for (ordinal, &child) in children.iter().enumerate() {- pages += usize::from(- self.memberships- .insert(- child- .element_index()- .expect("only elements belong to sibling sequences") as usize,- SiblingSequenceMembership {- sequence,- ordinal: u32::try_from(ordinal).expect("sibling sequence space exhausted"),- },- )- .1,- );- }- (sequence, children, pages)- }-- fn sequence_and_ordinal(&self, node: StyleNodeID) -> Option<(&Arc<[StyleNodeID]>, u32)> {- let membership = self.memberships.get(node.element_index()? as usize)?;- Some((&self.sequences[membership.sequence as usize], membership.ordinal))- }-- fn sibling_sequence(&self, node: StyleNodeID) -> Option<&[StyleNodeID]> {- self.sequence_and_ordinal(node).map(|(sequence, _)| sequence.as_ref())- }-- pub(super) fn sibling_positions(&self, node: StyleNodeID) -> Option<SiblingPositions> {- let (sequence, ordinal) = self.sequence_and_ordinal(node)?;- let count = u32::try_from(sequence.len()).expect("sibling sequence space exhausted");- Some(SiblingPositions {- from_start: ordinal + 1,- from_end: count - ordinal,- })- }-}--/// The semantic side of a match-program evaluation.-#[derive(Clone, Copy)]-#[repr(usize)]-pub(super) enum MatchEvaluationSide {- Current = 0,- OldTree = 1,- OldFacts = 2,-}--impl MatchEvaluationSide {- fn tree_side(self) -> usize {- usize::from(matches!(self, Self::OldTree))- }-}--/// Caller-owned scratch lent exclusively to one match-program evaluator at a time.-///-/// Exact comparison has three semantic sides, but only two tree geometries. Current matching and-/// old-fact matching share the current sequence positions; the old-tree side has its own. Type-/// positions and selector answers additionally depend on the fact side and therefore remain-/// distinct.-#[derive(Clone, Default)]-pub struct MatchScratch {- relations_by_evaluation_side: [MatchRelationCache; 3],- sibling_geometry_by_tree_side: [SiblingSequenceGeometry; 2],- type_positions_by_evaluation_side: [SiblingPositionColumn; 3],- /// Canonical plain an+b answers shared across independently compiled selector programs.- positional_answers_by_evaluation_side: [PositionalAnswers; 3],-}--#[derive(Clone, Default)]-struct PositionalAnswers {- by_test: Vec<(NthPosition, HashMap<StyleNodeID, bool>)>,-}--impl PositionalAnswers {- fn get(&self, position: NthPosition, node: StyleNodeID) -> Option<bool> {- self.by_test- .iter()- .find(|(candidate, _)| *candidate == position)?- .1- .get(&node)- .copied()- }-- fn insert(&mut self, position: NthPosition, node: StyleNodeID, answer: bool) {- match self.by_test.iter_mut().find(|(candidate, _)| *candidate == position) {- Some((_, answers)) => {- answers.insert(node, answer);- }- None => {- let answers = HashMap::from_iter([(node, answer)]);- self.by_test.push((position, answers));- }- }- }-}--impl MatchRelationCache {- /// Discard selector-specific answers before a following matching traversal.- ///- /// Exact planning asks a narrow set of selector entries, while matching asks every candidate- /// entry for each element being styled. Carrying the planner's sparse selector-answer maps into- /// that much wider probe set makes almost every lookup a miss and displaces useful matching- /// state.- fn clear_selector_answers(&mut self) {- self.answers = MatchRelationAnswers::default();- self.preceding_sibling_prefixes = PrecedingSiblingPrefixes::default();- }-- fn lookup(- &self,- program: SelectorProgramID,- relation: SelectorNodeID,- node: StyleNodeID,- ) -> Lookup<(), MatchRelationAnswerGap> {- self.answers.lookup(program, relation, node)- }-- fn insert(&mut self, program: SelectorProgramID, relation: SelectorNodeID, node: StyleNodeID, answer: bool) {- self.answers.insert(program, relation, node, answer);- }-- fn preceding_sibling_prefix(- &mut self,- program: SelectorProgramID,- relation: SelectorNodeID,- parent: StyleNodeID,- ) -> (PrecedingSiblingParentID, Option<PrecedingSiblingPrefix>) {- let parent = {- let parent_ids = &mut self.preceding_sibling_parent_ids;- let next_id = parent_ids.len();- *parent_ids.entry(parent).or_insert_with(|| {- PrecedingSiblingParentID(u32::try_from(next_id).expect("preceding sibling parent space exhausted"))- })- };- (parent, self.preceding_sibling_prefixes.get(program, relation, parent))- }-- fn insert_preceding_sibling_prefix(- &mut self,- program: SelectorProgramID,- relation: SelectorNodeID,- parent: PrecedingSiblingParentID,- prefix: PrecedingSiblingPrefix,- ) {- self.preceding_sibling_prefixes- .insert(program, relation, parent, prefix);- }-}--impl MatchScratch {- /// Keep only reusable current-tree, current-fact data for the following matching traversal.- pub(super) fn retain_current_for_matching(&mut self) {- self.relations_by_evaluation_side[MatchEvaluationSide::Current as usize].clear_selector_answers();- self.clear_old_evaluation_sides();- }-- /// Old-side answers describe one transaction's before state, so they must not survive into- /// the next transaction, whose before state is a different topology.- pub(super) fn clear_old_evaluation_sides(&mut self) {- self.relations_by_evaluation_side[MatchEvaluationSide::OldTree as usize] = MatchRelationCache::default();- self.relations_by_evaluation_side[MatchEvaluationSide::OldFacts as usize] = MatchRelationCache::default();- self.sibling_geometry_by_tree_side[MatchEvaluationSide::OldTree.tree_side()] =- SiblingSequenceGeometry::default();- self.type_positions_by_evaluation_side[MatchEvaluationSide::OldTree as usize] =- SiblingPositionColumn::default();- self.type_positions_by_evaluation_side[MatchEvaluationSide::OldFacts as usize] =- SiblingPositionColumn::default();- self.positional_answers_by_evaluation_side[MatchEvaluationSide::OldTree as usize] =- PositionalAnswers::default();- self.positional_answers_by_evaluation_side[MatchEvaluationSide::OldFacts as usize] =- PositionalAnswers::default();- }-- fn relations(&self, side: MatchEvaluationSide) -> &MatchRelationCache {- &self.relations_by_evaluation_side[side as usize]- }-- pub(super) fn sibling_position(- &self,- node: StyleNodeID,- side: MatchEvaluationSide,- of_type: bool,- ) -> Option<SiblingPositions> {- match of_type {- true => self.type_positions_by_evaluation_side[side as usize].get(node.element_index()? as usize),- false => self.sibling_geometry_by_tree_side[side.tree_side()].sibling_positions(node),- }- }-- fn positional_answer(&self, position: NthPosition, node: StyleNodeID, side: MatchEvaluationSide) -> Option<bool> {- self.positional_answers_by_evaluation_side[side as usize].get(position, node)- }-- fn insert_positional_answer(- &mut self,- position: NthPosition,- node: StyleNodeID,- side: MatchEvaluationSide,- answer: bool,- ) {- self.positional_answers_by_evaluation_side[side as usize].insert(position, node, answer);- }-- fn sibling_sequence(&self, node: StyleNodeID, side: MatchEvaluationSide) -> Option<&[StyleNodeID]> {- self.sibling_geometry_by_tree_side[side.tree_side()].sibling_sequence(node)- }-- /// Publish one tree-side sibling sequence and return its shared child range, allocated pages,- /// and whether the sequence was new.- pub(super) fn publish_sibling_sequence(- &mut self,- children: Vec<StyleNodeID>,- side: MatchEvaluationSide,- ) -> (Arc<[StyleNodeID]>, usize, bool) {- if let Some(&first) = children.first()- && let Some((sequence, _)) =- self.sibling_geometry_by_tree_side[side.tree_side()].sequence_and_ordinal(first)- {- return (sequence.clone(), 0, false);- }-- let (_, children, pages) = self.sibling_geometry_by_tree_side[side.tree_side()].insert_sequence(children);- (children, pages, true)- }-}--impl<'a> MatchEvaluator<'a> {- #[must_use]- pub fn new(tree: &'a StyleNodeTree, facts: &'a StyleNodeFacts) -> Self {- SelectorEvaluator {- subject: EngineSubject {- tree,- facts,- transaction_fact_view: None,- part_exposure_scope: None,- match_workspace: None,- positional_index_policy: PositionalIndexPolicy::All,- transitive_relation_program: None,- witnesses: None,- },- bindings: SelectorBindings::default(),- }- }-- /// The same, evaluating rules attached to one shadow tree rather than to the document.- #[must_use]- pub fn in_shadow_tree(mut self, shadow_root: StyleNodeID) -> Self {- self.bindings.scope_shadow_root = Some(shadow_root);- self- }-- /// Evaluate a part through the tree scope it is exposed to.- #[must_use]- pub fn for_a_part_exposed_in(mut self, scope: TreeScopeID) -> Self {- self.subject.part_exposure_scope = Some(scope);- self- }-- #[must_use]- #[cfg(test)]- pub fn with_scope_root(mut self, scope_root: StyleNodeID) -> Self {- self.bindings.scope_root_instance = Some(scope_root);- self- }-- #[must_use]- pub(super) fn with_transaction_fact_view(- mut self,- view: &'a TransactionFactView,- side: TransactionFactSide,- ) -> Self {- self.subject.transaction_fact_view = Some((view, side));- self- }-- #[must_use]- pub(super) fn with_match_workspace(mut self, workspace: &'a mut MatchScratch, side: MatchEvaluationSide) -> Self {- self.subject.match_workspace = Some((workspace, side));- self- }-- /// Answer only stepped positional tests from the workspace's sibling index, and memoize no- /// positional answer. See [`PositionalIndexPolicy::SteppedOnly`].- #[must_use]- pub(super) fn indexing_stepped_positions_only(mut self) -> Self {- self.subject.positional_index_policy = PositionalIndexPolicy::SteppedOnly;- self- }-- /// Return completed simple relational evaluations through an owned effect buffer.- ///- /// Only an evaluator reading the live tree and the current facts may observe: retention's- /// soundness rests on every entry having been written by an evaluation whose answer is the- /// current truth, so an evaluator with a before-side transaction view or workspace must never- /// call this.- #[must_use]- pub(super) fn observing_witnesses(mut self, witnesses: &'a mut Vec<WitnessEffect>) -> Self {- debug_assert!(self.subject.transaction_fact_view.is_none());- debug_assert!(- self.subject- .match_workspace- .as_ref()- .is_none_or(|(_, side)| matches!(side, MatchEvaluationSide::Current))- );- self.subject.witnesses = Some(witnesses);- self- }-- /// How far the subject is from the scoping root its `@scope` resolved through.- ///- /// The specification creates one scope per element matching `<scope-start>`, and a declaration- /// from the nearest one wins, so this is the hop count to the nearest inclusive ancestor the- /// root selector names. A rule with no `@scope` is infinitely far, which is what makes an- /// unscoped declaration lose the proximity comparison to every scoped one.- pub fn scope_proximity_of(- &mut self,- program: &SelectorProgram,- entry: &SelectorEntry,- node: StyleNodeID,- counters: &Counters,- ) -> Result<u32, Incomplete> {- let Some(scope_root) = entry.scope_root else {- return Ok(u32::MAX);- };- let mut proximity = 0;- let mut candidate = Some(node);- while let Some(current) = candidate {- if self.matches_node(program, scope_root, current, counters)? {- return Ok(proximity);- }- proximity += 1;- candidate = self.subject.tree.parent(current);- }- Ok(u32::MAX)- }-- /// Whether `node` matches any entry of `program`, and which entry contributes the greatest- /// specificity among those that do.- ///- /// Short-circuiting is only allowed where it cannot hide a later entry with a greater cascade- /// contribution, so every entry is evaluated rather than stopping at the first match.- #[cfg(test)]- pub fn match_entries(- &mut self,- program: &SelectorProgram,- node: StyleNodeID,- counters: &Counters,- ) -> Result<Option<SelectorEntry>, Incomplete> {- let mut best: Option<SelectorEntry> = None;- for entry in program.entries() {- if self.matches_node(program, entry.root, node, counters)? {- let better = best.is_none_or(|current| entry.specificity > current.specificity);- if better {- best = Some(*entry);- }- }- }- Ok(best)- }-- /// Whether `node` matches one entry.- #[inline]- pub fn matches_entry(- &mut self,- program: &SelectorProgram,- entry: &SelectorEntry,- node: StyleNodeID,- counters: &Counters,- ) -> Result<bool, Incomplete> {- self.matches_node(program, entry.root, node, counters)- }-- /// Whether `node` matches one entry after its dispatch posting already proved `known`.- ///- /// Dispatch selects a subject-local feature from the entry root. Do not ask the fact store for- /// that same feature again while materializing the posting's exact selector incidence.- pub(super) fn matches_entry_after_dispatch(- &mut self,- program: &SelectorProgram,- entry: &SelectorEntry,- known: DispatchKey,- node: StyleNodeID,- counters: &Counters,- ) -> Result<bool, Incomplete> {- let is_known_operand = |operand| {- matches!(program.node(operand), SelectorOp::Feature(_) | SelectorOp::State(_))- && program.dispatch_key_of(operand) == known- };- if is_known_operand(entry.root) {- return Ok(true);- }- let SelectorOp::And { first, count } = program.node(entry.root) else {- return self.matches_node(program, entry.root, node, counters);- };- let mut skipped = false;- for &operand in program.operands(first, count) {- if !skipped && is_known_operand(operand) {- skipped = true;- continue;- }- if !self.matches_node(program, operand, node, counters)? {- return Ok(false);- }- }- Ok(true)- }-- /// Whether `node` matches one entry, reusing transitive relation answers from other nodes- /// evaluated against the same selector program.- #[inline]- pub fn matches_entry_for_program(- &mut self,- program_id: SelectorProgramID,- program: &SelectorProgram,- entry: &SelectorEntry,- node: StyleNodeID,- counters: &Counters,- ) -> Result<bool, Incomplete> {- let previous = self.subject.transitive_relation_program.replace(program_id);- let result = self.matches_node(program, entry.root, node, counters);- self.subject.transitive_relation_program = previous;- result- }-- /// Match the local half of one top-down selector-prefix step.- pub(super) fn matches_prefix_local(- &mut self,- program_id: SelectorProgramID,- program: &SelectorProgram,- local: SelectorPrefixLocal,- node: StyleNodeID,- counters: &Counters,- ) -> Result<bool, Incomplete> {- let previous = self.subject.transitive_relation_program.replace(program_id);- let result = match program.node(local.root) {- SelectorOp::And { first, count } => (|| {- for &operand in program.operands(first, count) {- if Some(operand) == local.relation {- continue;- }- if !self.matches_node(program, operand, node, counters)? {- return Ok(false);- }- }- Ok(true)- })(),- _ => self.matches_node(program, local.root, node, counters),- };- self.subject.transitive_relation_program = previous;- result- }-- /// Whether `node` is known not to carry `key`.- ///- /// A node the fact store has no row for is a shadow root, which publishes nothing and answers- /// no question about what it carries. That is not a rejection: a candidate filter that read it- /// as one would abandon the whole document over `.wrap > .child` inside any shadow tree.- #[inline]- #[must_use]- pub fn node_cannot_carry_dispatch_key(&self, key: DispatchKey, node: StyleNodeID) -> bool {- self.subject.row_of(node).is_ok_and(|row| {- !row.facts- .carries_dispatch_key(row.row, key, self.subject.tree.parent(node).is_none())- })- }-- #[inline]- pub(super) fn indexed_sibling_position(- &mut self,- position: NthPosition,- node: StyleNodeID,- ) -> Result<Option<i64>, Incomplete> {- self.subject.indexed_sibling_position(position, node)- }-- #[inline]- pub(super) fn row_of(&self, node: StyleNodeID) -> Result<MatchFactRow<'a>, Incomplete> {- self.subject.row_of(node)- }-- #[inline]- pub(super) fn serves_only_resident_rows(&self) -> bool {- self.subject.serves_only_resident_rows()- }-}--impl<'a> EngineSubject<'a> {- #[inline]- fn parent_of(&self, node: StyleNodeID) -> Option<StyleNodeID> {- self.tree().parent(node)- }-- #[inline]- fn children_of(&self, parent: StyleNodeID) -> SiblingChildren<'a> {- self.tree().children(parent)- }- /// Return a sibling position from private scratch, building that sequence on its first ask.- ///- /// A broad matching or exact-planning batch asks many positional selectors about the same- /// children. Counting from an end for every `(selector, child)` pair is quadratic in the- /// sequence length and repeated across rules. Child positions depend only on tree relations;- /// of-type positions additionally depend on the fact side, so old and new evaluations use- /// separate caches.- pub(super) fn indexed_sibling_position(- &mut self,- position: NthPosition,- node: StyleNodeID,- ) -> Result<Option<i64>, Incomplete> {- let Some((_, side)) = self.match_workspace.as_ref() else {- return Ok(None);- };- let side = *side;- if !position.of_type- && let Some(cached) = self- .transaction_fact_view- .and_then(|(view, side)| view.sibling_positions(side, node))- {- return Ok(Some(i64::from(match position.from_end {- true => cached.from_end,- false => cached.from_start,- })));- }- if let Some(cached) = self- .match_workspace- .as_ref()- .unwrap()- .0- .sibling_position(node, side, position.of_type)- {- return Ok(Some(i64::from(match position.from_end {- true => cached.from_end,- false => cached.from_start,- })));- }-- let Some(parent) = self.parent_of(node) else {- if position.of_type {- self.row_of(node)?;- }- return Ok(Some(1));- };- let view_sequence = self- .transaction_fact_view- .and_then(|(view, side)| view.sibling_sequence(side, node));- if view_sequence.is_none()- && self- .match_workspace- .as_ref()- .unwrap()- .0- .sibling_sequence(node, side)- .is_none()- {- let children = self.children_of(parent).collect();- self.match_workspace.as_mut().unwrap().0.sibling_geometry_by_tree_side[side.tree_side()]- .insert_sequence(children);- }- let siblings = view_sequence.unwrap_or_else(|| {- self.match_workspace- .as_ref()- .unwrap()- .0- .sibling_sequence(node, side)- .unwrap()- });- if siblings.is_empty() {- return Ok(None);- }-- if position.of_type {- let mut type_ids = HashMap::default();- let mut sibling_types = Vec::with_capacity(siblings.len());- let mut type_positions: SmallVec<[SiblingPositions; 1]> = SmallVec::new();- for &sibling in siblings {- let row = match self.row_of(sibling) {- Ok(row) => row,- Err(Incomplete::MissingFacts(missing)) => {- return Err(Incomplete::MissingSiblingFacts {- first: missing,- last_exclusive: None,- });- }- Err(incomplete) => return Err(incomplete),- };- let sibling_type = (row.facts.tag_of(row.row), row.facts.namespace_of(row.row));- let next_type_id = u32::try_from(type_positions.len()).expect("sibling type space exhausted");- let type_id = *type_ids.entry(sibling_type).or_insert_with(|| {- type_positions.push(SiblingPositions {- from_start: 0,- from_end: 0,- });- next_type_id- });- sibling_types.push(type_id);- type_positions[type_id as usize].from_end += 1;- }- let scratch = &mut self.match_workspace.as_mut().unwrap().0;- let siblings = view_sequence.unwrap_or_else(|| {- scratch.sibling_geometry_by_tree_side[side.tree_side()]- .sibling_sequence(node)- .unwrap()- });- let positions = &mut scratch.type_positions_by_evaluation_side[side as usize];- for (&sibling, type_id) in siblings.iter().zip(sibling_types) {- let position = &mut type_positions[type_id as usize];- position.from_start += 1;- positions.insert(- sibling.element_index().expect("only elements have sibling positions") as usize,- *position,- );- position.from_end -= 1;- }- }-- let Some(cached) = self- .match_workspace- .as_ref()- .unwrap()- .0- .sibling_position(node, side, position.of_type)- else {- return Ok(None);- };- Ok(Some(i64::from(match position.from_end {- true => cached.from_end,- false => cached.from_start,- })))- }-- #[inline]- pub(super) fn row_of(&self, node: StyleNodeID) -> Result<MatchFactRow<'a>, Incomplete> {- let row = match self.transaction_fact_view {- Some((view, side)) => view.row_of(side, self.facts, node),- None => self.facts.row_of(node).map(|row| (self.facts, row)),- };- row.map(|(facts, row)| MatchFactRow { facts, row })- .ok_or(Incomplete::MissingFacts(node))- }-- /// Whether every row this evaluator serves comes from the resident arrangement. Only a- /// before-side view with retained before rows can serve a row from somewhere else.- #[inline]- pub(super) fn serves_only_resident_rows(&self) -> bool {- match self.transaction_fact_view {- Some((view, TransactionFactSide::Before)) => view.before.is_none(),- _ => true,- }- }-- /// The distinct hosts a `::part()` rule can address this element from, nearest first.- ///- /// One per level of `exportparts` forwarding. An element that carries a part name and is- /// forwarded nowhere has no recorded pairing at all, so the host of the tree it stands in is the- /// only level it has - which is every part in a document using no `exportparts`.- fn part_exposure_hosts_of(&self, node: StyleNodeID) -> SmallVec<[StyleNodeID; 1]> {- let pairs = self.tree.part_hosts_of(node);- if pairs.is_empty() {- return self.tree.shadow_host_of(node).into_iter().collect();- }- let mut hosts = SmallVec::new();- for &(_, host) in pairs {- if !hosts.contains(&host) {- hosts.push(host);- }- }- hosts- }-}--/// The style engine's tree, as a transaction view shows it where there is one.-#[derive(Clone, Copy)]-pub struct EngineTree<'a> {- tree: &'a StyleNodeTree,- transaction_fact_view: Option<(&'a TransactionFactView, TransactionFactSide)>,-}--impl<'a> EngineTree<'a> {- #[inline]- fn children(self, parent: StyleNodeID) -> SiblingChildren<'a> {- match self.transaction_fact_view {- Some((view, side)) => view.children_of(self.tree, side, parent),- None => SiblingChildren::Live(self.tree.children(parent)),- }- }-}--impl SelectorTree for EngineTree<'_> {- type Node = StyleNodeID;-- #[inline]- fn backs_pseudo_element(self, node: StyleNodeID, kind: u16) -> bool {- self.tree.backing_pseudo_kind_of(node) == Some(kind)- }-- #[inline]- fn parent(self, node: StyleNodeID) -> Option<StyleNodeID> {- self.transaction_fact_view.map_or_else(- || self.tree.parent(node),- |(view, side)| view.parent_of(self.tree, side, node),- )- }-- #[inline]- fn previous_sibling(self, node: StyleNodeID) -> Option<StyleNodeID> {- self.transaction_fact_view.map_or_else(- || self.tree.previous_element_sibling(node),- |(view, side)| view.previous_sibling_of(self.tree, side, node),- )- }-- #[inline]- fn next_sibling(self, node: StyleNodeID) -> Option<StyleNodeID> {- self.transaction_fact_view.map_or_else(- || self.tree.next_element_sibling(node),- |(view, side)| view.next_sibling_of(self.tree, side, node),- )- }-- #[inline]- fn first_child(self, parent: StyleNodeID) -> Option<StyleNodeID> {- match self.transaction_fact_view {- Some((view, side)) => view.children_of(self.tree, side, parent).next(),- None => self.tree.first_element_child(parent),- }- }-- #[inline]- fn first_sibling(self, node: StyleNodeID) -> StyleNodeID {- self.parent(node)- .and_then(|parent| self.first_child(parent))- .unwrap_or(node)- }-- #[inline]- fn inclusive_siblings(self, node: StyleNodeID) -> impl Iterator<Item = StyleNodeID> {- let parent = self.parent(node);- parent- .map(|parent| self.children(parent))- .into_iter()- .flatten()- .chain(parent.is_none().then_some(node))- }-- #[inline]- fn live_parent(self, node: StyleNodeID) -> Option<StyleNodeID> {- self.tree.parent(node)- }-- #[inline]- fn shadow_root_of(self, host: StyleNodeID) -> Option<StyleNodeID> {- self.tree.shadow_root_of(host)- }-- #[inline]- fn host_of(self, shadow_root: StyleNodeID) -> Option<StyleNodeID> {- self.tree.host_of(shadow_root)- }-- #[inline]- fn for_each_on_axis(- self,- axis: RelativeAxis,- below_the_axis: bool,- anchor: StyleNodeID,- visit: impl FnMut(StyleNodeID) -> bool,- ) {- candidate_witnesses(axis, below_the_axis, anchor, self.tree, visit);- }-- #[inline]- fn assigned_slot_of(self, node: StyleNodeID) -> Option<StyleNodeID> {- self.tree.assigned_slot_of(node)- }-- #[inline]- fn shadow_host_of(self, node: StyleNodeID) -> Option<StyleNodeID> {- self.tree.shadow_host_of(node)- }-}--impl<'a> SelectorSubject for EngineSubject<'a> {- type Atoms = EngineAtoms;- type Node = StyleNodeID;- type Tree = EngineTree<'a>;- type Row = MatchFactRow<'a>;- type Attribute = (&'a StyleNodeFacts, super::index::AttributeFact);- type Features<'s>- = MatchFactRow<'a>- where- Self: 's;- type Incomplete = Incomplete;- type Counters = Counters;- type PrefixSlot = PrecedingSiblingParentID;-- #[inline]- fn tree(&self) -> EngineTree<'a> {- EngineTree {- tree: self.tree,- transaction_fact_view: self.transaction_fact_view,- }- }-- #[inline]- fn row(&mut self, node: StyleNodeID) -> Result<MatchFactRow<'a>, Incomplete> {- self.row_of(node)- }-- #[inline]- fn features(&self, row: MatchFactRow<'a>) -> MatchFactRow<'a> {- row- }-- #[inline]- fn same_type(&self, row: MatchFactRow<'a>, other: MatchFactRow<'a>) -> bool {- row.facts.tag_of(row.row) == other.facts.tag_of(other.row)- && row.facts.namespace_of(row.row) == other.facts.namespace_of(other.row)- }-- #[inline]- fn attribute_value_atom(&self, (_, attribute): (&'a StyleNodeFacts, super::index::AttributeFact)) -> StyleAtomID {- attribute.value- }-- #[inline]- fn attribute_value_text(- &self,- (facts, attribute): (&'a StyleNodeFacts, super::index::AttributeFact),- ) -> Option<TokenizerInput<'_>> {- facts.text_of(attribute).map(TokenizerInput::Utf16)- }-- #[inline]- fn has_state(&self, row: MatchFactRow<'a>, fact: StateFact) -> bool {- row.facts.states_of(row.row).contains(fact)- }-- #[inline]- fn language_tag(&self, row: MatchFactRow<'a>) -> TokenizerInput<'_> {- TokenizerInput::Utf16(row.facts.language_tag_of(row.row))- }-- #[inline]- fn directionality_is(&self, row: MatchFactRow<'a>, direction: StyleAtomID) -> bool {- row.facts.directionality_of(row.row) == direction- }-- #[inline]- fn has_custom_state(&self, row: MatchFactRow<'a>, state: StyleAtomID) -> bool {- row.facts.custom_states_of(row.row).contains(&state)- }-- #[inline]- fn heading_level(&self, row: MatchFactRow<'a>) -> u8 {- row.facts.heading_level_of(row.row)- }-- #[inline]- fn is_empty(&mut self, node: StyleNodeID) -> Result<bool, Incomplete> {- // Element children are style nodes and the tree answers for them. A text or comment child is- // not, so the element publishes whether it holds one.- let row = self.row_of(node)?;- Ok(self.tree.first_element_child(node).is_none() && !row.facts.has_text_content_of(row.row))- }-- #[inline]- fn is_root(&self, node: StyleNodeID) -> bool {- self.parent_of(node).is_none()- }-- #[inline]- fn is_node(&self, node: StyleNodeID, named: StyleNodeID) -> bool {- node == named- }-- #[inline]- fn has_part(&self, row: MatchFactRow<'a>, part: StyleAtomID) -> bool {- row.facts.parts_of(row.row).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.tree.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_of(node)?;- let pairs = self.tree.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_of(row.row).contains(&part),- false => pairs- .iter()- .any(|&(exposed, exposed_to)| exposed == part && exposed_to == host),- })- }-- /// A row facts cannot answer for yet is never prejudged.- #[inline]- fn may_match(&self, program: &SelectorProgram, compound: SelectorNodeID, node: StyleNodeID) -> bool {- let required = program.relation_target_bloom(compound);- if required == 0 {- return true;- }- match self.row_of(node) {- Ok(row) => row.facts.dispatch_bloom_of(row.row, false) & required == required,- Err(_) => true,- }- }-- /// Answers are kept per compiled program, so only an evaluation that names its program and binds- /// no scope, anchor or shadow root may share them.- #[inline]- fn remembers_relations(&self, bindings: &SelectorBindings<StyleNodeID>) -> bool {- self.match_workspace.is_some()- && self.transitive_relation_program.is_some()- && bindings.scope_root_instance.is_none()- && bindings.relative_anchor.is_none()- && bindings.scope_shadow_root.is_none()- }-- #[inline]- fn relation_answer(&self, _program: &SelectorProgram, relation: SelectorNodeID, node: StyleNodeID) -> Option<bool> {- let (workspace, side) = self.match_workspace.as_ref()?;- match workspace- .relations(*side)- .lookup(self.transitive_relation_program?, relation, node)- {- Lookup::Known(()) => Some(true),- Lookup::KnownAbsent => Some(false),- Lookup::Missing(_) => None,- }- }-- #[inline]- fn record_relation_answer(- &mut self,- _program: &SelectorProgram,- relation: SelectorNodeID,- node: StyleNodeID,- answer: bool,- ) {- if let Some((workspace, side)) = self.match_workspace.as_mut()- && let Some(program_id) = self.transitive_relation_program- {- workspace.relations_by_evaluation_side[*side as usize].insert(program_id, relation, node, answer);- }- }-- #[inline]- fn preceding_sibling_prefix(- &mut self,- _program: &SelectorProgram,- relation: SelectorNodeID,- node: StyleNodeID,- ) -> Option<RememberedPrefix<PrecedingSiblingParentID, StyleNodeID>> {- // Only a sibling sequence with a parent has somewhere to keep its progress.- let parent = self.tree().parent(node)?;- let program_id = self.transitive_relation_program?;- let (workspace, side) = self.match_workspace.as_mut()?;- let (slot, prefix) = workspace.relations_by_evaluation_side[*side as usize]- .preceding_sibling_prefix(program_id, relation, parent);- Some(RememberedPrefix { slot, prefix })- }-- #[inline]- fn record_preceding_sibling_prefix(- &mut self,- _program: &SelectorProgram,- relation: SelectorNodeID,- parent: PrecedingSiblingParentID,- prefix: PrecedingSiblingPrefix,- ) {- if let Some((workspace, side)) = self.match_workspace.as_mut()- && let Some(program_id) = self.transitive_relation_program- {- workspace.relations_by_evaluation_side[*side as usize]- .insert_preceding_sibling_prefix(program_id, relation, parent, prefix);- }- }-- #[inline]- fn positional_answer(&self, position: NthPosition, node: StyleNodeID) -> Option<bool> {- if self.positional_index_policy != PositionalIndexPolicy::All {- return None;- }- let (workspace, side) = self.match_workspace.as_ref()?;- workspace.positional_answer(position, node, *side)- }-- #[inline]- fn record_positional_answer(&mut self, position: NthPosition, node: StyleNodeID, answer: bool) {- if self.positional_index_policy == PositionalIndexPolicy::All- && let Some((workspace, side)) = self.match_workspace.as_mut()- {- workspace.insert_positional_answer(position, node, *side, 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);- }- self.indexed_sibling_position(position, node)- }-- /// A completed walk of the live tree is what a retained witness is: proof that the query's- /// Boolean on this element is true right now. Both outcomes are recorded - the entry doubles as- /// "the last completed evaluation answered true", which is the half a routing-time- /// re-verification cannot re-establish on its own.- fn record_relative_answer(- &mut self,- program: &SelectorProgram,- query: RelativeQueryID,- anchor: StyleNodeID,- answer: bool,- witness: Option<StyleNodeID>,- ) {- if let Some(witnesses) = self.witnesses.as_deref_mut()- && let Some(program_id) = self.transitive_relation_program- && program.retainable_relative_query(query).is_some()- {- let key = RelationalWitnessKey {- program: program_id,- query,- anchor,- };- match (answer, witness) {- (true, Some(witness)) => witnesses.push(WitnessEffect::Retain(key, witness)),- (false, _) => witnesses.push(WitnessEffect::Clear(key)),- (true, None) => {}- }- }- }-}--/// `index` is a 1-based position; the test is whether it equals `step * n + offset` for some-/// non-negative integer `n`.-pub(super) fn matches_an_plus_b(step: i32, offset: i32, index: i64) -> bool {- let step = i64::from(step);- let offset = i64::from(offset);- if step == 0 {- return index == offset;- }- let difference = index - offset;- difference % step == 0 && difference / step >= 0-}--fn fold(unit: u16) -> u16 {- if (u16::from(b'A')..=u16::from(b'Z')).contains(&unit) {- return unit + u16::from(b'a' - b'A');- }- unit-}--pub(crate) fn attribute_value_matches<T: Copy + Into<u16>>(- operator: AttributeOperator,- value: &[T],- literal: &[u16],- insensitive: bool,-) -> bool {- match operator {- AttributeOperator::Presence => true,- AttributeOperator::Exact => equals(value, literal, insensitive),- AttributeOperator::Includes => {- !literal.is_empty()- && value- .split(|unit| matches!((*unit).into(), 0x20 | 0x09 | 0x0A | 0x0C | 0x0D))- .any(|token| equals(token, literal, insensitive))- }- AttributeOperator::DashMatch => {- equals(value, literal, insensitive)- || (value.len() > literal.len()- && value[literal.len()].into() == u16::from(b'-')- && starts_with(value, literal, insensitive))- }- AttributeOperator::Prefix => !literal.is_empty() && starts_with(value, literal, insensitive),- AttributeOperator::Suffix => {- !literal.is_empty()- && value.len() >= literal.len()- && equals(&value[value.len() - literal.len()..], literal, insensitive)- }- AttributeOperator::Substring => {- !literal.is_empty()- && value.len() >= literal.len()- && (0..=value.len() - literal.len())- .any(|start| equals(&value[start..start + literal.len()], literal, insensitive))- }- }-}--fn equals<T: Copy + Into<u16>>(value: &[T], literal: &[u16], insensitive: bool) -> bool {- if !insensitive {- return value.len() == literal.len() && value.iter().zip(literal).all(|(&left, &right)| left.into() == right);- }- value.len() == literal.len()- && value- .iter()- .zip(literal)- .all(|(&left, &right)| fold(left.into()) == fold(right))-}--fn starts_with<T: Copy + Into<u16>>(value: &[T], literal: &[u16], insensitive: bool) -> bool {- value.len() >= literal.len() && equals(&value[..literal.len()], literal, insensitive)-}--#[cfg(test)]-mod tests {- use super::super::index::AttributeFact;- use super::super::index::LocalFeatureKey;- use super::super::index::StateSet;- use super::super::instrumentation::Counter;- use super::super::relative_selector::RelativeAxis;- use super::*;-- #[test]- fn shared_route_columns_detach_before_an_edit() {- let push = |columns: &mut RouteColumns, rule| {- let empty = RouteRange { offset: 0, length: 0 };- let route = RouteID::from_index(columns.len());- let previous = columns- .make_mut()- .canonical_route_heads- .insert((RuleID(rule), EntryID(0)), route);- columns.make_mut().canonical_next.push(previous);- columns.make_mut().sibling_first.push(route);- columns.push(- RouteHeader {- rule: RuleID(rule),- entry: EntryID(0),- selector_node: NO_ROUTE_INDEX,- anchor_index: NO_ROUTE_INDEX,- },- RouteRanges {- path: empty,- origin: empty,- origin_requirements: empty,- parent: empty,- waypoints: empty,- },- );- };- let mut first = RouteColumns::default();- let mut second = RouteColumns::default();- for rule in 0..128 {- push(&mut first, rule);- push(&mut second, rule);- }- first.make_mut().inverse_steps.push(InverseStep::Children);- first.make_mut().keys.push(DispatchKey::Universal);- second.make_mut().inverse_steps.push(InverseStep::Children);- second.make_mut().keys.push(DispatchKey::Universal);- let mut pools = RoutingPools::default();- first.share(&mut pools);- second.share(&mut pools);- let (RouteColumns::Shared(a), RouteColumns::Shared(b)) = (&first, &second) else {- panic!("columns were not shared")- };- assert!(Arc::ptr_eq(a, b));- second.make_mut().inverse_steps.push(InverseStep::Descendants);- second.make_mut().keys.push(DispatchKey::Universal);- assert_eq!(first.inverse_steps, [InverseStep::Children]);- assert_eq!(first.keys, [DispatchKey::Universal]);- push(&mut second, 128);- assert_eq!(first.len(), 128);- assert_eq!(second.len(), 129);- assert_eq!(first.canonical_route_heads.len(), 128);- assert_eq!(second.canonical_route_heads.len(), 129);- assert_eq!(first.sibling_first.len(), 128);- assert_eq!(second.sibling_first.len(), 129);- second.share(&mut pools);- drop(first);- let headers = second.headers.as_ptr();- second.make_mut();- assert_eq!(- second.headers.as_ptr(),- headers,- "the sole owner can recover its buffers"- );- assert_eq!(second.headers[128].rule, RuleID(128));- }-- #[test]- fn relation_answers_share_packed_pages_per_compiled_relation() {- let mut cache = MatchRelationCache::default();- let program = SelectorProgramID(7);- let relation = SelectorNodeID(11);- let first = StyleNodeID::element(1);- let same_page = StyleNodeID::element(511);- let next_page = StyleNodeID::element(512);- assert_eq!(- cache.lookup(program, relation, first),- Lookup::Missing(MatchRelationAnswerGap {- program,- relation,- node: first,- })- );- cache.insert(program, relation, first, false);- cache.insert(program, relation, same_page, true);- cache.insert(program, relation, next_page, true);-- assert_eq!(cache.lookup(program, relation, first), Lookup::KnownAbsent);- assert_eq!(cache.lookup(program, relation, same_page), Lookup::Known(()));- assert_eq!(cache.lookup(program, relation, next_page), Lookup::Known(()));- let missing_program = SelectorProgramID(8);- assert_eq!(- cache.lookup(missing_program, relation, first),- Lookup::Missing(MatchRelationAnswerGap {- program: missing_program,- relation,- node: first,- })- );- }-- #[test]- fn preceding_sibling_prefixes_pack_parents_by_compiled_relation() {- let mut prefixes = PrecedingSiblingPrefixes::default();- let program = SelectorProgramID(7);- let relation = SelectorNodeID(11);- let first_parent = PrecedingSiblingParentID(0);- let second_parent = PrecedingSiblingParentID(17);- let first = PrecedingSiblingPrefix {- next: Some(StyleNodeID::element(3)),- answer: false,- };- let replacement = PrecedingSiblingPrefix {- next: None,- answer: true,- };-- assert!(prefixes.get(program, relation, first_parent).is_none());- prefixes.insert(program, relation, second_parent, replacement);- prefixes.insert(program, relation, first_parent, first);- assert_eq!(prefixes.get(program, relation, first_parent).unwrap().next, first.next);- assert!(!prefixes.get(program, relation, first_parent).unwrap().answer);- assert!(prefixes.get(program, SelectorNodeID(12), first_parent).is_none());-- prefixes.insert(program, relation, first_parent, replacement);- assert!(prefixes.get(program, relation, first_parent).unwrap().answer);- assert_eq!(prefixes.get(program, relation, first_parent).unwrap().next, None);- }-- #[test]- fn sibling_positions_share_tree_geometry_but_not_fact_sensitive_ranks() {- let mut cache = MatchScratch::default();- let node = StyleNodeID::element(3);- let next_page = StyleNodeID::element(64);- let position = SiblingPositions {- from_start: 1,- from_end: 2,- };-- let (sequence, pages, published) =- cache.publish_sibling_sequence(vec![node, next_page], MatchEvaluationSide::Current);- assert_eq!(pages, 2);- assert!(published);- let (reused, pages, published) =- cache.publish_sibling_sequence(vec![node, next_page], MatchEvaluationSide::OldFacts);- assert_eq!(pages, 0);- assert!(!published);- assert!(Arc::ptr_eq(&sequence, &reused));- assert_eq!(- cache.sibling_position(node, MatchEvaluationSide::OldFacts, false),- Some(position)- );- assert_eq!(cache.sibling_position(node, MatchEvaluationSide::OldTree, false), None);- assert_eq!(- cache.sibling_geometry_by_tree_side[MatchEvaluationSide::Current.tree_side()]- .memberships- .page_count(),- 2- );-- cache.type_positions_by_evaluation_side[MatchEvaluationSide::Current as usize]- .insert(node.element_index().unwrap() as usize, position);- assert_eq!(cache.sibling_position(node, MatchEvaluationSide::OldFacts, true), None);- cache.type_positions_by_evaluation_side[MatchEvaluationSide::OldFacts as usize]- .insert(node.element_index().unwrap() as usize, position);- cache.retain_current_for_matching();- assert_eq!(- cache.sibling_position(node, MatchEvaluationSide::Current, true),- Some(position)- );- assert_eq!(cache.sibling_position(node, MatchEvaluationSide::OldFacts, true), None);- }-- #[test]- fn positional_answers_are_shared_across_programs() {- let fixture = Fixture::new();- let first = single_entry(|builder| {- builder.push(SelectorOp::NthPosition(NthPosition {- step: 2,- offset: 0,- from_end: false,- of_selector: None,- of_type: false,- }))- });- let second = single_entry(|builder| {- builder.push(SelectorOp::NthPosition(NthPosition {- step: 2,- offset: 0,- from_end: false,- of_selector: None,- of_type: false,- }))- });- let mut workspace = MatchScratch::default();- let mut evaluator = MatchEvaluator::new(&fixture.tree, &fixture.facts)- .with_match_workspace(&mut workspace, MatchEvaluationSide::Current);-- assert!(- !evaluator- .matches_entry(&first, &first.entries()[0], fixture.nodes[1], &fixture.counters)- .unwrap()- );- assert!(- !evaluator- .matches_entry(&second, &second.entries()[0], fixture.nodes[1], &fixture.counters)- .unwrap()- );- assert_eq!(fixture.counters.get(Counter::StructuralTests), 1);- }-- #[test]- fn feature_answers_are_recomputed_across_programs() {- let fixture = Fixture::new();- let first = single_entry(|builder| builder.push_feature(FeatureTest::Class(CLASS_ITEM)));- let second = single_entry(|builder| builder.push_feature(FeatureTest::Class(CLASS_ITEM)));- let mut workspace = MatchScratch::default();- let mut evaluator = MatchEvaluator::new(&fixture.tree, &fixture.facts)- .with_match_workspace(&mut workspace, MatchEvaluationSide::Current);-- assert!(- evaluator- .matches_entry_for_program(- SelectorProgramID(7),- &first,- &first.entries()[0],- fixture.nodes[1],- &fixture.counters,- )- .unwrap()- );- assert!(- evaluator- .matches_entry_for_program(- SelectorProgramID(8),- &second,- &second.entries()[0],- fixture.nodes[1],- &fixture.counters,- )- .unwrap()- );- assert_eq!(fixture.counters.get(Counter::LocalFeatureTests), 2);- }-- /// A four-element document: `root > [first.item, second.item#target, third]`.- struct Fixture {- tree: StyleNodeTree,- facts: StyleNodeFacts,- nodes: Vec<StyleNodeID>,- counters: Counters,- }-- const TAG_DIV: StyleAtomID = StyleAtomID(1);- const TAG_SPAN: StyleAtomID = StyleAtomID(2);- const CLASS_ITEM: StyleAtomID = StyleAtomID(10);- const CLASS_THEME: StyleAtomID = StyleAtomID(11);- const ID_TARGET: StyleAtomID = StyleAtomID(20);- const ATTR_HREF: StyleAtomID = StyleAtomID(30);- const VALUE_HREF: StyleAtomID = StyleAtomID(41);- const ATTR_TYPE: StyleAtomID = StyleAtomID(31);- const VALUE_TEXT: StyleAtomID = StyleAtomID(40);-- #[test]- fn selector_program_atom_roots_cover_every_operator_payload() {- let program: SelectorProgram = SelectorProgram {- nodes: vec![- SelectorOp::Feature(FeatureTest::TagName(TagTest {- written: StyleAtomID(1),- folded: StyleAtomID(2),- fold_in_namespace: StyleAtomID(3),- })),- SelectorOp::Feature(FeatureTest::Id(StyleAtomID(4))),- SelectorOp::Feature(FeatureTest::Class(StyleAtomID(5))),- SelectorOp::Feature(FeatureTest::Attribute(AttributeTest {- name: StyleAtomID(6),- any_namespace: false,- folded: StyleAtomID(7),- fold_in_namespace: StyleAtomID(8),- operator: AttributeOperator::Exact,- value_atom: StyleAtomID(9),- value_offset: 0,- value_length: 0,- case: AttributeCase::InsensitiveForNamespace(StyleAtomID(10)),- })),- SelectorOp::Feature(FeatureTest::Namespace(NamespaceTest::Named(StyleAtomID(11)))),- SelectorOp::Part(StyleAtomID(12)),- SelectorOp::ValueState {- kind: ValueStateTestKind::Directionality,- value: StyleAtomID(13),- },- ],- ..SelectorProgram::default()- };- let mut atoms = HashSet::default();- assert_eq!(program.collect_atoms(&mut atoms), 7);- assert_eq!(atoms, (1..=13).map(StyleAtomID).collect());- }-- impl Fixture {- fn new() -> Self {- let mut tree = StyleNodeTree::new();- let nodes: Vec<StyleNodeID> = (0..4).map(|_| tree.allocate_element()).collect();- tree.set_first_element_child(nodes[0], Some(nodes[1]));- for index in 1..4 {- tree.set_parent(nodes[index], Some(nodes[0]));- tree.set_next_element_sibling(nodes[index], nodes.get(index + 1).copied());- tree.set_previous_element_sibling(nodes[index], (index > 1).then(|| nodes[index - 1]));- }-- let mut facts = StyleNodeFacts::new();- let href: Vec<u16> = "https://example.com/a".encode_utf16().collect();- facts.set_attribute_value_text_for_test(VALUE_HREF, &href);- facts.push_row(- nodes[0],- TAG_DIV,- StyleAtomID::NONE,- StateSet::default(),- &[CLASS_THEME],- &[],- );- facts.push_row(- nodes[1],- TAG_DIV,- StyleAtomID::NONE,- StateSet::default(),- &[CLASS_ITEM],- &[AttributeFact {- name: ATTR_HREF,- value: VALUE_HREF,- }],- );- let mut hovered = StateSet::default();- hovered.insert(StateFact::Hover);- facts.push_row(- nodes[2],- TAG_SPAN,- ID_TARGET,- hovered,- &[CLASS_ITEM],- &[AttributeFact {- name: ATTR_TYPE,- value: VALUE_TEXT,- }],- );- let row = facts.row_of(nodes[2]).unwrap();- facts.set_row_parameters(row, StyleAtomID::NONE, StyleAtomID::NONE, 0, &[], &[StyleAtomID(77)]);- facts.push_row(nodes[3], TAG_DIV, StyleAtomID::NONE, StateSet::default(), &[], &[]);-- Self {- tree,- facts,- nodes,- counters: Counters::new(),- }- }-- fn matches(&mut self, program: &SelectorProgram, node: usize) -> bool {- let mut evaluator = MatchEvaluator::new(&self.tree, &self.facts);- evaluator- .matches_entry(program, &program.entries()[0], self.nodes[node], &self.counters)- .unwrap()- }-- /// The same, for rules attached to a shadow tree rather than to the document.- fn matches_in_shadow_tree(&mut self, program: &SelectorProgram, node: usize, shadow_root: usize) -> bool {- let shadow_root = self.nodes[shadow_root];- let mut evaluator = MatchEvaluator::new(&self.tree, &self.facts).in_shadow_tree(shadow_root);- evaluator- .matches_entry(program, &program.entries()[0], self.nodes[node], &self.counters)- .unwrap()- }- }-- fn single_entry(build: impl FnOnce(&mut SelectorProgramBuilder) -> SelectorNodeID) -> SelectorProgram {- let mut builder = SelectorProgramBuilder::new();- let root = build(&mut builder);- builder.push_entry(root);- builder.finish()- }-- #[test]- fn a_compound_matches_only_when_every_operand_does() {- // span.item#target- let program = single_entry(|builder| {- let tag = builder.push_feature(FeatureTest::TagName(TagTest::exact(TAG_SPAN)));- let class = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let id = builder.push_feature(FeatureTest::Id(ID_TARGET));- builder.push_compound(&[tag, class, id])- });-- let mut fixture = Fixture::new();- assert!(fixture.matches(&program, 2));- assert!(!fixture.matches(&program, 1));- assert!(!fixture.matches(&program, 3));- }-- #[test]- fn transpose_routing_retains_each_necessary_compound_feature() {- // span.item#target- let program = single_entry(|builder| {- let tag = builder.push_feature(FeatureTest::TagName(TagTest::exact(TAG_SPAN)));- let class = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let id = builder.push_feature(FeatureTest::Id(ID_TARGET));- builder.push_compound(&[tag, class, id])- });-- assert_eq!(- program.subject_required_keys(0),- vec![DispatchKey::Class(CLASS_ITEM), DispatchKey::TagName(TAG_SPAN),]- );- }-- #[test]- fn transpose_routing_does_not_turn_alternatives_into_requirements() {- // span:is(.item, .theme)- let program = single_entry(|builder| {- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let theme = builder.push_feature(FeatureTest::Class(CLASS_THEME));- let either_class = builder.push_any_of(&[item, theme]);- let tag = builder.push_feature(FeatureTest::TagName(TagTest::exact(TAG_SPAN)));- builder.push_compound(&[tag, either_class])- });-- assert_eq!(- program.subject_required_keys(0),- &[],- "neither alternative is independently necessary"- );- }-- #[test]- fn compound_operands_run_cheapest_first() {- // Declared attribute-first, but the ID test is what should reject.- let program = single_entry(|builder| {- let (offset, length) = builder.push_literal(&"x".encode_utf16().collect::<Vec<_>>());- let attribute = builder.push_feature(FeatureTest::Attribute(AttributeTest {- fold_in_namespace: StyleAtomID::NONE,- folded: ATTR_HREF,- any_namespace: false,- name: ATTR_HREF,- operator: AttributeOperator::Substring,- value_atom: StyleAtomID::NONE,- value_offset: offset,- value_length: length,- case: AttributeCase::Sensitive,- }));- let id = builder.push_feature(FeatureTest::Id(ID_TARGET));- builder.push_compound(&[attribute, id])- });-- let SelectorOp::And { first, count } = program.node(program.entries()[0].root) else {- panic!("expected a compound");- };- let ordered = program.operands(first, count);- assert!(- matches!(program.node(ordered[0]), SelectorOp::Feature(FeatureTest::Id(_))),- "the ID test must be tried before the substring test"- );-- let mut fixture = Fixture::new();- // The candidate has no matching ID, so the substring test never runs.- assert!(!fixture.matches(&program, 1));- assert_eq!(fixture.counters.get(Counter::LocalFeatureTests), 1);- }-- #[test]- fn descendant_and_child_combinators_evaluate_leftwards() {- // .theme .item- let descendant = single_entry(|builder| {- let theme = builder.push_feature(FeatureTest::Class(CLASS_THEME));- let ancestor = builder.push(SelectorOp::Ancestor(theme));- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- builder.push_compound(&[item, ancestor])- });- // .theme > .item- let child = single_entry(|builder| {- let theme = builder.push_feature(FeatureTest::Class(CLASS_THEME));- let parent = builder.push(SelectorOp::Parent(theme));- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- builder.push_compound(&[item, parent])- });-- let mut fixture = Fixture::new();- assert!(fixture.matches(&descendant, 1));- assert!(fixture.matches(&child, 1));- assert!(!fixture.matches(&descendant, 0));- assert!(!fixture.matches(&child, 3));- }-- #[test]- fn sibling_combinators_look_backwards_from_the_subject() {- // .item + span- let adjacent = single_entry(|builder| {- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let previous = builder.push(SelectorOp::PreviousSibling(item));- let span = builder.push_feature(FeatureTest::TagName(TagTest::exact(TAG_SPAN)));- builder.push_compound(&[span, previous])- });- // .item ~ div- let general = single_entry(|builder| {- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let preceding = builder.push(SelectorOp::PrecedingSibling(item));- let div = builder.push_feature(FeatureTest::TagName(TagTest::exact(TAG_DIV)));- builder.push_compound(&[div, preceding])- });-- let mut fixture = Fixture::new();- assert!(fixture.matches(&adjacent, 2));- assert!(!fixture.matches(&adjacent, 1));- assert!(fixture.matches(&general, 3));- assert!(!fixture.matches(&general, 1));- }-- #[test]- fn the_before_transaction_view_evaluates_multiple_adjacent_steps() {- // .item + .item + div- let program = single_entry(|builder| {- let first = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let previous = builder.push(SelectorOp::PreviousSibling(first));- let middle = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let middle = builder.push_compound(&[middle, previous]);- let previous = builder.push(SelectorOp::PreviousSibling(middle));- let subject = builder.push_feature(FeatureTest::TagName(TagTest::exact(TAG_DIV)));- builder.push_compound(&[subject, previous])- });-- let mut fixture = Fixture::new();- fixture- .tree- .set_next_element_sibling(fixture.nodes[1], Some(fixture.nodes[3]));- fixture- .tree- .set_previous_element_sibling(fixture.nodes[3], Some(fixture.nodes[1]));- fixture.tree.set_parent(fixture.nodes[2], None);- fixture.tree.set_next_element_sibling(fixture.nodes[2], None);- fixture.tree.set_previous_element_sibling(fixture.nodes[2], None);-- let mut view = TransactionFactView {- root: fixture.nodes[0],- moved_features: Default::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,- };- view.insert_before_sibling_sequence(- fixture.nodes[0],- vec![fixture.nodes[1], fixture.nodes[2], fixture.nodes[3]],- );- view.finish_before_sibling_relations();- assert_eq!(- view.sibling_positions(TransactionFactSide::Before, fixture.nodes[2]),- Some(SiblingPositions {- from_start: 2,- from_end: 2,- })- );- assert_eq!(view.before_sibling_geometry.memberships.page_count(), 1);-- assert!(- !MatchEvaluator::new(&fixture.tree, &fixture.facts)- .matches_entry(&program, &program.entries()[0], fixture.nodes[3], &fixture.counters,)- .unwrap()- );- assert!(- MatchEvaluator::new(&fixture.tree, &fixture.facts)- .with_transaction_fact_view(&view, TransactionFactSide::Before)- .matches_entry(&program, &program.entries()[0], fixture.nodes[3], &fixture.counters,)- .unwrap()- );- }-- #[test]- fn a_general_sibling_miss_requests_the_remaining_sequence_prefix() {- let program = single_entry(|builder| {- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let preceding = builder.push(SelectorOp::PrecedingSibling(item));- let div = builder.push_feature(FeatureTest::TagName(TagTest::exact(TAG_DIV)));- builder.push_compound(&[div, preceding])- });- let fixture = Fixture::new();- let mut sparse = StyleNodeFacts::new();- sparse.push_row(- fixture.nodes[3],- TAG_DIV,- StyleAtomID::NONE,- StateSet::default(),- &[],- &[],- );- let mut evaluator = MatchEvaluator::new(&fixture.tree, &sparse);-- assert_eq!(- evaluator.matches_entry(&program, &program.entries()[0], fixture.nodes[3], &fixture.counters),- Err(Incomplete::MissingSiblingFacts {- first: fixture.nodes[1],- last_exclusive: Some(fixture.nodes[3]),- })- );- }-- #[test]- fn an_adjacent_sibling_miss_requests_only_the_previous_node() {- let program = single_entry(|builder| {- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let previous = builder.push(SelectorOp::PreviousSibling(item));- let div = builder.push_feature(FeatureTest::TagName(TagTest::exact(TAG_DIV)));- builder.push_compound(&[div, previous])- });- let fixture = Fixture::new();- let mut sparse = StyleNodeFacts::new();- sparse.push_row(- fixture.nodes[3],- TAG_DIV,- StyleAtomID::NONE,- StateSet::default(),- &[],- &[],- );- let mut evaluator = MatchEvaluator::new(&fixture.tree, &sparse);-- assert_eq!(- evaluator.matches_entry(&program, &program.entries()[0], fixture.nodes[3], &fixture.counters),- Err(Incomplete::MissingFacts(fixture.nodes[2]))- );- }-- #[test]- fn a_missing_fact_below_a_sibling_names_its_descendant_range() {- let mut fixture = Fixture::new();-- let child = fixture.tree.allocate_element();- fixture.tree.set_parent(child, Some(fixture.nodes[1]));- fixture.tree.set_first_element_child(fixture.nodes[1], Some(child));- let program = single_entry(|builder| {- let descendant = builder.push_feature(FeatureTest::Class(CLASS_THEME));- let has_descendant = builder.push_relative_exists(RelativeQuery {- axis: RelativeAxis::Descendant,- compound: descendant,- driving_feature: Some(LocalFeatureKey::Class(CLASS_THEME)),- simple: true,- witness_is_below_the_axis: false,- match_in_shadow_tree: false,- });- let preceding = builder.push(SelectorOp::PrecedingSibling(has_descendant));- let div = builder.push_feature(FeatureTest::TagName(TagTest::exact(TAG_DIV)));- builder.push_compound(&[div, preceding])- });- let mut evaluator = MatchEvaluator::new(&fixture.tree, &fixture.facts);-- assert_eq!(- evaluator.matches_entry(&program, &program.entries()[0], fixture.nodes[3], &fixture.counters),- Err(Incomplete::MissingDescendantFacts {- root: fixture.nodes[1],- first: child,- })- );- }-- #[test]- fn a_following_sibling_query_requests_the_remaining_sequence_suffix() {- let program = single_entry(|builder| {- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- builder.push_relative_exists(RelativeQuery {- axis: RelativeAxis::FollowingSibling,- compound: item,- driving_feature: Some(LocalFeatureKey::Class(CLASS_ITEM)),- simple: true,- witness_is_below_the_axis: false,- match_in_shadow_tree: false,- })- });- let fixture = Fixture::new();- let mut sparse = StyleNodeFacts::new();- sparse.push_row(- fixture.nodes[1],- TAG_DIV,- StyleAtomID::NONE,- StateSet::default(),- &[CLASS_ITEM],- &[],- );- let mut evaluator = MatchEvaluator::new(&fixture.tree, &sparse);-- assert_eq!(- evaluator.matches_entry(&program, &program.entries()[0], fixture.nodes[1], &fixture.counters),- Err(Incomplete::MissingSiblingFacts {- first: fixture.nodes[2],- last_exclusive: None,- })- );- }-- #[test]- fn attribute_operators_read_text_only_when_an_atom_cannot_answer() {- let mut fixture = Fixture::new();-- let exact = single_entry(|builder| {- builder.push_feature(FeatureTest::Attribute(AttributeTest {- fold_in_namespace: StyleAtomID::NONE,- folded: ATTR_TYPE,- any_namespace: false,- name: ATTR_TYPE,- operator: AttributeOperator::Exact,- value_atom: VALUE_TEXT,- value_offset: 0,- value_length: 0,- case: AttributeCase::Sensitive,- }))- });- assert!(fixture.matches(&exact, 2), "interned values compare as integers");-- let prefix = single_entry(|builder| {- let (offset, length) = builder.push_literal(&"https://".encode_utf16().collect::<Vec<_>>());- builder.push_feature(FeatureTest::Attribute(AttributeTest {- fold_in_namespace: StyleAtomID::NONE,- folded: ATTR_HREF,- any_namespace: false,- name: ATTR_HREF,- operator: AttributeOperator::Prefix,- value_atom: StyleAtomID::NONE,- value_offset: offset,- value_length: length,- case: AttributeCase::Sensitive,- }))- });- assert!(fixture.matches(&prefix, 1));- assert!(!fixture.matches(&prefix, 2));-- let suffix = single_entry(|builder| {- let (offset, length) = builder.push_literal(&"/A".encode_utf16().collect::<Vec<_>>());- builder.push_feature(FeatureTest::Attribute(AttributeTest {- fold_in_namespace: StyleAtomID::NONE,- folded: ATTR_HREF,- any_namespace: false,- name: ATTR_HREF,- operator: AttributeOperator::Suffix,- value_atom: StyleAtomID::NONE,- value_offset: offset,- value_length: length,- case: AttributeCase::Insensitive,- }))- });- assert!(fixture.matches(&suffix, 1), "the i flag folds ASCII case");-- let presence = single_entry(|builder| {- builder.push_feature(FeatureTest::Attribute(AttributeTest {- fold_in_namespace: StyleAtomID::NONE,- folded: ATTR_HREF,- any_namespace: false,- name: ATTR_HREF,- operator: AttributeOperator::Presence,- value_atom: StyleAtomID::NONE,- value_offset: 0,- value_length: 0,- case: AttributeCase::Sensitive,- }))- });- assert!(fixture.matches(&presence, 1));- assert!(!fixture.matches(&presence, 3));- }-- #[test]- fn state_is_a_fact_like_any_other() {- let program = single_entry(|builder| {- let hovered = builder.push(SelectorOp::State(StateFact::Hover));- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- builder.push_compound(&[item, hovered])- });- let mut fixture = Fixture::new();- assert!(fixture.matches(&program, 2));- assert!(!fixture.matches(&program, 1));- }-- #[test]- fn query_scope_binds_scope_to_element_root() {- let program = single_entry(|builder| {- let scope = builder.push(SelectorOp::ScopeRootInstance);- let scope = builder.push(SelectorOp::Parent(scope));- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- builder.push_compound(&[scope, item])- });-- let fixture = Fixture::new();- let mut evaluator = MatchEvaluator::new(&fixture.tree, &fixture.facts).with_scope_root(fixture.nodes[0]);- assert!(- evaluator- .matches_entry(&program, &program.entries()[0], fixture.nodes[1], &fixture.counters)- .unwrap()- );-- let mut evaluator = MatchEvaluator::new(&fixture.tree, &fixture.facts).with_scope_root(fixture.nodes[1]);- assert!(- !evaluator- .matches_entry(&program, &program.entries()[0], fixture.nodes[1], &fixture.counters)- .unwrap()- );- }-- #[test]- fn nth_child_counts_the_child_sequence() {- let second = single_entry(|builder| {- builder.push(SelectorOp::NthPosition(NthPosition {- step: 0,- offset: 2,- from_end: false,- of_selector: None,- of_type: false,- }))- });- let odd = single_entry(|builder| {- builder.push(SelectorOp::NthPosition(NthPosition {- step: 2,- offset: 1,- from_end: false,- of_selector: None,- of_type: false,- }))- });- let last = single_entry(|builder| {- builder.push(SelectorOp::NthPosition(NthPosition {- step: 0,- offset: 1,- from_end: true,- of_selector: None,- of_type: false,- }))- });-- let mut fixture = Fixture::new();- assert!(!fixture.matches(&second, 1));- assert!(fixture.matches(&second, 2));- assert!(fixture.matches(&odd, 1));- assert!(!fixture.matches(&odd, 2));- assert!(fixture.matches(&odd, 3));- assert!(fixture.matches(&last, 3));- assert!(!fixture.matches(&last, 2));- // The root has no child sequence.- assert!(!fixture.matches(&second, 0));- }-- #[test]- fn nth_of_type_counts_only_matching_siblings() {- let second_div = single_entry(|builder| {- builder.push(SelectorOp::NthPosition(NthPosition {- step: 0,- offset: 2,- from_end: false,- of_selector: None,- of_type: true,- }))- });- let mut fixture = Fixture::new();- // Children are div, span, div: the second div is the third child.- assert!(fixture.matches(&second_div, 3));- assert!(!fixture.matches(&second_div, 2));- }-- #[test]- fn positional_misses_request_only_the_direction_the_test_counts() {- let from_start = single_entry(|builder| {- builder.push(SelectorOp::NthPosition(NthPosition {- step: 0,- offset: 2,- from_end: false,- of_selector: None,- of_type: true,- }))- });- let from_end = single_entry(|builder| {- builder.push(SelectorOp::NthPosition(NthPosition {- step: 0,- offset: 2,- from_end: true,- of_selector: None,- of_type: true,- }))- });- let fixture = Fixture::new();- let mut first_only = StyleNodeFacts::new();- first_only.push_row(- fixture.nodes[1],- TAG_DIV,- StyleAtomID::NONE,- StateSet::default(),- &[],- &[],- );- let mut evaluator = MatchEvaluator::new(&fixture.tree, &first_only);- assert_eq!(- evaluator.matches_entry(&from_end, &from_end.entries()[0], fixture.nodes[1], &fixture.counters),- Err(Incomplete::MissingSiblingFacts {- first: fixture.nodes[2],- last_exclusive: None,- })- );-- let mut last_only = StyleNodeFacts::new();- last_only.push_row(- fixture.nodes[3],- TAG_DIV,- StyleAtomID::NONE,- StateSet::default(),- &[],- &[],- );- let mut evaluator = MatchEvaluator::new(&fixture.tree, &last_only);- assert_eq!(- evaluator.matches_entry(- &from_start,- &from_start.entries()[0],- fixture.nodes[3],- &fixture.counters- ),- Err(Incomplete::MissingSiblingFacts {- first: fixture.nodes[1],- last_exclusive: Some(fixture.nodes[3]),- })- );- }-- #[test]- fn matching_reports_the_greatest_specificity_among_matching_entries() {- let mut builder = SelectorProgramBuilder::new();- let class = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let class_entry = builder.push_entry(class);- builder.set_entry_specificity(- class_entry,- Specificity {- classes: 1,- ..Specificity::default()- },- );- let id = builder.push_feature(FeatureTest::Id(ID_TARGET));- let id_entry = builder.push_entry(id);- builder.set_entry_specificity(- id_entry,- Specificity {- ids: 1,- ..Specificity::default()- },- );- let program = builder.finish();-- let fixture = Fixture::new();- let mut evaluator = MatchEvaluator::new(&fixture.tree, &fixture.facts);- let matched = evaluator- .match_entries(&program, fixture.nodes[2], &fixture.counters)- .unwrap()- .unwrap();- assert_eq!(- matched.specificity,- Specificity {- ids: 1,- ..Specificity::default()- },- "an earlier lower-specificity match must not hide a later higher one"- );- }-- #[test]- fn a_missing_fact_row_is_reported_rather_than_answered() {- let program = single_entry(|builder| builder.push_feature(FeatureTest::Class(CLASS_ITEM)));- let fixture = Fixture::new();- let missing = StyleNodeID::element(99);- let mut evaluator = MatchEvaluator::new(&fixture.tree, &fixture.facts);- assert_eq!(- evaluator.matches_entry(&program, &program.entries()[0], missing, &fixture.counters),- Err(Incomplete::MissingFacts(missing))- );- }-- fn transpose_of(program: &SelectorProgram) -> Vec<(RoutingKey, Vec<InverseStep>)> {- let mut collected = Vec::new();- program.collect_transpose_entry_points(0, |site| collected.push((site.key, site.path.to_vec())));- collected- }-- #[test]- fn a_descendant_selector_transposes_each_operand_to_its_own_reach() {- // .theme .item- let program = single_entry(|builder| {- let theme = builder.push_feature(FeatureTest::Class(CLASS_THEME));- let ancestor = builder.push(SelectorOp::Ancestor(theme));- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- builder.push_compound(&[item, ancestor])- });-- let collected = transpose_of(&program);- // The subject operand reaches only the changed node itself.- assert!(collected.contains(&(RoutingKey::Class(CLASS_ITEM), vec![])));- // The ancestor operand reaches descendants of whatever changed.- assert!(collected.contains(&(RoutingKey::Class(CLASS_THEME), vec![InverseStep::Descendants])));- assert_eq!(collected.len(), 2);- }-- #[test]- fn each_combinator_transposes_to_its_inverse_relation() {- let cases = [- (- SelectorOp::Parent as fn(SelectorNodeID) -> SelectorOp,- InverseStep::Children,- ),- (SelectorOp::Ancestor, InverseStep::Descendants),- (SelectorOp::PreviousSibling, InverseStep::NextSibling),- (SelectorOp::PrecedingSibling, InverseStep::FollowingSiblings),- ];- for (combinator, expected) in cases {- let program = single_entry(|builder| {- let left = builder.push_feature(FeatureTest::Class(CLASS_THEME));- let step = builder.push(combinator(left));- let right = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- builder.push_compound(&[right, step])- });- let collected = transpose_of(&program);- assert!(- collected.contains(&(RoutingKey::Class(CLASS_THEME), vec![expected])),- "expected {expected:?} for the left operand"- );- }- }-- #[test]- fn a_nested_path_is_reported_in_application_order() {- // .a > .b .c: a change to .a reaches its children, and their descendants.- let program = single_entry(|builder| {- let a = builder.push_feature(FeatureTest::Class(StyleAtomID(1)));- let parent = builder.push(SelectorOp::Parent(a));- let b = builder.push_feature(FeatureTest::Class(StyleAtomID(2)));- let inner = builder.push_compound(&[b, parent]);- let ancestor = builder.push(SelectorOp::Ancestor(inner));- let c = builder.push_feature(FeatureTest::Class(StyleAtomID(3)));- builder.push_compound(&[c, ancestor])- });-- let collected = transpose_of(&program);- assert!(collected.contains(&(- RoutingKey::Class(StyleAtomID(1)),- vec![InverseStep::Children, InverseStep::Descendants]- )));- assert!(collected.contains(&(RoutingKey::Class(StyleAtomID(2)), vec![InverseStep::Descendants])));- assert!(collected.contains(&(RoutingKey::Class(StyleAtomID(3)), vec![])));- }-- #[test]- fn a_negated_or_hidden_operand_is_still_routed() {- // :not(.theme):where(.item)- let program = single_entry(|builder| {- let theme = builder.push_feature(FeatureTest::Class(CLASS_THEME));- let negation = builder.push(SelectorOp::Not(theme));- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let hidden = builder.push(SelectorOp::Where(item));- builder.push_compound(&[negation, hidden])- });-- let collected = transpose_of(&program);- assert!(- collected.contains(&(RoutingKey::Class(CLASS_THEME), vec![])),- "a change inside a negation flips the subject and has to be routed"- );- assert!(collected.contains(&(RoutingKey::Class(CLASS_ITEM), vec![])));- }-- #[test]- fn a_universal_selector_routes_from_no_local_input() {- let program = single_entry(|builder| builder.push_feature(FeatureTest::AnyElement));- assert!(- transpose_of(&program).is_empty(),- "* changes only when the element itself does, which the tree delta already names"- );- }-- #[test]- fn a_positional_selector_routes_structurally() {- let program = single_entry(|builder| {- builder.push(SelectorOp::NthPosition(NthPosition {- step: 2,- offset: 1,- from_end: false,- of_selector: None,- of_type: false,- }))- });- assert_eq!(transpose_of(&program), vec![(RoutingKey::Structural, vec![])]);- }-- #[test]- fn a_positional_argument_routes_through_the_child_sequence() {- let program = single_entry(|builder| {- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- builder.push(SelectorOp::NthPosition(NthPosition {- step: 0,- offset: 1,- from_end: false,- of_selector: Some(item),- of_type: false,- }))- });- let collected = transpose_of(&program);- assert!(collected.contains(&(RoutingKey::Structural, vec![])));- assert!(- collected.contains(&(RoutingKey::Class(CLASS_ITEM), vec![InverseStep::SiblingSequence])),- "changing what counts moves indices across the whole child sequence"- );- }-- #[test]- fn the_registry_returns_only_the_routes_that_mention_an_input() {- let mut registry = RoutingRegistry::new();- let mut programs = SelectorPrograms::new();-- let hovered = single_entry(|builder| {- let class = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let state = builder.push(SelectorOp::State(StateFact::Hover));- builder.push_compound(&[class, state])- });- let unrelated = single_entry(|builder| builder.push_feature(FeatureTest::Id(ID_TARGET)));- let sibling = single_entry(|builder| {- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let preceding = builder.push(SelectorOp::PrecedingSibling(item));- let target = builder.push_feature(FeatureTest::Id(StyleAtomID(4242)));- builder.push_compound(&[target, preceding])- });- let relational = single_entry(|builder| {- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let has = builder.push_relative_exists(RelativeQuery {- axis: RelativeAxis::Descendant,- compound: item,- driving_feature: None,- simple: true,- witness_is_below_the_axis: false,- match_in_shadow_tree: false,- });- let theme = builder.push_feature(FeatureTest::Class(CLASS_THEME));- builder.push_compound(&[theme, has])- });-- let hovered = programs.add(hovered);- let unrelated = programs.add(unrelated);- let sibling = programs.add(sibling);- let relational = programs.add(relational);- registry.add_rule(RuleID(1), hovered, &programs);- registry.add_rule(RuleID(2), unrelated, &programs);- registry.add_rule(RuleID(3), sibling, &programs);- registry.add_rule(RuleID(4), relational, &programs);-- // A hover change reaches only the rule that mentions it.- let routed = registry.routes_for(RoutingKey::State(StateFact::Hover));- assert_eq!(routed.len(), 1);- assert_eq!(registry.rule_of(routed[0]), RuleID(1));- assert_eq!(registry.path_of(routed[0]), &[]);-- // And an unmentioned input reaches nothing at all, without scanning any selector header.- assert!(registry.routes_for(RoutingKey::Class(StyleAtomID(999))).is_empty());- assert_eq!(registry.routes_for(RoutingKey::Id(ID_TARGET)).len(), 1);- let arrivals = registry.arrival_routes_for(RoutingKey::Class(CLASS_ITEM));- assert_eq!(arrivals.len(), 2);- assert_eq!(registry.rule_of(arrivals[0]), RuleID(3));- assert_eq!(registry.rule_of(arrivals[1]), RuleID(4));- }-- #[test]- fn the_registry_canonicalizes_equivalent_sibling_routes() {- assert_eq!(size_of::<Option<RouteID>>(), size_of::<u32>());-- // .item.theme + #target- let sibling = single_entry(|builder| {- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let theme = builder.push_feature(FeatureTest::Class(CLASS_THEME));- let origin = builder.push_compound(&[item, theme]);- let preceding = builder.push(SelectorOp::PrecedingSibling(origin));- let target = builder.push_feature(FeatureTest::Id(ID_TARGET));- builder.push_compound(&[target, preceding])- });- let mut registry = RoutingRegistry::new();- let mut programs = SelectorPrograms::new();- let sibling = programs.add(sibling);- registry.add_rule(RuleID(1), sibling, &programs);-- let item_routes = registry.routes_for(RoutingKey::Class(CLASS_ITEM));- let theme_routes = registry.routes_for(RoutingKey::Class(CLASS_THEME));- assert_eq!(registry.len(), 2, "one subject route and one canonical sibling route");- assert_eq!(registry.sibling_first_routes().len(), 1);- assert_eq!(item_routes.len(), 1);- assert_eq!(theme_routes, item_routes);- assert_eq!(registry.arrival_routes_for(RoutingKey::Class(CLASS_ITEM)), item_routes);- assert_eq!(registry.arrival_routes_for(RoutingKey::Class(CLASS_THEME)), item_routes);- }-- #[test]- fn selector_list_entries_have_independent_canonical_route_chains() {- const SELECTOR_ENTRY_COUNT: u32 = 64;-- // Model one rule containing `.class-0, .class-1, ...`. Each selector produces one route- // that cannot be canonicalized with a route from another selector in the list.- let mut builder = SelectorProgramBuilder::new();- for index in 0..SELECTOR_ENTRY_COUNT {- let class = builder.push_feature(FeatureTest::Class(StyleAtomID(1000 + index)));- builder.push_entry(class);- }- let mut programs = SelectorPrograms::new();- let program = programs.add(builder.finish());- let rule = RuleID(1);- let mut registry = RoutingRegistry::new();- registry.add_rule(rule, program, &programs);-- assert_eq!(registry.len(), SELECTOR_ENTRY_COUNT as usize);- assert_eq!(- registry.routes.canonical_route_heads.len(),- SELECTOR_ENTRY_COUNT as usize- );- assert!(- registry.routes.canonical_next.iter().all(Option::is_none),- "each selector entry should have its own one-route chain"- );- }-- #[test]- fn equal_flat_route_directories_share_and_reopen_independently() {- let key = RoutingKey::Class(CLASS_ITEM);- let mut pool = WeakPool::default();- let mut first = RouteDirectory::default();- let mut second = RouteDirectory::default();- for directory in [&mut first, &mut second] {- directory.push(key, RouteID::from_index(0));- directory.finish(&mut pool);- }- let (RouteDirectory::FlatAfterChange { data: Some(a) }, RouteDirectory::FlatAfterChange { data: Some(b) }) =- (&first, &second)- else {- panic!("directories were not flattened");- };- assert!(Arc::ptr_eq(a, b));- second.push(key, RouteID::from_index(1));- assert_eq!(first.get(key), &[RouteID::from_index(0)]);- assert_eq!(second.get(key), &[RouteID::from_index(0), RouteID::from_index(1)]);- second.finish(&mut pool);- second.finish(&mut pool);- drop(first);- assert_eq!(second.get(key), &[RouteID::from_index(0), RouteID::from_index(1)]);- }-- #[test]- fn a_flat_route_directory_reopens_for_program_changes() {- let first = single_entry(|builder| builder.push_feature(FeatureTest::Class(CLASS_ITEM)));- let second = single_entry(|builder| builder.push_feature(FeatureTest::Class(CLASS_THEME)));- let mut registry = RoutingRegistry::new();- let mut programs = SelectorPrograms::new();- let first = programs.add(first);- let second = programs.add(second);-- registry.add_rule(RuleID(1), first, &programs);- assert!(registry.finish_directories());- assert!(!registry.finish_directories());- assert_eq!(registry.routes_for(RoutingKey::Class(CLASS_ITEM)).len(), 1);-- registry.add_rule(RuleID(2), second, &programs);- assert_eq!(registry.routes_for(RoutingKey::Class(CLASS_ITEM)).len(), 1);- assert_eq!(registry.routes_for(RoutingKey::Class(CLASS_THEME)).len(), 1);- assert!(registry.finish_directories());- assert_eq!(registry.routes_for(RoutingKey::Class(CLASS_ITEM)).len(), 1);- assert_eq!(registry.routes_for(RoutingKey::Class(CLASS_THEME)).len(), 1);- }-- #[test]- fn route_directories_stay_mutable_while_rules_are_added() {- let program = single_entry(|builder| builder.push_feature(FeatureTest::Class(CLASS_ITEM)));- let mut registry = RoutingRegistry::new();- let mut programs = SelectorPrograms::new();- let program = programs.add(program);-- registry.add_rule(RuleID(1), program, &programs);- assert!(registry.finish_directories());- assert!(registry.directories_are_flat());-- for rule in 2..=8 {- registry.add_rule(RuleID(rule), program, &programs);- assert!(registry.finish_directories());- assert!(!registry.directories_are_flat());- }- assert!(registry.finish_directories());- assert!(registry.directories_are_flat());- }-- #[test]- fn distinct_structural_operators_have_distinct_routes() {- let structural = single_entry(|builder| {- let empty = builder.push(SelectorOp::Empty);- let first = builder.push(SelectorOp::NthPosition(NthPosition {- step: 0,- offset: 1,- from_end: false,- of_selector: None,- of_type: false,- }));- builder.push_compound(&[empty, first])- });- let mut registry = RoutingRegistry::new();- let mut programs = SelectorPrograms::new();- let structural = programs.add(structural);- registry.add_rule(RuleID(1), structural, &programs);-- let routes = registry.routes_for(RoutingKey::Structural);- assert_eq!(routes.len(), 2);- assert_ne!(- registry.route(routes[0]).selector_node,- registry.route(routes[1]).selector_node- );- }-- #[test]- fn the_running_program_total_tracks_what_the_programs_reserve() {- let mut programs = SelectorPrograms::new();- // Enough programs, of differing sizes, to reallocate the list several times over.- for index in 0..64_u32 {- let program = single_entry(|builder| {- let mut operands = vec![builder.push_feature(FeatureTest::Class(StyleAtomID(index + 1)))];- for extra in 0..index % 5 {- operands.push(builder.push_feature(FeatureTest::Class(StyleAtomID(extra + 100))));- }- builder.push_compound(&operands)- });- programs.add(program);- }- }-- #[test]- fn structurally_equal_selector_programs_share_dense_ir() {- let mut programs = SelectorPrograms::new();- let make_program = || single_entry(|builder| builder.push_feature(FeatureTest::Class(StyleAtomID(7))));-- let first = programs.add(make_program());- let second = programs.add(make_program());- assert_eq!(first, second);- let entry = programs.entry_id(first, 0);- assert_eq!(entry, programs.entry_id(second, 0));- assert_eq!(programs.len(), 1);-- let different = programs.add(single_entry(|builder| {- builder.push_feature(FeatureTest::Class(StyleAtomID(8)))- }));- assert_ne!(first, different);- assert_eq!(programs.len(), 2);- }-- #[test]- fn shared_selector_indices_detach_for_reclamation_and_reuse() {- let make_program = |atom| single_entry(|builder| builder.push_feature(FeatureTest::Class(StyleAtomID(atom))));- let mut first = SelectorPrograms::new();- let mut second = SelectorPrograms::new();-- for programs in [&mut first, &mut second] {- programs.add(make_program(7));- programs.add(make_program(8));- programs.share_indices();+pub(crate) fn attribute_value_matches<T: Copy + Into<u16>>(+ operator: crate::css::selector::AttributeMatchType,+ value: &[T],+ literal: &[u16],+ insensitive: bool,+) -> bool {+ use crate::css::selector::AttributeMatchType;+ match operator {+ AttributeMatchType::HasAttribute => true,+ AttributeMatchType::ExactValue => equals(value, literal, insensitive),+ AttributeMatchType::ContainsWord => {+ !literal.is_empty()+ && value+ .split(|unit| matches!((*unit).into(), 0x20 | 0x09 | 0x0A | 0x0C | 0x0D))+ .any(|token| equals(token, literal, insensitive))}- assert_eq!(first.program_index.as_ptr(), second.program_index.as_ptr());- assert_eq!(first.entry_locations.as_ptr(), second.entry_locations.as_ptr());- let entry = first.entry_id(SelectorProgramID(0), 0);- second.sweep_unreferenced(&[false, true]);- let recycled = second.add(make_program(9));- assert_eq!(recycled, SelectorProgramID(0));- assert_eq!(first.entry_location(entry), (SelectorProgramID(0), 0));- assert!(first.get(SelectorProgramID(0)) == &make_program(7));- assert!(second.get(recycled) == &make_program(9));- assert_eq!(first.add(make_program(7)), SelectorProgramID(0));- assert_eq!(second.add(make_program(9)), recycled);- assert_eq!(size_of::<Option<NonZeroU32>>(), 4);- assert_eq!(size_of::<Option<(NonZeroU32, u32)>>(), 8);- }-- #[test]- fn selector_entry_runs_keep_fragmented_recycled_identities() {- let consecutive = SelectorEntryIDs::from_entries(vec![EntryID(7), EntryID(8), EntryID(9)]);- assert!(matches!(consecutive, SelectorEntryIDs::Consecutive { .. }));- assert_eq!(- consecutive.iter().collect::<Vec<_>>(),- [EntryID(7), EntryID(8), EntryID(9)]- );-- let fragmented = SelectorEntryIDs::from_entries(vec![EntryID(1), EntryID(4), EntryID(5)]);- let cloned = fragmented.clone();- let (SelectorEntryIDs::Explicit(first), SelectorEntryIDs::Explicit(second)) = (&fragmented, &cloned) else {- panic!("fragmented entry identities need an explicit list");- };- assert!(Arc::ptr_eq(first, second));- assert_eq!(cloned.iter().collect::<Vec<_>>(), [EntryID(1), EntryID(4), EntryID(5)]);- assert_eq!(SelectorEntryIDs::from_entries(Vec::new()).len(), 0);- }-- #[test]- fn live_entry_identities_account_for_program_entry_storage() {- let make_program = |first: u32, count: u32| {- let mut builder = SelectorProgramBuilder::new();- for index in first..first + count {- let root = builder.push_feature(FeatureTest::Class(StyleAtomID(index)));- builder.push_entry(root);- }- builder.finish()- };- let check = |programs: &SelectorPrograms| {- let allocated_entries: usize = programs- .entry_ids_by_program- .iter()- .flatten()- .map(|entries| entries.len())- .sum();- assert_eq!(- programs.entry_locations.len() - programs.vacant_entries.len(),- allocated_entries- );- assert_eq!(programs.entry_locations.iter().flatten().count(), allocated_entries);- };- for mut programs in [SelectorPrograms::new(), SelectorPrograms::shared_across_documents()] {- check(&programs);- let first = programs.add(make_program(1, 5));- let retained = programs.add(make_program(10, 2));- assert_eq!(first, programs.add(make_program(1, 5)));- check(&programs);-- let mut referenced = vec![false; programs.len()];- referenced[retained.0 as usize] = true;- programs.sweep_unreferenced(&referenced);- check(&programs);- // Reuse only part of the vacant entry space, then exhaust it and grow again.- programs.add(make_program(20, 3));- check(&programs);- programs.add(make_program(30, 7));- check(&programs);- programs.sweep_unreferenced(&[]);- check(&programs);- programs.add(make_program(40, 1));- check(&programs);+ AttributeMatchType::StartsWithSegment => {+ equals(value, literal, insensitive)+ || (value.len() > literal.len()+ && value[literal.len()].into() == u16::from(b'-')+ && starts_with(value, literal, insensitive))}- }-- #[test]- fn process_programs_keep_transpose_sites_once_another_rule_or_document_routes_them() {- // NB: The pool is shared with every other test in the process; nothing else interns a class selector on this- // atom.- let make_program = || single_entry(|builder| builder.push_feature(FeatureTest::Class(StyleAtomID(9301))));- let mut first = SelectorPrograms::shared_across_documents();- let mut second = SelectorPrograms::shared_across_documents();- let first_id = first.add(make_program());- let second_id = second.add(make_program());- let Some(SelectorProgramStorage::Process(shared)) = first.programs[first_id.0 as usize].clone() else {- panic!("shared selector programs must have process storage");- };- let visit = |programs: &SelectorPrograms, program, rule| {- let mut sites = 0;- programs.for_each_transpose_entry_point(program, 0, rule, |_| sites += 1);- sites- };-- let sites = visit(&first, first_id, RuleID(1));- assert!(sites > 0);- // A document routing the same rule again, as rebuilding its routing does, keeps nothing.- assert_eq!(visit(&first, first_id, RuleID(1)), sites);- assert!(shared.transpose_sites.get().is_none());-- assert_eq!(visit(&second, second_id, RuleID(1)), sites);- assert!(shared.transpose_sites.get().is_some());- assert_eq!(visit(&first, first_id, RuleID(2)), sites);- }-- #[test]- fn process_programs_share_payload_and_its_memory_lifetime() {- let make_program = || single_entry(|builder| builder.push_feature(FeatureTest::Class(StyleAtomID(91))));-- let program_hash = SelectorPrograms::program_hash(&make_program());- let mut first = SelectorPrograms::shared_across_documents();- let mut second = SelectorPrograms::shared_across_documents();- let first_id = first.add(make_program());- let second_id = second.add(make_program());-- let (SelectorProgramStorage::Process(first_program), SelectorProgramStorage::Process(second_program)) = (- first.programs[first_id.0 as usize].as_ref().unwrap(),- second.programs[second_id.0 as usize].as_ref().unwrap(),- ) else {- panic!("shared selector programs must have process storage");- };- assert!(Arc::ptr_eq(first_program, second_program));- // The pool is shared with every other test running in the process, so this test only- // looks at its own program: nothing else interns a class selector on this atom.- assert_eq!(selector_program_pools().programs.live_values_under(program_hash), 1);-- drop(first);- assert_eq!(selector_program_pools().programs.live_values_under(program_hash), 1);- drop(second);- assert_eq!(selector_program_pools().programs.live_values_under(program_hash), 0);- }-- #[test]- fn selector_program_slots_are_reused_after_reclamation() {- let mut programs = SelectorPrograms::new();- let first = programs.add(single_entry(|builder| {- builder.push_feature(FeatureTest::Class(StyleAtomID(7)))- }));- let first_entry = programs.entry_id(first, 0);- let retained = programs.add(single_entry(|builder| {- builder.push_feature(FeatureTest::Class(StyleAtomID(8)))- }));-- let mut referenced = vec![false; programs.len()];- referenced[retained.0 as usize] = true;- programs.sweep_unreferenced(&referenced);- assert_eq!(programs.get(retained).entries().len(), 1);-- let reused = programs.add(single_entry(|builder| {- builder.push_feature(FeatureTest::Class(StyleAtomID(9)))- }));- assert_eq!(reused, first);- assert_eq!(programs.entry_id(reused, 0), first_entry);- assert_eq!(programs.len(), 2);- }-- #[test]- fn the_registry_stays_proportional_to_selector_input_incidence() {- let mut registry = RoutingRegistry::new();- let mut programs = SelectorPrograms::new();- for index in 0..200_u32 {- let program = single_entry(|builder| {- let class = builder.push_feature(FeatureTest::Class(StyleAtomID(1000 + index)));- let theme = builder.push_feature(FeatureTest::Class(CLASS_THEME));- let ancestor = builder.push(SelectorOp::Ancestor(theme));- builder.push_compound(&[class, ancestor])- });- let program = programs.add(program);- registry.add_rule(RuleID(index), program, &programs);+ AttributeMatchType::StartsWithString => !literal.is_empty() && starts_with(value, literal, insensitive),+ AttributeMatchType::EndsWithString => {+ !literal.is_empty()+ && value.len() >= literal.len()+ && equals(&value[value.len() - literal.len()..], literal, insensitive)}-- // Two inputs per rule, and the shared ancestor class collects all two hundred entries.- assert_eq!(registry.len(), 400);- assert_eq!(registry.routes_for(RoutingKey::Class(CLASS_THEME)).len(), 200);- assert_eq!(registry.routes_for(RoutingKey::Class(StyleAtomID(1007))).len(), 1);- assert_eq!(registry.routed_input_count(), 201);- }-- #[test]- fn routes_and_rules_share_one_subject_fact_record_per_entry() {- let mut programs = SelectorPrograms::new();- let program = single_entry(|builder| {- let target = builder.push_feature(FeatureTest::Class(StyleAtomID(7)));- let hovered = builder.push(SelectorOp::State(StateFact::Hover));- builder.push_compound(&[target, hovered])- });- let program = programs.add(program);- let mut registry = RoutingRegistry::new();- registry.add_rule(RuleID(1), program, &programs);- registry.add_rule(RuleID(2), program, &programs);-- assert_eq!(registry.len(), 2);- assert_ne!(- registry.rule_of(RouteID::from_index(0)),- registry.rule_of(RouteID::from_index(1))- );- assert_eq!(registry.routes.entry_facts.iter().flatten().count(), 1);- let first_route = RouteID::from_index(0);- for index in 1..registry.len() {- assert_eq!(- registry.subject_dispatch_of(RouteID::from_index(index)),- registry.subject_dispatch_of(first_route)- );- assert_eq!(- registry.subject_required_of(RouteID::from_index(index)),- registry.subject_required_of(first_route)- );+ AttributeMatchType::ContainsString => {+ !literal.is_empty()+ && value.len() >= literal.len()+ && (0..=value.len() - literal.len())+ .any(|start| equals(&value[start..start + literal.len()], literal, insensitive))}}+}- #[test]- fn routing_columns_keep_the_hot_header_compact() {- assert_eq!(size_of::<RouteHeader>(), 16);- assert_eq!(size_of::<RouteRange>(), 8);- }-- #[test]- fn a_relational_selector_answers_existentially_and_stops_at_the_first_witness() {- // .theme:has(> .item)- let program = single_entry(|builder| {- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let has = builder.push_relative_exists(RelativeQuery {- axis: RelativeAxis::Child,- compound: item,- driving_feature: None,- simple: true,- witness_is_below_the_axis: false,- match_in_shadow_tree: false,- });- let theme = builder.push_feature(FeatureTest::Class(CLASS_THEME));- builder.push_compound(&[theme, has])- });-- let mut fixture = Fixture::new();- // The root carries .theme and has two .item children; the first one answers it.- assert!(fixture.matches(&program, 0));- assert!(!fixture.matches(&program, 1), "an .item is not itself a .theme");- }-- #[test]- fn a_relational_selector_with_no_witness_is_false() {- // :has(> #nothing)- let program = single_entry(|builder| {- let id = builder.push_feature(FeatureTest::Id(StyleAtomID(4242)));- builder.push_relative_exists(RelativeQuery {- axis: RelativeAxis::Child,- compound: id,- driving_feature: None,- simple: true,- witness_is_below_the_axis: false,- match_in_shadow_tree: false,- })- });- let mut fixture = Fixture::new();- assert!(!fixture.matches(&program, 0));+fn equals<T: Copy + Into<u16>>(value: &[T], literal: &[u16], insensitive: bool) -> bool {+ if !insensitive {+ return value.len() == literal.len() && value.iter().zip(literal).all(|(&left, &right)| left.into() == right);}-- #[test]- fn a_relational_selector_transposes_witnesses_to_their_anchors() {- // .card:has(+ .selected)- let program = single_entry(|builder| {- let selected = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- let has = builder.push_relative_exists(RelativeQuery {- axis: RelativeAxis::NextSibling,- compound: selected,- driving_feature: Some(super::super::index::LocalFeatureKey::Class(CLASS_ITEM)),- simple: true,- witness_is_below_the_axis: false,- match_in_shadow_tree: false,- });- let card = builder.push_feature(FeatureTest::Class(CLASS_THEME));- builder.push_compound(&[card, has])- });-- let mut collected = Vec::new();- program.collect_transpose_entry_points(0, |site| {- collected.push((site.key, site.path.to_vec(), site.anchor));- });-- // The witness records its anchor step separately rather than folding it into the path, so- // routing can resolve the anchors before continuing.- let witness = collected+ value.len() == literal.len()+ && value.iter()- .find(|(key, _, _)| *key == RoutingKey::Class(CLASS_ITEM))- .expect("the witness compound is routed");- assert_eq!(- witness.1,- Vec::<InverseStep>::new(),- "the anchor step is not in the path"- );- let anchor = witness.2.expect("a witness carries its anchor");- assert_eq!(anchor.axis, RelativeAxis::NextSibling);- assert_eq!(anchor.anchor_dispatch, DispatchKey::Class(CLASS_THEME));-- assert!(- collected- .iter()- .any(|(key, path, anchor)| *key == RoutingKey::Class(CLASS_THEME)- && path.is_empty()- && anchor.is_none())- );- }-- #[test]- fn shadow_operators_consume_the_relation_they_name() {- let mut fixture = Fixture::new();- let host = fixture.nodes[0];- let slotted = fixture.nodes[1];- let shadow_root = fixture.nodes[3];- fixture.tree.set_shadow_root(host, shadow_root);- fixture.tree.set_assigned_slot(slotted, Some(fixture.nodes[2]));- fixture- .tree- .set_part_hosts(fixture.nodes[2], &[(StyleAtomID(77), host)]);-- let host_rule = single_entry(|builder| {- let any = builder.push_feature(FeatureTest::AnyElement);- builder.push(SelectorOp::Host(any))- });- assert!(- fixture.matches_in_shadow_tree(&host_rule, 0, 3),- "the host of the tree the rule is in is the host"- );- assert!(- !fixture.matches_in_shadow_tree(&host_rule, 1, 3),- "a DOM child of the host is not"- );- assert!(- !fixture.matches(&host_rule, 0),- "and a rule in the document scope names no host at all"- );-- let slotted_rule = single_entry(|builder| {- let any = builder.push_feature(FeatureTest::AnyElement);- builder.push(SelectorOp::Slotted(any))- });- assert!(fixture.matches(&slotted_rule, 1));- assert!(!fixture.matches(&slotted_rule, 3), "an unassigned node is not slotted");-- let part_rule = single_entry(|builder| builder.push(SelectorOp::Part(StyleAtomID(77))));- assert!(fixture.matches(&part_rule, 2));- assert!(!fixture.matches(&part_rule, 1));- }-- #[test]- fn a_host_guard_under_a_combinator_keeps_the_subject_in_its_scope() {- // `:host(.theme) > .item` reads the host, so it can leave its scope, but its subject is a- // child of the host in the shadow tree and never anything outside it.- let host_child = single_entry(|builder| {- let theme = builder.push_feature(FeatureTest::Class(CLASS_THEME));- let host = builder.push(SelectorOp::Host(theme));- let parent = builder.push(SelectorOp::Parent(host));- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- builder.push_compound(&[item, parent])- });- assert!(host_child.can_leave_its_scope());- assert!(!host_child.subject_can_leave_its_scope());-- // `:host .item`- let host_descendant = single_entry(|builder| {- let any = builder.push_feature(FeatureTest::AnyElement);- let host = builder.push(SelectorOp::Host(any));- let ancestor = builder.push(SelectorOp::Ancestor(host));- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- builder.push_compound(&[item, ancestor])- });- assert!(host_descendant.can_leave_its_scope());- assert!(!host_descendant.subject_can_leave_its_scope());-- // `:host(.theme)` names the host itself.- let host = single_entry(|builder| {- let theme = builder.push_feature(FeatureTest::Class(CLASS_THEME));- builder.push(SelectorOp::Host(theme))- });- assert!(host.can_leave_its_scope());- assert!(host.subject_can_leave_its_scope());-- // `::slotted(.item)` names a light-DOM element of the host.- let slotted = single_entry(|builder| {- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- builder.push(SelectorOp::Slotted(item))- });- assert!(slotted.can_leave_its_scope());- assert!(slotted.subject_can_leave_its_scope());-- // `.theme .item` reads nothing outside its scope.- let plain = single_entry(|builder| {- let theme = builder.push_feature(FeatureTest::Class(CLASS_THEME));- let ancestor = builder.push(SelectorOp::Ancestor(theme));- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- builder.push_compound(&[item, ancestor])- });- assert!(!plain.can_leave_its_scope());- assert!(!plain.subject_can_leave_its_scope());- }-- #[test]- fn a_generic_descendant_walk_does_not_pierce_a_shadow_root() {- let mut fixture = Fixture::new();- fixture.tree.set_shadow_root(fixture.nodes[0], fixture.nodes[3]);-- // .theme .item still means DOM ancestry; hosting changes nothing about it.- let program = single_entry(|builder| {- let theme = builder.push_feature(FeatureTest::Class(CLASS_THEME));- let ancestor = builder.push(SelectorOp::Ancestor(theme));- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- builder.push_compound(&[item, ancestor])- });- assert!(fixture.matches(&program, 1));- }-- #[test]- fn a_shadow_guard_on_the_subject_transposes_to_the_subject() {- // `:host(.theme)` and `::slotted(.item)` style the element they test. The match program- // evaluates them on the subject itself, so a change to what they test reaches that element- // and nothing else: taking the relation as a step would name the hosted tree or the slot,- // neither of which is the subject.- let host = single_entry(|builder| {- let theme = builder.push_feature(FeatureTest::Class(CLASS_THEME));- builder.push(SelectorOp::Host(theme))- });- assert_eq!(transpose_of(&host), vec![(RoutingKey::Class(CLASS_THEME), vec![])]);-- let slotted = single_entry(|builder| {- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- builder.push(SelectorOp::Slotted(item))- });- assert_eq!(transpose_of(&slotted), vec![(RoutingKey::Class(CLASS_ITEM), vec![])]);-- let part = single_entry(|builder| builder.push(SelectorOp::Part(StyleAtomID(77))));- assert_eq!(transpose_of(&part), vec![(RoutingKey::Part(StyleAtomID(77)), vec![])]);- }+ .zip(literal)+ .all(|(&left, &right)| fold(left.into()) == fold(right))+}- #[test]- fn a_shadow_guard_behind_a_combinator_transposes_through_its_own_relation() {- // `:host(.theme) .item` puts the subject inside the hosted tree, which no DOM-ancestry step- // reaches. The step to the hosted tree is what carries the change across the boundary.- let host = single_entry(|builder| {- let theme = builder.push_feature(FeatureTest::Class(CLASS_THEME));- let guard = builder.push(SelectorOp::Host(theme));- let ancestor = builder.push_ancestor(guard);- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- builder.push_compound(&[item, ancestor])- });- assert!(- transpose_of(&host).contains(&(- RoutingKey::Class(CLASS_THEME),- vec![InverseStep::HostedTree, InverseStep::Descendants]- )),- "a host change reaches the tree it hosts, not its DOM descendants"- );- }+fn starts_with<T: Copy + Into<u16>>(value: &[T], literal: &[u16], insensitive: bool) -> bool {+ value.len() >= literal.len() && equals(&value[..literal.len()], literal, insensitive)+}- #[test]- fn a_nested_shadow_guard_carries_its_compound_through_the_host() {- let host = single_entry(|builder| {- let any = builder.push_feature(FeatureTest::AnyElement);- let host = builder.push(SelectorOp::Host(any));- let alternate = builder.push_feature(FeatureTest::Class(StyleAtomID(202)));- let host_or_alternate = builder.push_any_of(&[host, alternate]);- let theme = builder.push_feature(FeatureTest::Class(CLASS_THEME));- let guard = builder.push_compound(&[host_or_alternate, theme]);- let ancestor = builder.push_ancestor(guard);- let item = builder.push_feature(FeatureTest::Class(CLASS_ITEM));- builder.push_compound(&[item, ancestor])- });- assert!(- transpose_of(&host).contains(&(- RoutingKey::Class(CLASS_THEME),- vec![InverseStep::HostedTree, InverseStep::Descendants]- )),- "a host nested in :is() carries its compound across the boundary"- );- }+#[cfg(test)]+mod tests {+ use super::*;#[test]fn an_plus_b_handles_the_boundary_forms() {@@ -8235,25 +488,4 @@ mod tests {assert!(!matches_an_plus_b(-1, 3, 4));assert!(matches_an_plus_b(1, 0, 5));}-- #[test]- fn an_plus_b_range_changes_are_decided_without_walking_the_range() {- let position = |step, offset| NthPosition {- step,- offset,- from_end: false,- of_selector: None,- of_type: false,- };-- assert!(!position(3, 0).could_change_from_range(1, 1, 2));- assert!(position(3, 0).could_change_from_range(2, 2, 3));- assert!(position(3, 0).could_change_from_range(3, 2, 3));- assert!(!position(1, 3).could_change_from_range(5, 3, 8));- assert!(position(1, 3).could_change_from_range(3, 1, 3));- assert!(!position(-1, 3).could_change_from_range(2, 1, 3));- assert!(position(-1, 3).could_change_from_range(3, 3, 4));- assert!(!position(1_000_000_000, 500_000_000).could_change_from_range(1, 1, 499_999_999));- assert!(position(1_000_000_000, 500_000_000).could_change_from_range(1, 1, 500_000_000));- }}diff --git a/Libraries/LibWeb/Rust/src/css/style/selector_analysis.rs b/Libraries/LibWeb/Rust/src/css/style/selector_analysis.rsnew file mode 100644index 00000000000..72b4379c8d8--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/selector_analysis.rs@@ -0,0 +1,474 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What the rule index reads of an entry's selector, from its components: which families of+//! buckets it is in, whether it revalidates, the ids it tests for, and the key a compound reached+//! by no name is bucketed by.++use super::StyleAtomID;+use super::component_matching::{CompoundTarget, EntrySelector, compound_target, mentions};+use super::index::DispatchKey;+use crate::css::selector::{+ Combinator, CompoundRef, PseudoClassType, PseudoElementType, PseudoElementValue, Selector, SelectorListView,+ SimpleSelector,+};+use crate::css::selector_arena::{Nesting, SheetNamespaces};+use smallvec::SmallVec;++/// What the rule index reads of one entry.+#[derive(Clone, Copy)]+pub(super) struct EntryFacts {+ pub(super) never_matches: bool,+ pub(super) scoped: bool,+ pub(super) revalidates: bool,+ pub(super) host: bool,+ pub(super) slotted: bool,+ pub(super) part: bool,+}++impl EntryFacts {+ pub(super) fn of(entry: EntrySelector<'_>) -> Self {+ let scoped = entry.scope().is_some();+ let subject = subject_compound(entry.selector);+ let first = subject.first_compound();+ let pseudo_element = match first.simple_selectors.first() {+ Some(SimpleSelector::PseudoElement(pseudo_element)) => Some(pseudo_element.pseudo_element),+ _ => None,+ };+ Self {+ never_matches: never_matches(&first),+ scoped,+ revalidates: scoped || revalidates(entry.selector),+ // NB: Asking the host is the wider of the two answers where the subject may be the+ // scoping root, which can be the host.+ host: scoped || names_the_host(&first),+ slotted: pseudo_element == Some(PseudoElementType::Slotted),+ part: pseudo_element == Some(PseudoElementType::Part),+ }+ }+}++/// The compound of `selector` an element matching it is the subject of: its first, or the one+/// left of a pseudo-element no element stands for.+pub(super) fn subject_compound(selector: Selector<'_>) -> Selector<'_> {+ let first = selector.first_compound();+ let transparent = matches!(compound_target(&first), CompoundTarget::Transparent);+ match (transparent, selector.left()) {+ (true, Some((Combinator::PseudoElement, left))) => left,+ _ => selector,+ }+}++/// Whether the compound tests something no element satisfies, as a `:has()`, `:is()` or+/// `:where()` all of whose arguments were invalid does.+pub(crate) fn never_matches(compound: &CompoundRef<'_>) -> bool {+ compound.simple_selectors.iter().any(|simple| match simple {+ SimpleSelector::PseudoClass(pseudo_class) => match pseudo_class.pseudo_class {+ PseudoClassType::Has | PseudoClassType::Is | PseudoClassType::Where => {+ pseudo_class.argument_selector_list.is_empty()+ }+ PseudoClassType::State => pseudo_class.identifier_identity.is_none(),+ _ => false,+ },+ SimpleSelector::Invalid(_) => true,+ _ => false,+ })+}++/// Whether a compound can match the featureless host of the tree its rule is in: one of its+/// simple selectors names the host or the scoping root, and every other one may match the host.+fn names_the_host(compound: &CompoundRef<'_>) -> bool {+ let names = |simple: &SimpleSelector<'_>| {+ mentions(simple, &|simple| match simple {+ SimpleSelector::PseudoClass(pseudo_class) => {+ matches!(+ pseudo_class.pseudo_class,+ PseudoClassType::Host | PseudoClassType::Scope+ )+ }+ SimpleSelector::Nesting(Nesting::Root | Nesting::Scope) => true,+ _ => false,+ })+ };+ compound.simple_selectors.iter().any(|simple| names(&simple))+}++/// Whether a selector can tell apart two elements that agree on the style sharing key: their tag,+/// namespace, classes and states, the absence of an id a selector tests for, and parents that are+/// the same element or themselves shared a style, all the way up. What it reads of the elements+/// and their ancestors beyond that key, such as attributes, siblings and tree position, it has to+/// be evaluated for.+fn revalidates(selector: Selector<'_>) -> bool {+ let mut compound = Some(subject_compound(selector));+ while let Some(current) = compound {+ if current.is_relative_anchor() {+ return true;+ }+ if current+ .first_compound()+ .simple_selectors+ .iter()+ .any(|simple| simple_revalidates(&simple))+ {+ return true;+ }+ compound = match current.left() {+ None => None,+ Some((Combinator::ImmediateChild | Combinator::Descendant, left)) => Some(left),+ Some(_) => return true,+ };+ }+ false+}++fn simple_revalidates(simple: &SimpleSelector<'_>) -> bool {+ let any = |list: SelectorListView<'_>| list.iter().any(revalidates);+ match simple {+ SimpleSelector::Universal(_)+ | SimpleSelector::TagName(_)+ | SimpleSelector::Id(_)+ | SimpleSelector::Class(_) => false,+ SimpleSelector::PseudoClass(pseudo_class) => match pseudo_class.pseudo_class {+ PseudoClassType::Root => false,+ PseudoClassType::Is | PseudoClassType::Where | PseudoClassType::Not => {+ any(pseudo_class.argument_selector_list)+ }+ kind => super::compiler::state_fact_for(kind).is_none(),+ },+ SimpleSelector::Nesting(Nesting::Rule(parent)) => any(*parent),+ _ => true,+ }+}++/// Collect the ids `selector`, which does not revalidate, tests for, in each form an element+/// carries them.+pub(super) fn collect_tested_ids(selector: Selector<'_>, ids: &mut Vec<StyleAtomID>) {+ let atoms = super::process_atoms();+ for current in subject_compound(selector).compounds() {+ for simple in current.simple_selectors.iter() {+ let simple = &simple;+ match simple {+ SimpleSelector::Id(name) => {+ ids.push(name.name);+ if !name.is_ascii_lowercase {+ ids.push(atoms.ascii_lowercase(name.name));+ }+ }+ SimpleSelector::PseudoClass(pseudo_class)+ if matches!(+ pseudo_class.pseudo_class,+ PseudoClassType::Is | PseudoClassType::Where | PseudoClassType::Not+ ) =>+ {+ for selector in pseudo_class.argument_selector_list {+ collect_tested_ids(selector, ids);+ }+ }+ SimpleSelector::Nesting(Nesting::Rule(parent)) => {+ for selector in *parent {+ collect_tested_ids(selector, ids);+ }+ }+ _ => {}+ }+ }+ }+}++/// A key only elements the subject compound of `selector` can match carry, for a compound reached+/// by no name: a state, being a heading, or being the document element.+pub(super) fn state_dispatch_key(selector: Selector<'_>) -> Option<DispatchKey> {+ let compound = subject_compound(selector).first_compound();+ compound.simple_selectors.iter().find_map(|simple| match simple {+ SimpleSelector::PseudoClass(pseudo_class) => match pseudo_class.pseudo_class {+ PseudoClassType::Heading => Some(DispatchKey::Heading),+ PseudoClassType::Root => Some(DispatchKey::Root),+ kind => super::compiler::state_fact_for(kind).map(DispatchKey::State),+ },+ _ => None,+ })+}++/// How many keys a compound may carry before checking them all costs more than the rejections save.+const MAX_DISPATCH_KEYS: usize = 8;++/// The keys an element matching the subject compound of `selector` carries one of, which its entry+/// is bucketed by, or none where it carries none in particular: the universal bucket's.+///+/// A name not written in ASCII lowercase is bucketed under its lowercase form too, which a+/// quirks-mode document, an HTML element's tag name and an HTML attribute name are carried in.+pub(super) fn subject_dispatch_keys(selector: Selector<'_>) -> SmallVec<[DispatchKey; 4]> {+ let mut keys = compound_dispatch_keys(&subject_compound(selector).first_compound()).unwrap_or_default();+ keys.sort_unstable();+ keys.dedup();+ keys+}++/// The cheapest set of keys one of which every element matching `compound` carries.+fn compound_dispatch_keys(compound: &CompoundRef<'_>) -> Option<SmallVec<[DispatchKey; 4]>> {+ compound+ .simple_selectors+ .iter()+ .filter_map(|simple| simple_dispatch_keys(&simple))+ .min_by_key(|keys| {+ keys.iter()+ .map(|&key| u32::from(dispatch_selectivity(key)) + 1)+ .sum::<u32>()+ })+}++fn simple_dispatch_keys(simple: &SimpleSelector<'_>) -> Option<SmallVec<[DispatchKey; 4]>> {+ let atoms = super::process_atoms();+ let both = |make: fn(StyleAtomID) -> DispatchKey, name: StyleAtomID, lowercase: bool| {+ let mut keys: SmallVec<[DispatchKey; 4]> = smallvec::smallvec![make(name)];+ if !lowercase {+ keys.push(make(atoms.ascii_lowercase(name)));+ }+ Some(keys)+ };+ let alternatives = |list: SelectorListView<'_>| {+ let mut keys: SmallVec<[DispatchKey; 4]> = SmallVec::new();+ for selector in list {+ keys.extend(compound_dispatch_keys(&selector.first_compound())?);+ if keys.len() > MAX_DISPATCH_KEYS {+ return None;+ }+ }+ (!keys.is_empty()).then_some(keys)+ };+ match simple {+ SimpleSelector::Id(name) => both(DispatchKey::Id, name.name, name.is_ascii_lowercase),+ SimpleSelector::Class(name) => both(DispatchKey::Class, name.name, name.is_ascii_lowercase),+ SimpleSelector::TagName(name) => both(DispatchKey::TagName, name.name, name.name_is_ascii_lowercase),+ SimpleSelector::Attribute(attribute) => both(+ DispatchKey::AttributeName,+ attribute.qualified_name.name,+ attribute.qualified_name.name_is_ascii_lowercase,+ )+ // NB: A name qualified by a namespace is carried qualified, which the components do not hold.+ .filter(|_| {+ matches!(+ attribute.qualified_name.namespace_type,+ crate::css::selector::NamespaceType::Default | crate::css::selector::NamespaceType::None+ )+ }),+ SimpleSelector::PseudoClass(pseudo_class) => match pseudo_class.pseudo_class {+ PseudoClassType::Is | PseudoClassType::Where => alternatives(pseudo_class.argument_selector_list),+ PseudoClassType::Host => pseudo_class+ .argument_selector_list+ .single()+ .and_then(|argument| compound_dispatch_keys(&argument.first_compound())),+ PseudoClassType::State if !pseudo_class.identifier_identity.is_none() => {+ Some(smallvec::smallvec![DispatchKey::CustomState(+ pseudo_class.identifier_identity+ )])+ }+ // NB: A state without a posting names nothing to find its elements by, and admitting it+ // would take the compound away from names that do.+ kind => super::compiler::state_fact_for(kind)+ .filter(|fact| fact.has_selector_posting())+ .map(|fact| smallvec::smallvec![DispatchKey::State(fact)]),+ },+ SimpleSelector::PseudoElement(pseudo_element) => match pseudo_element.value {+ PseudoElementValue::CompoundSelector(argument)+ if pseudo_element.pseudo_element == PseudoElementType::Slotted =>+ {+ compound_dispatch_keys(&argument.first_compound())+ }+ _ if pseudo_element.pseudo_element == PseudoElementType::Part => pseudo_element+ .identifier_identities+ .first()+ .map(|&part| smallvec::smallvec![DispatchKey::Part(part)]),+ _ => None,+ },+ SimpleSelector::Nesting(Nesting::Rule(parent)) => alternatives(*parent),+ _ => None,+ }+}++/// How selective a dispatch key is expected to be, lowest first.+pub(super) fn dispatch_selectivity(key: DispatchKey) -> u8 {+ match key {+ DispatchKey::Part(_) | DispatchKey::CustomState(_) | DispatchKey::Id(_) => 0,+ DispatchKey::Class(_) => 1,+ DispatchKey::AttributeName(_) => 2,+ DispatchKey::TagName(_) => 3,+ DispatchKey::Directionality(_) => 4,+ _ => 5,+ }+}++/// What the host and the arrival routing ask of a document's selectors: the attribute names they+/// test, those whose values they read as text, whether they test `:local-link`, and what an element+/// arriving has to carry to reach the anchor of one of their `:has()`.+#[derive(Clone, Default)]+pub(in crate::css::style) struct SelectorSummary {+ pub(super) tested_attribute_names: Vec<StyleAtomID>,+ pub(super) attribute_value_text_names: Vec<StyleAtomID>,+ pub(super) tests_local_link: bool,+ pub(super) relational_arrival_keys: Vec<DispatchKey>,+}++impl SelectorSummary {+ /// The summary of the selectors of `list`, inside the `@scope` levels `scope`.+ pub(super) fn of(list: SelectorListView<'_>, scope: Option<&super::bridge::BoundScopeChain>) -> Self {+ let mut summary = Self::default();+ for selector in list {+ summary.add_selector(selector, false);+ }+ for bound in scope+ .into_iter()+ .flat_map(|scope| scope.roots.iter().chain(&scope.limits))+ {+ let selector = bound.view();+ summary.add_selector(selector, false);+ }+ summary+ }++ fn add_selector(&mut self, selector: Selector<'_>, in_argument: bool) {+ for current in selector.compounds() {+ for simple in current.simple_selectors.iter() {+ self.add_simple(&simple, selector.namespaces(), in_argument);+ }+ }+ }++ fn add_list(&mut self, list: SelectorListView<'_>, in_argument: bool) {+ for selector in list {+ self.add_selector(selector, in_argument);+ }+ }++ fn arrival_key(&mut self, in_argument: bool, key: DispatchKey) {+ if in_argument && !self.relational_arrival_keys.contains(&key) {+ self.relational_arrival_keys.push(key);+ }+ }++ fn add_simple(&mut self, simple: &SimpleSelector<'_>, namespaces: SheetNamespaces<'_>, in_argument: bool) {+ let atoms = super::process_atoms();+ let forms = |name: StyleAtomID, lowercase: bool| -> SmallVec<[StyleAtomID; 2]> {+ match lowercase {+ true => smallvec::smallvec![name],+ false => smallvec::smallvec![name, atoms.ascii_lowercase(name)],+ }+ };+ match simple {+ SimpleSelector::Universal(_) => self.arrival_key(in_argument, DispatchKey::Structural),+ SimpleSelector::TagName(name) => {+ for form in forms(name.name, name.name_is_ascii_lowercase) {+ self.arrival_key(in_argument, DispatchKey::TagName(form));+ }+ }+ SimpleSelector::Id(name) => {+ for form in forms(name.name, name.is_ascii_lowercase) {+ self.arrival_key(in_argument, DispatchKey::Id(form));+ }+ }+ SimpleSelector::Class(name) => {+ for form in forms(name.name, name.is_ascii_lowercase) {+ self.arrival_key(in_argument, DispatchKey::Class(form));+ }+ }+ SimpleSelector::Attribute(attribute) => {+ // `[*|x]` tests the name qualified by no namespace, `[ns|x]` the one qualified by the+ // namespace the prefix names, and `[x]` the bare local name.+ let qualifier = match attribute.qualified_name.namespace_type {+ crate::css::selector::NamespaceType::Any => Some(StyleAtomID::NONE),+ crate::css::selector::NamespaceType::Named => {+ match namespaces.namespace_of(attribute.qualified_name.namespace) {+ Some(namespace) => Some(namespace),+ None => return,+ }+ }+ _ => None,+ };+ // NB: The selector's arena leases the qualified names too, which keeps them live+ // while the rule is.+ let names: SmallVec<[StyleAtomID; 2]> = forms(+ attribute.qualified_name.name,+ attribute.qualified_name.name_is_ascii_lowercase,+ )+ .into_iter()+ .map(|name| match qualifier {+ Some(namespace) => super::AtomLease::acquire_qualified(atoms, namespace, name).atom(),+ None => name,+ })+ .collect();+ let reads_text = attribute.match_type != crate::css::selector::AttributeMatchType::HasAttribute+ && (attribute.match_type != crate::css::selector::AttributeMatchType::ExactValue+ || attribute.case_type == crate::css::selector::AttributeCaseType::Insensitive+ || attribute.names_a_legacy_case_insensitive_attribute);+ for &name in &names {+ if !self.tested_attribute_names.contains(&name) {+ self.tested_attribute_names.push(name);+ }+ if reads_text && !self.attribute_value_text_names.contains(&name) {+ self.attribute_value_text_names.push(name);+ }+ self.arrival_key(in_argument, DispatchKey::AttributeName(name));+ }+ }+ SimpleSelector::PseudoClass(pseudo_class) => {+ let list = pseudo_class.argument_selector_list;+ match pseudo_class.pseudo_class {+ PseudoClassType::Has => self.add_list(list, true),+ PseudoClassType::State if !pseudo_class.identifier_identity.is_none() => {+ self.arrival_key(in_argument, DispatchKey::CustomState(pseudo_class.identifier_identity));+ }+ PseudoClassType::Lang => self.arrival_key(in_argument, DispatchKey::Language),+ // NB: Which direction `:dir()` names is a fact of the tree's shape as an arrival+ // sees it.+ PseudoClassType::Root+ | PseudoClassType::Empty+ | PseudoClassType::Scope+ | PseudoClassType::Heading+ | PseudoClassType::Dir => self.arrival_key(in_argument, DispatchKey::Structural),+ kind => {+ if let Some(fact) = super::compiler::state_fact_for(kind) {+ self.tests_local_link |= fact == super::input_types::StateFact::LocalLink;+ self.arrival_key(in_argument, DispatchKey::State(fact));+ }+ if reads_position(pseudo_class) {+ self.arrival_key(in_argument, DispatchKey::Structural);+ }+ self.add_list(list, in_argument);+ }+ }+ }+ SimpleSelector::PseudoElement(pseudo_element) => match pseudo_element.value {+ PseudoElementValue::CompoundSelector(argument) => self.add_selector(argument, in_argument),+ _ if pseudo_element.pseudo_element == PseudoElementType::Part => {+ for &part in pseudo_element.identifier_identities {+ self.arrival_key(in_argument, DispatchKey::Part(part));+ }+ }+ _ => {}+ },+ SimpleSelector::Nesting(Nesting::Rule(parent)) => self.add_list(*parent, in_argument),+ SimpleSelector::Nesting(_) => self.arrival_key(in_argument, DispatchKey::Structural),+ SimpleSelector::Invalid(_) => {}+ }+ }+}++/// Whether a pseudo-class reads where the element stands among its siblings.+fn reads_position(pseudo_class: &crate::css::selector::PseudoClassSelector<'_>) -> bool {+ matches!(+ pseudo_class.pseudo_class,+ PseudoClassType::FirstChild+ | PseudoClassType::LastChild+ | PseudoClassType::OnlyChild+ | PseudoClassType::FirstOfType+ | PseudoClassType::LastOfType+ | PseudoClassType::OnlyOfType+ | PseudoClassType::NthChild+ | PseudoClassType::NthLastChild+ | PseudoClassType::NthOfType+ | PseudoClassType::NthLastOfType+ )+}diff --git a/Libraries/LibWeb/Rust/src/css/style/selector_evaluation.rs b/Libraries/LibWeb/Rust/src/css/style/selector_evaluation.rsindex d239ca90b1e..4281ac73b01 100644--- a/Libraries/LibWeb/Rust/src/css/style/selector_evaluation.rs+++ b/Libraries/LibWeb/Rust/src/css/style/selector_evaluation.rs@@ -4,104 +4,77 @@* SPDX-License-Identifier: BSD-2-Clause*/-//! The one interpreter of compiled selector programs.+//! What selectors are matched against: a subject holding the elements and the facts a selector+//! tests, and the evaluator walking selector components over it.//!-//! A program is evaluated against a subject: whatever holds the elements and the facts a selector-//! tests. The style engine's subject reads its own storage, and the DOM query subject reads the live-//! DOM. Every matching rule lives here, so two subjects can differ in what their storage holds and-//! never in what a selector means.+//! The style engine's subject reads its own storage, and the DOM query subject reads the live DOM.+//! Every matching rule lives in the evaluator, so two subjects can differ in what their storage+//! holds and never in what a selector means.//!//! A subject brings its accelerations along as hooks. A hook can only skip work: each default is//! the answer the evaluation reaches without the shortcut.-use std::convert::Infallible;-use smallvec::SmallVec;use super::index::StyleAtomID;-use super::instrumentation::Counter;-use super::instrumentation::Counters;+use super::input_types::StateFact;use super::relative_selector::RelativeAxis;-use super::relative_selector::RelativeQueryID;-use super::selector::AtomSpace;-use super::selector::AttributeCase;-use super::selector::AttributeOperator;-use super::selector::AttributeTest;-use super::selector::FeatureTest;-use super::selector::Incomplete;-use super::selector::NamespaceTest;use super::selector::NthPosition;-use super::selector::SelectorNodeID;-use super::selector::SelectorOp;-use super::selector::SelectorProgram;-use super::selector::ValueStateTestKind;-use super::selector::attribute_value_matches;-use super::selector::matches_an_plus_b;-use super::transaction::StateFact;use super::tree::StyleNodeID;use crate::css::css_tokenizer::TokenizerInput;-use crate::css::selector::language_range_matches_tag;--/// Where an evaluation reports how much work it did.-pub(crate) trait CounterSink {- fn bump(&self, counter: Counter);-}--impl CounterSink for Counters {- fn bump(&self, counter: Counter) {- Counters::bump(self, counter);- }-}--/// A subject that counts nothing.-impl CounterSink for () {- fn bump(&self, _counter: Counter) {}-}--/// Why a subject could not answer, refined by the scan that asked.-///-/// A scan over siblings or descendants that stops at a node its subject cannot read still knows the-/// rest of the range it would have read, which lets its caller widen the question to exactly that.-pub(crate) trait ScanIncomplete<N>: Copy {- /// The same, reported by a sibling scan that reached `sibling` and would have continued up to- /// `last_exclusive`, or to the end of the sequence when that is none.- #[must_use]- fn in_sibling_scan(self, sibling: N, last_exclusive: Option<N>) -> Self;- /// The same, reported by a scan of `root`'s descendants that reached `candidate`.- #[must_use]- fn in_descendant_scan(self, root: N, candidate: N) -> Self;-}--impl ScanIncomplete<StyleNodeID> for Incomplete {- fn in_sibling_scan(self, sibling: StyleNodeID, last_exclusive: Option<StyleNodeID>) -> Self {- match self {- Self::MissingFacts(missing) if missing == sibling => Self::MissingSiblingFacts {- first: sibling,- last_exclusive,- },- other => other,+/// Visit the candidate witnesses of a relative selector along `axis` from `anchor` in `tree`, in tree+/// order, until `visit` returns false.+pub(crate) fn walk_relative_axis<T: SelectorTree>(+ tree: T,+ axis: RelativeAxis,+ below_the_axis: bool,+ anchor: T::Node,+ mut visit: impl FnMut(T::Node) -> bool,+) {+ // Visit the subtree of `root`, `root` itself included when `inclusive`, until `visit` returns false.+ fn visit_subtree<T: SelectorTree>(+ tree: T,+ root: T::Node,+ inclusive: bool,+ visit: &mut impl FnMut(T::Node) -> bool,+ ) -> bool {+ if inclusive && !visit(root) {+ return false;}- }-- fn in_descendant_scan(self, root: StyleNodeID, candidate: StyleNodeID) -> Self {- match self {- Self::MissingFacts(missing) if missing == candidate => {- Self::MissingDescendantFacts { root, first: candidate }+ let mut descendant = tree.next_in_subtree(root, root);+ while let Some(candidate) = descendant {+ if !visit(candidate) {+ return false;}- other => other,+ descendant = tree.next_in_subtree(candidate, root);}- }-}--/// A subject that can always answer.-impl<N> ScanIncomplete<N> for Infallible {- fn in_sibling_scan(self, _sibling: N, _last_exclusive: Option<N>) -> Self {- match self {}+ true}- fn in_descendant_scan(self, _root: N, _candidate: N) -> Self {- match self {}+ let (first, every_sibling, subtree) = match axis {+ RelativeAxis::Descendant => {+ visit_subtree(tree, anchor, false, &mut visit);+ return;+ }+ RelativeAxis::Child => (tree.first_child(anchor), true, false),+ RelativeAxis::NextSibling => (tree.next_sibling(anchor), false, false),+ RelativeAxis::FollowingSibling => (tree.next_sibling(anchor), true, false),+ // The witness lies under the sibling rather than being it, so the sibling's whole subtree is the+ // candidate range.+ RelativeAxis::NextSiblingSubtree => (tree.next_sibling(anchor), false, true),+ RelativeAxis::FollowingSiblingSubtree => (tree.next_sibling(anchor), true, true),+ };+ let mut sibling = first;+ while let Some(candidate) = sibling {+ let proceed = match subtree {+ true => visit_subtree(tree, candidate, !below_the_axis, &mut visit),+ false => visit(candidate),+ };+ if !proceed || !every_sibling {+ return;+ }+ sibling = tree.next_sibling(candidate);}}@@ -117,16 +90,6 @@ pub(crate) trait SelectorTree: Copy {fn previous_sibling(self, node: Self::Node) -> Option<Self::Node>;fn next_sibling(self, node: Self::Node) -> Option<Self::Node>;fn first_child(self, parent: Self::Node) -> Option<Self::Node>;- /// The first of a node's inclusive siblings, which is the node itself when it has none.- fn first_sibling(self, node: Self::Node) -> Self::Node;-- /// A node's inclusive siblings, in tree order.- fn inclusive_siblings(self, node: Self::Node) -> impl Iterator<Item = Self::Node> {- std::iter::successors(Some(self.first_sibling(node)), move |&sibling| {- self.next_sibling(sibling)- })- }-/// The parent in the tree as it stands now. Scope, slot and relational walks read it even where/// the combinators read an earlier state of the tree.fn live_parent(self, node: Self::Node) -> Option<Self::Node> {@@ -169,61 +132,6 @@ pub(crate) trait SelectorTree: Copy {None}- /// Visit the candidate witnesses of a relative selector along `axis` from `anchor`, in tree- /// order, until `visit` returns false.- fn for_each_on_axis(- self,- axis: RelativeAxis,- below_the_axis: bool,- anchor: Self::Node,- mut visit: impl FnMut(Self::Node) -> bool,- ) {- // Visit the subtree of `root`, `root` itself included when `inclusive`, until `visit` returns false.- fn visit_subtree<T: SelectorTree>(- tree: T,- root: T::Node,- inclusive: bool,- visit: &mut impl FnMut(T::Node) -> bool,- ) -> bool {- if inclusive && !visit(root) {- return false;- }- let mut descendant = tree.next_in_subtree(root, root);- while let Some(candidate) = descendant {- if !visit(candidate) {- return false;- }- descendant = tree.next_in_subtree(candidate, root);- }- true- }-- let (first, every_sibling, subtree) = match axis {- RelativeAxis::Descendant => {- visit_subtree(self, anchor, false, &mut visit);- return;- }- RelativeAxis::Child => (self.first_child(anchor), true, false),- RelativeAxis::NextSibling => (self.next_sibling(anchor), false, false),- RelativeAxis::FollowingSibling => (self.next_sibling(anchor), true, false),- // The witness lies under the sibling rather than being it, so the sibling's whole subtree is the- // candidate range.- RelativeAxis::NextSiblingSubtree => (self.next_sibling(anchor), false, true),- RelativeAxis::FollowingSiblingSubtree => (self.next_sibling(anchor), true, true),- };- let mut sibling = first;- while let Some(candidate) = sibling {- let proceed = match subtree {- true => visit_subtree(self, candidate, !below_the_axis, &mut visit),- false => visit(candidate),- };- if !proceed || !every_sibling {- return;- }- sibling = self.next_sibling(candidate);- }- }-/// The slot an element is assigned to.fn assigned_slot_of(self, _node: Self::Node) -> Option<Self::Node> {None@@ -235,7 +143,7 @@ pub(crate) trait SelectorTree: Copy {}}-/// What a feature test reads of one element. Names are atoms of the program's atom space.+/// What a feature test reads of one element. Names are process atoms.pub(crate) trait ElementFeatures {type Attribute: Copy;@@ -248,64 +156,33 @@ pub(crate) trait ElementFeatures {fn attributes_named(&self, name: StyleAtomID, any_namespace: bool) -> impl Iterator<Item = Self::Attribute> + '_;}-/// Whether an element passes one feature test. `value_matches` compares an attribute's value with the one the test-/// names, ASCII case-insensitively when it is told to.-pub(crate) fn matches_feature<E: ElementFeatures>(- element: &E,- test: FeatureTest,- mut value_matches: impl FnMut(AttributeTest, E::Attribute, bool) -> bool,-) -> bool {- // https://html.spec.whatwg.org/multipage/semantics-other.html#case-sensitivity-of-selectors- // When comparing a CSS element type selector to the names of HTML elements in HTML documents, the CSS element type- // selector must first be converted to ASCII lowercase. The same selector when compared to other elements must be- // compared according to its original case. In both cases, to match, the values must be identical to each other- // (and therefore the comparison is case sensitive).- //- // When comparing the name part of a CSS attribute selector to the names of attributes on HTML elements in HTML- // documents, the name part of the CSS attribute selector must first be converted to ASCII lowercase. The same- // selector when compared to other attributes must be compared according to its original case. In both cases, the- // comparison is case-sensitive.- //- // NB: A test's folding namespace is the HTML namespace in an HTML document, and none anywhere else.- let folds =- |fold_in_namespace: StyleAtomID| !fold_in_namespace.is_none() && element.namespace_is(fold_in_namespace);- match test {- FeatureTest::AnyElement => true,- FeatureTest::Namespace(NamespaceTest::None) => element.namespace_is(StyleAtomID::NONE),- FeatureTest::Namespace(NamespaceTest::Named(namespace)) => element.namespace_is(namespace),- FeatureTest::TagName(tag) => element.local_name_is(match folds(tag.fold_in_namespace) {- true => tag.folded,- false => tag.written,- }),- FeatureTest::Id(id) => element.has_id(id),- FeatureTest::Class(class) => element.has_class(class),- FeatureTest::Attribute(test) => {- let insensitive = match test.case {- AttributeCase::Sensitive => false,- AttributeCase::Insensitive => true,- AttributeCase::InsensitiveForNamespace(namespace) => element.namespace_is(namespace),- };- let name = match folds(test.fold_in_namespace) {- true => test.folded,- false => test.name,- };- // `[*|x]` names one attribute per namespace the element carries `x` in, and the test holds when any of- // them satisfies it.- element- .attributes_named(name, test.any_namespace)- .any(|attribute| value_matches(test, attribute, insensitive))- }- }+/// What a selector read of how an element stands among its siblings, or of whether it is empty: what a change to+/// its siblings or children can move the answer of.+#[derive(Clone, Copy, PartialEq, Eq, Debug)]+pub(crate) enum StructuralRead {+ /// The element's previous sibling, across a `+`.+ PreviousSibling,+ /// The element's earlier siblings, across a `~`.+ EarlierSiblings,+ /// Where the element stands among its siblings: counted from the end, among those of its type, and in a way that+ /// tells more than whether it stands first where `beyond_edge`.+ Position {+ from_end: bool,+ of_type: bool,+ beyond_edge: bool,+ },+ /// Whether the element is `:empty`.+ Emptiness,+ /// Where the element stands among its siblings, for a value of its style or of a pseudo-element's.+ SiblingPositionValue,}-/// The elements a selector program is evaluated against, and their facts.+/// The elements a selector is matched against, and their facts.////// Facts are read through a row, which a subject fetches once per element and the evaluator then-/// asks every test of. Names are atoms of the program's own atom space. A subject answers what its+/// asks every test of. Names are process atoms. A subject answers what its/// storage holds, and nothing else: which name, case or namespace a test compares is decided here.pub(crate) trait SelectorSubject {- /// The atoms the subject's names are keyed by, which are the only ones a program it evaluates can hold.- type Atoms: AtomSpace;type Node: Copy + Eq;type Tree: SelectorTree<Node = Self::Node>;type Row: Copy;@@ -313,17 +190,12 @@ pub(crate) trait SelectorSubject {type Features<'s>: ElementFeatures<Attribute = Self::Attribute>whereSelf: 's;- type Incomplete: ScanIncomplete<Self::Node>;- type Counters: CounterSink;- /// Where a subject keeps one sibling sequence's preceding-sibling progress.- type PrefixSlot: Copy;- /// Whether the subject remembers how many siblings an `of S` positional test counts, through- /// `sibling_count_of` and `record_sibling_count_of`.- const REMEMBERS_SIBLING_COUNTS_OF_SELECTORS: bool = false;-+ type Incomplete: Copy;fn tree(&self) -> Self::Tree;fn row(&mut self, node: Self::Node) -> Result<Self::Row, Self::Incomplete>;+ /// Have the features of `row` answer for its attributes, which a test asks before it reads them.+ fn read_attributes(&mut self, _row: Self::Row) {}fn features(&self, row: Self::Row) -> Self::Features<'_>;/// Whether two elements have the same local name and namespace.fn same_type(&self, row: Self::Row, other: Self::Row) -> bool;@@ -347,6 +219,7 @@ pub(crate) trait SelectorSubject {false}+ /// Whether the element carries the part name `part` in its own tree.fn has_part(&self, _row: Self::Row, _part: StyleAtomID) -> bool {false}@@ -374,116 +247,88 @@ pub(crate) trait SelectorSubject {// Accelerations. Each default is what the evaluation does without one.- /// Whether `node` can possibly match the compound at `compound`.- fn may_match(&self, _program: &SelectorProgram<Self::Atoms>, _compound: SelectorNodeID, _node: Self::Node) -> bool {+ /// Whether [`Self::may_match_required`] rejects elements, so that a walk up has the bits a compound requires+ /// worked out at all.+ const FILTERS_BY_REQUIRED_DISPATCH_BLOOM: bool = false;++ /// Whether `node` can possibly carry every dispatch key whose bloom bits `required` holds.+ fn may_match_required(&self, _required: u64, _node: Self::Node) -> bool {true}- /// Whether answers of transitive relations may be remembered under these bindings.- fn remembers_relations(&self, _bindings: &SelectorBindings<Self::Node>) -> bool {- false+ /// The element's 1-based index in the sequence a positional test with no `of S` counts.+ fn sibling_index(&mut self, _position: NthPosition, _node: Self::Node) -> Result<Option<i64>, Self::Incomplete> {+ Ok(None)}- /// A remembered answer of the relation at `relation` for `node`.- fn relation_answer(- &self,- _program: &SelectorProgram<Self::Atoms>,- _relation: SelectorNodeID,- _node: Self::Node,+ /// A remembered answer of whether an element relative to `anchor` matches the selector list `list`, the+ /// argument of a `:has()`, evaluated under `bindings`.+ fn relative_answer_of(+ &mut self,+ _list: SelectorListKey,+ _anchor: Self::Node,+ _bindings: &SelectorBindings<Self::Node>,) -> Option<bool> {None}- fn record_relation_answer(- &mut self,- _program: &SelectorProgram<Self::Atoms>,- _relation: SelectorNodeID,- _node: Self::Node,- _answer: bool,- ) {- }+ /// Whether the subject remembers what a walk up across a descendant combinator found.+ const REMEMBERS_ANCESTOR_ANSWERS: bool = false;- /// The remembered progress of the preceding-sibling relation at `relation` through `node`'s- /// inclusive siblings, or none when the subject remembers none.- fn preceding_sibling_prefix(- &mut self,- program: &SelectorProgram<Self::Atoms>,- relation: SelectorNodeID,- node: Self::Node,- ) -> Option<RememberedPrefix<Self::PrefixSlot, Self::Node>>;+ /// Whether the subject remembers what a walk back across a subsequent-sibling combinator found.+ const REMEMBERS_SIBLING_ANSWERS: bool = false;++ /// What a walk remembers its answers in, found once per walk.+ type WalkAnswers: Copy;- fn record_preceding_sibling_prefix(+ /// Where what walks from the compound `selector` names, under `bindings`, found is remembered, for a subject that+ /// remembers it.+ fn walk_answers(&mut self,- program: &SelectorProgram<Self::Atoms>,- relation: SelectorNodeID,- slot: Self::PrefixSlot,- prefix: PrecedingSiblingPrefix<Self::Node>,- );+ _selector: SelectorKey,+ _bindings: &SelectorBindings<Self::Node>,+ ) -> Option<Self::WalkAnswers> {+ None+ }- fn positional_answer(&self, _position: NthPosition, _node: Self::Node) -> Option<bool> {+ /// Whether `node`, or an element a walk goes on to from it, matches what `answers` are of, as a walk remembered it.+ fn walk_answer(&self, _answers: Self::WalkAnswers, _node: Self::Node) -> Option<bool> {None}- fn record_positional_answer(&mut self, _position: NthPosition, _node: Self::Node, _answer: bool) {}+ /// Record in `answers` that each of `nodes`, or an element a walk goes on to from it, does or does not match.+ fn record_walk_answers(&mut self, _answers: Self::WalkAnswers, _nodes: &[Self::Node], _answer: bool) {}- /// The element's 1-based index in the sequence a positional test with no `of S` counts.- fn sibling_index(&mut self, _position: NthPosition, _node: Self::Node) -> Result<Option<i64>, Self::Incomplete> {- Ok(None)- }+ /// Note that a selector read `read` of `node`, for a subject that keeps what selectors read of the structure of+ /// its tree, whether or not the selector matched.+ fn note_structural_read(&self, _node: Self::Node, _read: StructuralRead) {}- /// A remembered number of siblings matching the selector at `selector`, counted from the start of the node's- /// sibling sequence (or from its end) through the node.- fn sibling_count_of(&self, _selector: SelectorNodeID, _from_end: bool, _node: Self::Node) -> Option<u32> {- None+ /// Whether the subject remembers the indices of elements among the siblings an `of S` list matches, which+ /// [`Self::of_index_of`] answers.+ fn remembers_of_indices(&self) -> bool {+ false}- fn record_sibling_count_of(&mut self, _selector: SelectorNodeID, _from_end: bool, _node: Self::Node, _count: u32) {}-- /// A remembered answer of the relative query for `anchor`.- fn relative_answer(- &self,- _program: &SelectorProgram<Self::Atoms>,- _query: RelativeQueryID,- _anchor: Self::Node,- ) -> Option<bool> {+ /// The 1-based index of `node`, which matches the selector list `list`, among its inclusive siblings that match+ /// it, counted from the end when `from_end`, as an earlier count remembered it.+ fn of_index_of(&self, _list: SelectorListKey, _from_end: bool, _node: Self::Node) -> Option<i64> {None}- /// Record the completed answer of a relative query, and the witness that made it true.- fn record_relative_answer(+ /// Record the index of `node` among its inclusive siblings that match `list`, as [`Self::of_index_of`] answers it.+ fn record_of_index(&mut self, _list: SelectorListKey, _from_end: bool, _node: Self::Node, _index: i64) {}++ /// Record the completed answer of a `:has()` argument list for `anchor`, evaluated under `bindings`.+ fn record_relative_answer_of(&mut self,- _program: &SelectorProgram<Self::Atoms>,- _query: RelativeQueryID,+ _list: SelectorListKey,_anchor: Self::Node,+ _bindings: &SelectorBindings<Self::Node>,_answer: bool,- _witness: Option<Self::Node>,) {}}-/// How far a preceding-sibling relation has been answered through one sibling sequence: every-/// sibling before `next` has been tried, and `answer` says whether one of them matched.-#[derive(Clone, Copy)]-pub(crate) struct PrecedingSiblingPrefix<N> {- pub(crate) next: Option<N>,- pub(crate) answer: bool,-}--/// The preceding-sibling progress a subject remembers for one sibling sequence, and where it keeps it.-pub(crate) struct RememberedPrefix<Slot, N> {- pub(crate) slot: Slot,- pub(crate) prefix: Option<PrecedingSiblingPrefix<N>>,-}--impl<N> Default for PrecedingSiblingPrefix<N> {- fn default() -> Self {- Self {- next: None,- answer: false,- }- }-}-/// What a selector's context names while it is evaluated.#[derive(Clone, Copy)]pub(crate) struct SelectorBindings<N> {@@ -499,8 +344,19 @@ pub(crate) struct SelectorBindings<N> {/// The anchor of the relational query being evaluated. Bound only while the witness walk runs,/// so that a nested `:has()` names its own anchor.pub(crate) relative_anchor: Option<N>,+ /// The scoping root of the innermost `@scope` level the last entry asked for matched in.+ pub(crate) matched_scope_root: Option<N>,+ /// Whether evaluation is inside the argument of a `:has()`.+ pub(crate) matching_relative_argument: bool,}+pub(crate) use crate::css::selector_arena::SelectorKey;++pub(crate) type SelectorListKey = (+ crate::css::selector_arena::SelectorArenaSerial,+ crate::css::selector_arena::ListStart,+);+impl<N> Default for SelectorBindings<N> {fn default() -> Self {Self {@@ -508,908 +364,14 @@ impl<N> Default for SelectorBindings<N> {scope_root_instance: None,matching_host_argument: false,relative_anchor: None,+ matched_scope_root: None,+ matching_relative_argument: false,}}}-type Answer<S> = Result<bool, <S as SelectorSubject>::Incomplete>;--/// Evaluates selector programs against one subject.+/// Matches selectors against one subject.pub(crate) struct SelectorEvaluator<S: SelectorSubject> {pub(crate) subject: S,pub(crate) bindings: SelectorBindings<S::Node>,}--impl<S: SelectorSubject> SelectorEvaluator<S> {- /// Whether the node is the host of the tree whose selectors are being evaluated.- fn node_hosts_the_scope(&self, node: S::Node) -> bool {- match self.bindings.scope_shadow_root {- Some(shadow_root) => self.subject.tree().shadow_root_of(node) == Some(shadow_root),- // A selector in the document scope is in no shadow tree, so it names no host.- None => false,- }- }-- fn matches_host_argument(- &mut self,- program: &SelectorProgram<S::Atoms>,- inner: SelectorNodeID,- host: S::Node,- counters: &S::Counters,- ) -> Answer<S> {- let was_matching_host_argument = std::mem::replace(&mut self.bindings.matching_host_argument, true);- let result = self.matches_node(program, inner, host, counters);- self.bindings.matching_host_argument = was_matching_host_argument;- result- }-- /// Whether the subject satisfies one scope instance: not excluded by its limit, and matching- /// what the rule writes inside it.- ///- /// The limit is checked from the subject up to the root, which is the specification's- /// "descendant of the scoping root and not of any scoping limit". The binding is already in- /// place, so `:scope` in either the limit or the selector names this root.- fn subject_is_in_scope(- &mut self,- program: &SelectorProgram<S::Atoms>,- limit: Option<SelectorNodeID>,- inner: SelectorNodeID,- node: S::Node,- root: S::Node,- counters: &S::Counters,- ) -> Answer<S> {- if let Some(limit) = limit {- let tree = self.subject.tree();- let mut walked = Some(node);- while let Some(current) = walked {- if self.matches_node(program, limit, current, counters)? {- return Ok(false);- }- if current == root {- break;- }- walked = tree.live_parent(current);- }- }- self.matches_node(program, inner, node, counters)- }-- /// Whether `root_candidate` roots a scope of the `@scope` that `node` is in.- #[allow(clippy::too_many_arguments)]- fn matches_in_scope_rooted_at(- &mut self,- program: &SelectorProgram<S::Atoms>,- root: SelectorNodeID,- limit: Option<SelectorNodeID>,- inner: SelectorNodeID,- node: S::Node,- root_candidate: S::Node,- counters: &S::Counters,- ) -> Answer<S> {- if !self.matches_node(program, root, root_candidate, counters)? {- return Ok(false);- }- let outer = self.bindings.scope_root_instance.replace(root_candidate);- let answer = self.subject_is_in_scope(program, limit, inner, node, root_candidate, counters);- self.bindings.scope_root_instance = outer;- answer- }-- #[inline]- fn matches_compound(- &mut self,- program: &SelectorProgram<S::Atoms>,- first: u32,- count: u32,- node: S::Node,- counters: &S::Counters,- ) -> Answer<S> {- for &operand in program.operands(first, count) {- let matches = match program.node(operand) {- SelectorOp::Feature(test) => {- counters.bump(Counter::LocalFeatureTests);- self.matches_feature(program, test, node)?- }- _ => self.matches_node(program, operand, node, counters)?,- };- if !matches {- return Ok(false);- }- }- Ok(true)- }-- // https://drafts.csswg.org/css-shadow-1/#host-element-in-tree- // When considered within its own shadow trees, the shadow host is featureless. Only the- // :host, :host(), and :host-context() pseudo-classes are allowed to match it. Selector-list- // pseudos preserve that restriction: only an alternative that reaches :host can match.- fn matches_featureless_host(- &mut self,- program: &SelectorProgram<S::Atoms>,- id: SelectorNodeID,- host: S::Node,- counters: &S::Counters,- ) -> Answer<S> {- match program.node(id) {- SelectorOp::Host(inner) => self.matches_host_argument(program, inner, host, counters),- SelectorOp::And { first, count } => {- if !program.mentions_the_host(id) {- return Ok(false);- }- for &operand in program.operands(first, count) {- let operand_matches = match program.node(operand) {- SelectorOp::RelativeExists(_) => self.matches_node(program, operand, host, counters)?,- SelectorOp::IsNode(named) => self.subject.is_node(host, named),- SelectorOp::ScopeRootInstance => self.bindings.scope_root_instance == Some(host),- _ => self.matches_featureless_host(program, operand, host, counters)?,- };- if !operand_matches {- return Ok(false);- }- }- Ok(true)- }- SelectorOp::Or { first, count } => {- for &operand in program.operands(first, count) {- if self.matches_featureless_host(program, operand, host, counters)? {- return Ok(true);- }- }- Ok(false)- }- SelectorOp::Where(inner) => self.matches_featureless_host(program, inner, host, counters),- SelectorOp::IsNode(named) => Ok(self.subject.is_node(host, named)),- SelectorOp::ScopeRootInstance => Ok(self.bindings.scope_root_instance == Some(host)),- _ => Ok(false),- }- }-- /// Whether `node` can possibly match the compound at `inner`. The shadow scope root matches- /// featurelessly, so its facts prove nothing about it.- #[inline]- fn relation_target_may_match(- &self,- program: &SelectorProgram<S::Atoms>,- inner: SelectorNodeID,- node: S::Node,- ) -> bool {- Some(node) == self.bindings.scope_shadow_root || self.subject.may_match(program, inner, node)- }-- #[inline]- fn matches_relation_target(- &mut self,- program: &SelectorProgram<S::Atoms>,- id: SelectorNodeID,- node: S::Node,- counters: &S::Counters,- ) -> Answer<S> {- if Some(node) != self.bindings.scope_shadow_root- && let SelectorOp::And { first, count } = program.node(id)- {- return self.matches_compound(program, first, count, node, counters);- }- self.matches_node(program, id, node, counters)- }-- fn matches_descendant_relation(- &mut self,- program: &SelectorProgram<S::Atoms>,- relation: SelectorNodeID,- inner: SelectorNodeID,- node: S::Node,- counters: &S::Counters,- ) -> Answer<S> {- if let Some(answer) = self.subject.relation_answer(program, relation, node) {- return Ok(answer);- }-- let tree = self.subject.tree();- let mut current = node;- let mut traversed: SmallVec<[S::Node; 8]> = SmallVec::new();- let mut incomplete = None;- let answer = loop {- traversed.push(current);- let Some(adjacent) = tree.parent(current) else {- break false;- };- counters.bump(Counter::CombinatorSteps);- match self.matches_relation_target(program, inner, adjacent, counters) {- Ok(true) => break true,- Ok(false) => {}- Err(error) => {- incomplete.get_or_insert(error);- }- }- if let Some(answer) = self.subject.relation_answer(program, relation, adjacent) {- break answer;- }- current = adjacent;- };- if !answer && let Some(incomplete) = incomplete {- return Err(incomplete);- }- // The relation is transitive: every node crossed before reaching the same positive witness- // or the same negative boundary has the same answer. Publishing the whole traversed prefix- // turns a later sparse candidate into one lookup even when the immediately adjacent node- // was not itself a selector candidate.- for traversed_node in traversed {- self.subject- .record_relation_answer(program, relation, traversed_node, answer);- }- Ok(answer)- }-- fn matches_preceding_sibling(- &mut self,- program: &SelectorProgram<S::Atoms>,- relation: SelectorNodeID,- inner: SelectorNodeID,- node: S::Node,- counters: &S::Counters,- ) -> Answer<S> {- let tree = self.subject.tree();- let remembered = match self.subject.remembers_relations(&self.bindings) {- true => self.subject.preceding_sibling_prefix(program, relation, node),- false => None,- };- let Some(RememberedPrefix {- slot,- prefix: cached_prefix,- }) = remembered- else {- for current in tree.inclusive_siblings(node) {- if current == node {- return Ok(false);- }- counters.bump(Counter::CombinatorSteps);- match self.matches_relation_target(program, inner, current, counters) {- Ok(true) => return Ok(true),- Ok(false) => {}- Err(incomplete) => return Err(incomplete.in_sibling_scan(current, Some(node))),- }- }- return Ok(false);- };-- if let Some(prefix) = cached_prefix- && prefix.next == Some(node)- {- return Ok(prefix.answer);- }- let mut prefix = cached_prefix.unwrap_or_else(|| PrecedingSiblingPrefix {- next: Some(tree.first_sibling(node)),- answer: false,- });- let mut retried_from_start = false;- let mut incomplete = None;- loop {- if prefix.next == Some(node) {- if !prefix.answer- && let Some(incomplete) = incomplete- {- return Err(incomplete);- }- self.subject- .record_preceding_sibling_prefix(program, relation, slot, prefix);- return Ok(prefix.answer);- }- let Some(current) = prefix.next else {- // Candidates normally arrive in tree order. If a caller asks out of order, restart- // this one prefix from the sequence head rather than treating ordering as a- // correctness requirement.- if retried_from_start {- return Ok(false);- }- prefix = PrecedingSiblingPrefix {- next: Some(tree.first_sibling(node)),- answer: false,- };- incomplete = None;- retried_from_start = true;- continue;- };- counters.bump(Counter::CombinatorSteps);- if !prefix.answer {- match self.matches_relation_target(program, inner, current, counters) {- Ok(true) => prefix.answer = true,- Ok(false) => {}- Err(error) => {- incomplete.get_or_insert(error);- }- }- }- prefix.next = tree.next_sibling(current);- }- }-- /// Whether every part name the rule writes is one this element is exposed to `host` under.- fn part_names_reach_host(- &mut self,- program: &SelectorProgram<S::Atoms>,- parts: SelectorNodeID,- node: S::Node,- host: S::Node,- ) -> Answer<S> {- match program.node(parts) {- SelectorOp::And { first, count } => {- for &operand in program.operands(first, count) {- if let SelectorOp::Part(name) = program.node(operand)- && !self.subject.exposes_part_to(node, name, host)?- {- return Ok(false);- }- }- Ok(true)- }- SelectorOp::Part(name) => self.subject.exposes_part_to(node, name, host),- _ => Ok(true),- }- }-- pub(crate) fn matches_node(- &mut self,- program: &SelectorProgram<S::Atoms>,- id: SelectorNodeID,- node: S::Node,- counters: &S::Counters,- ) -> Answer<S> {- let tree = self.subject.tree();- // A shadow root is a node of the tree, which is what makes a combinator walking up out of- // the tree stop at it rather than continue into the document. It is not an element, though:- // it publishes no facts, and nothing matches it - not even `*`. The one exception is- // `:host`, which names the host standing outside the tree, so a walk that reaches the root- // crosses there and nowhere else.- //- // The only shadow root a walk from inside the tree can reach is the scope's own, so this- // costs one comparison rather than a lookup.- if Some(node) == self.bindings.scope_shadow_root {- return match program.node(id) {- SelectorOp::Host(inner) => match tree.host_of(node) {- Some(host) => self.matches_host_argument(program, inner, host, counters),- None => Ok(false),- },- // A scoping root outside the tree is the host, and a combinator reaching up out of- // the tree lands here rather than on it. `:scope > .a` inside a scope rooted at the- // host is the same walk as `:host > .a`, so it crosses the same way.- SelectorOp::ScopeRootInstance => {- let host = tree.host_of(node);- Ok(host.is_some() && self.bindings.scope_root_instance == host)- }- SelectorOp::IsNode(named) => {- Ok(tree.host_of(node).is_some_and(|host| self.subject.is_node(host, named)))- }- // An in-shadow-tree query walks its axis from the shadow root and binds its anchor to- // it, so a chain tying itself back to that anchor - the leftmost step of- // `:host:has(> .child > .grand_child)` asks for the `.child`'s parent - compares- // against the root itself. It does not cross to the host the way a scoping root does,- // because the root is where the walk started.- SelectorOp::RelativeAnchorInstance => {- counters.bump(Counter::StructuralTests);- Ok(self.bindings.relative_anchor == Some(node))- }- // A compound with `:host` crosses to the host, but the host is featureless inside- // its own shadow tree: only `:host` itself decides against the host's features,- // through its argument, and `:has()` rides along as the one attached exception.- // Any other simple selector in the compound - `div:host`, `:host.x`, `*:host`,- // `:host:hover` - fails the whole compound rather than testing the host's facts.- // https://drafts.csswg.org/css-shadow-1/#host-element-in-tree- SelectorOp::And { .. } | SelectorOp::Or { .. } | SelectorOp::Where(_)- if program.mentions_the_host(id) =>- {- tree.host_of(node).map_or(Ok(false), |host| {- self.matches_featureless_host(program, id, host, counters)- })- }- _ => Ok(false),- };- }- match program.node(id) {- SelectorOp::Feature(test) => {- counters.bump(Counter::LocalFeatureTests);- self.matches_feature(program, test, node)- }- SelectorOp::Language { first, count } => {- counters.bump(Counter::StateTests);- let row = self.subject.row(node)?;- let mut ranges = program.language_ranges(first, count);- // An element with no resolved language matches no range at all, not even `*`.- Ok(match self.subject.language_tag(row) {- TokenizerInput::Latin1(tag) => {- !tag.is_empty() && ranges.any(|range| language_range_matches_tag(range, tag))- }- TokenizerInput::Utf16(tag) => {- !tag.is_empty() && ranges.any(|range| language_range_matches_tag(range, tag))- }- })- }- SelectorOp::State(fact) => {- counters.bump(Counter::StateTests);- let row = self.subject.row(node)?;- Ok(self.subject.has_state(row, fact))- }- SelectorOp::And { first, count } => self.matches_compound(program, first, count, node, counters),- SelectorOp::Or { first, count } => {- if self.node_hosts_the_scope(node) && program.mentions_the_host(id) {- return self.matches_featureless_host(program, id, node, counters);- }- for &operand in program.operands(first, count) {- if self.matches_node(program, operand, node, counters)? {- return Ok(true);- }- }- Ok(false)- }- SelectorOp::Where(inner) => self.matches_node(program, inner, node, counters),- SelectorOp::Not(inner) => Ok(!self.matches_node(program, inner, node, counters)?),- SelectorOp::Parent(inner) => {- counters.bump(Counter::CombinatorSteps);- match tree.parent(node) {- Some(parent) => self.matches_relation_target(program, inner, parent, counters),- None => Ok(false),- }- }- SelectorOp::Ancestor(inner) => {- if self.subject.remembers_relations(&self.bindings) {- return self.matches_descendant_relation(program, id, inner, node, counters);- }- let mut ancestor = tree.parent(node);- while let Some(current) = ancestor {- counters.bump(Counter::CombinatorSteps);- if self.relation_target_may_match(program, inner, current)- && self.matches_relation_target(program, inner, current, counters)?- {- return Ok(true);- }- ancestor = tree.parent(current);- }- Ok(false)- }- SelectorOp::PreviousSibling(inner) => {- counters.bump(Counter::CombinatorSteps);- match tree.previous_sibling(node) {- Some(previous) => self.matches_relation_target(program, inner, previous, counters),- None => Ok(false),- }- }- SelectorOp::PrecedingSibling(inner) => self.matches_preceding_sibling(program, id, inner, node, counters),- SelectorOp::NthPosition(position) => {- // An `of S` answer depends on what the argument matches, which the bindings decide.- let memoizes_answers = position.of_selector.is_none();- if memoizes_answers && let Some(answer) = self.subject.positional_answer(position, node) {- return Ok(answer);- }- counters.bump(Counter::StructuralTests);- let result = self.matches_nth(program, position, node, counters);- if memoizes_answers && let Ok(answer) = result {- self.subject.record_positional_answer(position, node, answer);- }- result- }- // Each shadow operator consumes the relation it names. A generic descendant walk does- // not pierce a shadow root, and a slot's assignment is not its DOM parent, so these- // cannot be expressed as ordinary combinators.- SelectorOp::Host(inner) => match self.node_hosts_the_scope(node) && !self.bindings.matching_host_argument {- true => self.matches_host_argument(program, inner, node, counters),- false => Ok(false),- },- SelectorOp::Slotted(inner) => match tree.assigned_slot_of(node) {- Some(_) => self.matches_node(program, inner, node, counters),- None => Ok(false),- },- SelectorOp::AssignedSlot(inner) => {- // The chain can pass through several trees; the slot this compound describes is the- // one in the tree whose rules are being asked.- const MAX_REASSIGNMENTS: usize = 32;- let mut current = node;- for _ in 0..MAX_REASSIGNMENTS {- let Some(slot) = tree.assigned_slot_of(current) else {- return Ok(false);- };- // The slot this compound describes is the one in the tree being asked. A shadow- // root's own tree scope is the outer one, so which tree a node is in is answered- // by walking to the root rather than by comparing scopes.- let in_this_tree = self.bindings.scope_shadow_root.is_none_or(|root| {- std::iter::successors(Some(slot), |&node| tree.live_parent(node)).any(|node| node == root)- });- if in_this_tree && self.matches_node(program, inner, slot, counters)? {- return Ok(true);- }- current = slot;- }- Ok(false)- }- SelectorOp::Part(part) => {- let row = self.subject.row(node)?;- Ok(self.subject.has_part(row, part))- }- // The host the part is exposed to, which is what the rule's outer compound describes.- //- // `exportparts` forwards a name outwards one host at a time, and each level exposes the- // names it chose to its own host. A level therefore answers this op only when it exposes- // every name the rule writes and its host is the element the outer compound describes:- // taking the name from one level and the host from another would name an element that no- // rule addresses, and taking only the outermost level would miss the rules of every tree- // the name passed through on its way out.- SelectorOp::ExposedToHost {- host: host_compound,- parts,- } => {- // https://drafts.csswg.org/css-shadow-parts-1/#part- // `::part()` reaches one level down: into a tree hosted by an element of the tree- // the rule itself is in. Without that bound a rule reached every part in the- // document, including the ones in its own tree. A compound naming `:host` reaches- // the rule's own tree as well, which is where a part forwarded out of it stands.- let scope_host = self.bindings.scope_shadow_root.and_then(|root| tree.host_of(root));- let mentions_the_host = program.mentions_the_host(host_compound);- for level_host in self.subject.part_exposure_hosts(node) {- let reaches_a_hosted_tree = tree.shadow_host_of(level_host) == scope_host;- let reaches_its_own_tree = Some(level_host) == scope_host && mentions_the_host;- if !reaches_a_hosted_tree && !reaches_its_own_tree {- continue;- }- if !self.part_names_reach_host(program, parts, node, level_host)? {- continue;- }- if self.matches_node(program, host_compound, level_host, counters)? {- return Ok(true);- }- }- Ok(false)- }- // The pseudo-classes written after an element-backed pseudo-element describe the element- // backing it, which stands in the host's shadow tree.- SelectorOp::BackingElement { kind, inner } => match tree.backing_element_of(node, kind) {- Some(backing) => self.matches_node(program, inner, backing, counters),- None => Ok(false),- },- SelectorOp::Root => {- counters.bump(Counter::StructuralTests);- Ok(self.subject.is_root(node))- }- SelectorOp::InScope {- root,- limit,- inner,- names_the_scope,- } => {- counters.bump(Counter::StructuralTests);- // One scope per element the `<scope-start>` matches, and the rule is relative to one- // of them. A scoped selector carries an implied `:scope ` prefix unless it names- // `:scope`, so the subject is normally a strict descendant of the root.- //- // An enclosing scope, when there is one, has already bound its own root; this- // scope's root has to be inside it, so the walk stops there. The `<scope-start>` is- // asked before the binding moves, because `:scope` written in one names the scope it- // is nested in rather than the scope it opens.- let enclosing_root = self.bindings.scope_root_instance;-- // A part stands inside a shadow tree, but an outer scope reaches it through the- // host exposing it. Scope membership is therefore measured from that host rather- // than from the part's DOM parent chain, which stops at the shadow root.- if program.subject_is_a_part(inner)- && let Some(level_hosts) = self.subject.part_hosts_in_exposure_scope(node)- {- for level_host in level_hosts {- let mut candidate = match names_the_scope {- true => Some(level_host),- false => tree.live_parent(level_host),- };- while let Some(root_candidate) = candidate {- if self.matches_in_scope_rooted_at(- program,- root,- limit,- inner,- node,- root_candidate,- counters,- )? {- return Ok(true);- }- if Some(root_candidate) == enclosing_root {- break;- }- candidate = tree.live_parent(root_candidate);- }- }- return Ok(false);- }-- let mut candidate = match names_the_scope {- true => Some(node),- false => tree.live_parent(node),- };- // A shadow root is not an element and roots nothing. The host standing outside the- // tree can be the scoping root, though - `@scope (:host)` says so, and an `@scope`- // with no `<scope-start>` whose `<style>` is a direct child of the shadow root roots- // there too - so the walk crosses at the root and stops.- if candidate == self.bindings.scope_shadow_root {- candidate = candidate.and_then(|root| tree.host_of(root));- }- while let Some(root_candidate) = candidate {- if self.matches_in_scope_rooted_at(program, root, limit, inner, node, root_candidate, counters)? {- return Ok(true);- }- if Some(root_candidate) == enclosing_root {- break;- }- candidate = tree.live_parent(root_candidate);- if candidate == self.bindings.scope_shadow_root {- candidate = candidate.and_then(|root| tree.host_of(root));- }- }- Ok(false)- }- SelectorOp::Empty => {- counters.bump(Counter::StructuralTests);- self.subject.is_empty(node)- }- SelectorOp::IsNode(named) => {- counters.bump(Counter::StructuralTests);- Ok(self.subject.is_node(node, named))- }- SelectorOp::ScopeRootInstance => {- counters.bump(Counter::StructuralTests);- Ok(self.bindings.scope_root_instance == Some(node))- }- SelectorOp::RelativeAnchorInstance => {- counters.bump(Counter::StructuralTests);- Ok(self.bindings.relative_anchor == Some(node))- }- // Without an enclosing `@scope`, the scoping root is the root of the tree.- SelectorOp::Scope => {- counters.bump(Counter::StructuralTests);- Ok(tree.live_parent(node).is_none())- }- SelectorOp::ValueState { kind, value } => {- counters.bump(Counter::StateTests);- let row = self.subject.row(node)?;- Ok(match kind {- ValueStateTestKind::Directionality => self.subject.directionality_is(row, value),- ValueStateTestKind::CustomState => self.subject.has_custom_state(row, value),- })- }- SelectorOp::Heading(levels) => {- counters.bump(Counter::StructuralTests);- let row = self.subject.row(node)?;- let level = self.subject.heading_level(row);- Ok((1..=9).contains(&level) && levels & (1 << (level - 1)) != 0)- }- // The existential answer: does any candidate on the query's axis satisfy its compound.- // Only the Boolean matters, so the walk stops at the first witness it finds.- SelectorOp::RelativeExists(query_id) => {- counters.bump(Counter::RelationalTests);- if let Some(answer) = self.subject.relative_answer(program, query_id, node) {- return Ok(answer);- }- let query = program.relative_query(query_id);- // An in-shadow-tree query is anchored on the host and walked from the tree the host- // opens. Binding the anchor to the shadow root as well as walking from it is what- // ties a multi-compound chain back to the right place: the leftmost step of- // `:host:has(> .child > .grand_child)` asks for the `.child`'s parent, and that is- // the root, not the host.- let anchor = match query.match_in_shadow_tree {- true => tree.shadow_root_of(node),- false => Some(node),- };- let Some(anchor) = anchor else {- return Ok(false);- };- let mut matched = Ok(false);- let mut found = None;- let enclosing_anchor = self.bindings.relative_anchor.replace(anchor);- tree.for_each_on_axis(- query.axis,- query.witness_is_below_the_axis,- anchor,- |candidate| match self.matches_node(program, query.compound, candidate, counters) {- Ok(true) => {- matched = Ok(true);- found = Some(candidate);- false- }- Ok(false) => true,- Err(incomplete) => {- matched = Err(match query.axis {- RelativeAxis::Descendant => incomplete.in_descendant_scan(anchor, candidate),- RelativeAxis::FollowingSibling => incomplete.in_sibling_scan(candidate, None),- _ => incomplete,- });- false- }- },- );- self.bindings.relative_anchor = enclosing_anchor;- // A walk that ended incomplete proved nothing either way.- if let Ok(answer) = matched {- self.subject- .record_relative_answer(program, query_id, node, answer, found);- }- matched- }- }- }-- fn matches_feature(&mut self, program: &SelectorProgram<S::Atoms>, test: FeatureTest, node: S::Node) -> Answer<S> {- if matches!(test, FeatureTest::AnyElement) {- return Ok(true);- }- let row = self.subject.row(node)?;- Ok(matches_feature(- &self.subject.features(row),- test,- |test, attribute, insensitive| self.matches_attribute_value(program, test, attribute, insensitive),- ))- }-- fn matches_attribute_value(- &self,- program: &SelectorProgram<S::Atoms>,- test: AttributeTest,- attribute: S::Attribute,- insensitive: bool,- ) -> bool {- if test.operator == AttributeOperator::Presence {- return true;- }- // An exact test on two interned values is an integer comparison, which is why the engine- // carries no text for attributes only tested this way.- if test.operator == AttributeOperator::Exact && !insensitive && !test.value_atom.is_none() {- let value = self.subject.attribute_value_atom(attribute);- if !value.is_none() {- return test.value_atom == value;- }- }-- let literal = program.literal(test.value_offset, test.value_length);- match self.subject.attribute_value_text(attribute) {- Some(TokenizerInput::Latin1(value)) => attribute_value_matches(test.operator, value, literal, insensitive),- Some(TokenizerInput::Utf16(value)) => attribute_value_matches(test.operator, value, literal, insensitive),- None => false,- }- }-- pub(crate) fn matches_nth(- &mut self,- program: &SelectorProgram<S::Atoms>,- position: NthPosition,- node: S::Node,- counters: &S::Counters,- ) -> Answer<S> {- if position.of_selector.is_none()- && let Some(index) = self.subject.sibling_index(position, node)?- {- return Ok(matches_an_plus_b(position.step, position.offset, index));- }- // What S matches depends on the bindings, so its counts can only be kept while they are the ones every- // count was made under.- if let Some(selector) = position.of_selector- && S::REMEMBERS_SIBLING_COUNTS_OF_SELECTORS- && self.subject.remembers_relations(&self.bindings)- {- if !self.matches_node(program, selector, node, counters)? {- return Ok(false);- }- let index = self.count_siblings_matching(program, selector, position.from_end, node, counters)?;- return Ok(matches_an_plus_b(position.step, position.offset, i64::from(index)));- }-- // https://drafts.csswg.org/selectors/#typedef-type-selector- // An element's type is its qualified name, so two `p` elements in different namespaces are- // different types and are counted in different sequences.- let subject_type = match position.of_type {- true => Some(self.subject.row(node)?),- false => None,- };-- // https://drafts.csswg.org/selectors/#child-index- // A positional test counts the subject among its inclusive siblings. The root of a tree has none, which makes- // it the one and only element of its sequence rather than absent from one: `:first-child`, `:last-child` and- // `:only-child` all name it. The children of a document or a fragment have no parent element, but they are- // siblings all the same.- //- // The subject has to be one of the counted siblings, or it has no position in the sequence.- if !self.counts_in_sequence(program, position, subject_type, node, counters)? {- return Ok(false);- }- let tree = self.subject.tree();-- // Count towards the near end only. The whole sequence is never needed, and a sequence of- // thousands of siblings is what a long list or a table is, so materializing one per test- // made `:first-child` cost the length of its parent's child list.- let mut index: i64 = 1;- let bounded = position.step == 0;- let mut current = match position.from_end {- true => tree.next_sibling(node),- false => Some(tree.first_sibling(node)),- };- while let Some(sibling) = current {- if !position.from_end && sibling == node {- break;- }- match self.counts_in_sequence(program, position, subject_type, sibling, counters) {- Ok(true) => {- index += 1;- // A test with no step names one position, so once the count is past it no further- // sibling can bring it back. `:first-child` stops at the first counted neighbour.- if bounded && index > i64::from(position.offset) {- return Ok(false);- }- }- Ok(false) => {}- Err(incomplete) => {- return Err(incomplete.in_sibling_scan(sibling, (!position.from_end).then_some(node)));- }- }- current = tree.next_sibling(sibling);- }- Ok(matches_an_plus_b(position.step, position.offset, index))- }-- /// How many siblings from the start of `node`'s sibling sequence (or from its end) through `node` match the- /// selector at `selector`. A count walks only to the nearest sibling whose count the subject remembers, and the- /// subject remembers the count of every sibling the walk passes, so counting every child of a parent walks its- /// children once.- fn count_siblings_matching(- &mut self,- program: &SelectorProgram<S::Atoms>,- selector: SelectorNodeID,- from_end: bool,- node: S::Node,- counters: &S::Counters,- ) -> Result<u32, S::Incomplete> {- let tree = self.subject.tree();- let toward_start = |sibling| match from_end {- true => tree.next_sibling(sibling),- false => tree.previous_sibling(sibling),- };- let away_from_start = |sibling| match from_end {- true => tree.previous_sibling(sibling),- false => tree.next_sibling(sibling),- };- let mut count = 0;- let mut sibling = node;- let mut next = loop {- if let Some(known) = self.subject.sibling_count_of(selector, from_end, sibling) {- if sibling == node {- return Ok(known);- }- count = known;- break away_from_start(sibling);- }- match toward_start(sibling) {- Some(previous) => sibling = previous,- None => break Some(sibling),- }- };- while let Some(sibling) = next {- count += u32::from(self.matches_node(program, selector, sibling, counters)?);- self.subject.record_sibling_count_of(selector, from_end, sibling, count);- if sibling == node {- break;- }- next = away_from_start(sibling);- }- Ok(count)- }-- /// Whether one sibling is counted by this positional test's sequence.- fn counts_in_sequence(- &mut self,- program: &SelectorProgram<S::Atoms>,- position: NthPosition,- subject_type: Option<S::Row>,- sibling: S::Node,- counters: &S::Counters,- ) -> Answer<S> {- match (subject_type, position.of_selector) {- (Some(subject_type), _) => {- let row = self.subject.row(sibling)?;- Ok(self.subject.same_type(row, subject_type))- }- (None, Some(selector)) => self.matches_node(program, selector, sibling, counters),- (None, None) => Ok(true),- }- }-}diff --git a/Libraries/LibWeb/Rust/src/css/style/shareable.rs b/Libraries/LibWeb/Rust/src/css/style/shareable.rsindex fd6a1a63645..2ea56c5ec56 100644--- a/Libraries/LibWeb/Rust/src/css/style/shareable.rs+++ b/Libraries/LibWeb/Rust/src/css/style/shareable.rs@@ -10,15 +10,11 @@//! writes only this flush's scratch. For many workers to run the same step over one read side,//! everything the step reads has to be shareable across threads and the per-worker scratch has to//! be movable to one. None of this is a runtime check: a type that stops being shareable stops-//! compiling, which is how the port of the read side found its own work list.+//! compiling.use super::*;-// NB: The prefix caches (`prefix_caches`, and `batch_matching_traversal`, which borrows them) are `Sync` only because-// their borrows are checked atomically, so the engine can move to the thread its stages run on. Two workers-// borrowing them at once would still panic; giving a walk prefix caches of its own is what makes them shareable.const _: () = {const fn assert_sync<T: Sync + ?Sized>() {}- assert_sync::<PublishedMatchAnswers>();assert_sync::<RetainedState>();};diff --git a/Libraries/LibWeb/Rust/src/css/style/sorted_merge.rs b/Libraries/LibWeb/Rust/src/css/style/sorted_merge.rsdeleted file mode 100644index fb9e283673c..00000000000--- a/Libraries/LibWeb/Rust/src/css/style/sorted_merge.rs+++ /dev/null@@ -1,66 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--use std::cmp::Ordering;--pub(super) enum SortedMergeEntry<'a, Left, Right> {- Both(&'a Left, &'a Right),- Left(&'a Left),- Right(&'a Right),-}--pub(super) struct SortedMerge<'a, Left, Right, Compare> {- left: &'a [Left],- right: &'a [Right],- compare: Compare,-}--pub(super) fn merge_sorted_by<'a, Left, Right, Compare>(- left: &'a [Left],- right: &'a [Right],- compare: Compare,-) -> SortedMerge<'a, Left, Right, Compare>-where- Compare: Fn(&Left, &Right) -> Ordering,-{- SortedMerge { left, right, compare }-}--impl<'a, Left, Right, Compare> Iterator for SortedMerge<'a, Left, Right, Compare>-where- Compare: Fn(&Left, &Right) -> Ordering,-{- type Item = SortedMergeEntry<'a, Left, Right>;-- fn next(&mut self) -> Option<Self::Item> {- match (self.left.split_first(), self.right.split_first()) {- (Some((left, left_rest)), Some((right, right_rest))) => match (self.compare)(left, right) {- Ordering::Equal => {- self.left = left_rest;- self.right = right_rest;- Some(SortedMergeEntry::Both(left, right))- }- Ordering::Less => {- self.left = left_rest;- Some(SortedMergeEntry::Left(left))- }- Ordering::Greater => {- self.right = right_rest;- Some(SortedMergeEntry::Right(right))- }- },- (Some((left, left_rest)), None) => {- self.left = left_rest;- Some(SortedMergeEntry::Left(left))- }- (None, Some((right, right_rest))) => {- self.right = right_rest;- Some(SortedMergeEntry::Right(right))- }- (None, None) => None,- }- }-}diff --git a/Libraries/LibWeb/Rust/src/css/style/user_agent_selectors.rs b/Libraries/LibWeb/Rust/src/css/style/user_agent_selectors.rsdeleted file mode 100644index d963601d10f..00000000000--- a/Libraries/LibWeb/Rust/src/css/style/user_agent_selectors.rs+++ /dev/null@@ -1,214 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! The user-agent sheets are the same objects in every document of the process, so the selectors-//! of their rules are compiled once per process. Every document that records the sheets attaches-//! the programs the first one compiled, and the routing registry its rules make.--use super::compiler::ScopeChain;-use super::inputs::compile_selector_program;-use super::rule_writes::NamespaceTexts;-use super::selector::{ProcessSelectorProgram, RoutingRegistry, SelectorEntryIDs, SharedSelectorIdentity};-use super::*;-use std::collections::hash_map::Entry;-use std::sync::{MutexGuard, OnceLock};--/// What a user-agent rule's selector program is compiled from. The rule's identity names its-/// selectors: no other rule ever takes it, and a user-agent rule is never edited. The rest is what-/// the compiler reads from the document.-#[derive(Clone, Copy, PartialEq, Eq, Hash)]-struct CompilationKey {- rule: u64,- fold_id_and_class_name_case: bool,- html_element_namespace: StyleAtomID,-}--struct UserAgentSelectorPrograms {- /// Holds every atom the programs name for as long as the process lives, so that none of them- /// is ever given to another name.- atoms: DocumentAtoms,- programs: HashMap<CompilationKey, ProcessSelectorProgram>,- routings: Vec<UserAgentRouting>,-}--/// A rule of a user-agent sheet as its routes name it: by the engine's identities of the rule, of-/// its program and of the program's entries, and by the program the process shares.-#[derive(PartialEq, Eq)]-struct UserAgentRoute {- rule: RuleID,- program: SelectorProgramID,- shared: SharedSelectorIdentity,- entries: SelectorEntryIDs,-}--/// The routing registry a user-agent sheet's rules make, routed in order into the registry-/// `after` names: an empty one, or by its index the one another sheet's rules made. Routing is a-/// function of what is routed into what, so every engine that routes the same rules the same way-/// makes this registry.-struct UserAgentRouting {- after: Option<usize>,- routes: Vec<UserAgentRoute>,- routing: RoutingRegistry,-}--/// How many routings the process keeps: one per set of user-agent sheets a document records,-/// which quirks mode, the HTML namespace and MathML or SVG content decide.-const MAX_USER_AGENT_ROUTINGS: usize = 16;--fn user_agent_selector_programs() -> MutexGuard<'static, UserAgentSelectorPrograms> {- static PROGRAMS: OnceLock<Mutex<UserAgentSelectorPrograms>> = OnceLock::new();- PROGRAMS- .get_or_init(|| {- Mutex::new(UserAgentSelectorPrograms {- atoms: DocumentAtoms::for_live_engine(),- programs: HashMap::default(),- routings: Vec::new(),- })- })- .lock()- .unwrap()-}--impl StyleEngine {- /// Whether this engine attaches the selector programs the process compiled for the user-agent- /// sheets. One whose atoms are its own cannot read programs that name the process's.- pub(super) fn shares_user_agent_selector_programs(&self) -> bool {- self.atoms.is_process_global()- }-- /// Add a style rule of a user-agent sheet, compiling its selectors only if no document in the- /// process has compiled them with the same inputs before.- pub(super) fn add_user_agent_style_rule(- &mut self,- sheet: SheetID,- before: Option<RuleID>,- rule_identity: u64,- selectors: &[&CompiledSelector],- namespaces: Option<&NamespaceTexts>,- ) -> RuleID {- debug_assert!(self.program.sheet_origin(sheet) == CascadeOrigin::UserAgent);- let key = CompilationKey {- rule: rule_identity,- fold_id_and_class_name_case: self.fold_id_and_class_name_case,- html_element_namespace: self.html_element_namespace,- };- let program = {- let mut cache = user_agent_selector_programs();- let UserAgentSelectorPrograms { atoms, programs, .. } = &mut *cache;- match programs.entry(key) {- Entry::Occupied(entry) => entry.get().clone(),- Entry::Vacant(entry) => {- let namespaces = NamespaceTexts::scope(namespaces, |text| {- atoms.intern_raw(ak::Utf16FlyString::from_utf16(text).raw_identity())- });- let compiled = compile_selector_program(- atoms,- key.fold_id_and_class_name_case,- key.html_element_namespace,- selectors,- namespaces,- &ScopeChain::default(),- &self.retained.counters,- );- entry.insert(ProcessSelectorProgram::share(compiled)).clone()- }- }- };- self.add_style_rule_with(sheet, before, |engine, previous_program| {- engine.note_selector_attribute_names(program.program());- engine.note_relational_arrival_keys(program.program());- let id = engine.retained.programs.add_process_program(&program);- engine.retained.selector_programs_need_sweep |= previous_program.is_some();-- id- })- }-- /// Publish the rules of the sheet `sheet` with `publish`. A user-agent sheet's rules are- /// routed together as the publication ends, so that an engine whose routing holds what- /// another document's held when it routed them takes a copy of the registry they made.- pub(super) fn publish_sheet_rules(&mut self, sheet: u32, publish: impl FnOnce(&mut Self)) {- let user_agent = sheet- .checked_sub(1)- .is_some_and(|sheet| self.program.sheet_origin(SheetID(sheet)) == CascadeOrigin::UserAgent);- if !user_agent || !self.shares_user_agent_selector_programs() {- publish(self);- return;- }- debug_assert!(self.retained.deferred_user_agent_routes.is_none());- self.retained.deferred_user_agent_routes = Some(Vec::new());- publish(self);- let deferred = self.retained.deferred_user_agent_routes.take().unwrap();- self.route_user_agent_rules(&deferred);- }-- fn route_user_agent_rules(&mut self, deferred: &[(RuleID, SelectorProgramID)]) {- if deferred.is_empty() {- return;- }- let routes = deferred- .iter()- .map(|&(rule, program)| {- let (shared, entries) = self.programs.shared_dispatch_identity(program)?;- Some(UserAgentRoute {- rule,- program,- shared,- entries,- })- })- .collect::<Option<Vec<_>>>();- let after = {- let cache = user_agent_selector_programs();- let after = match self.routing.is_empty() {- true => Some(None),- false => cache- .routings- .iter()- .position(|made| self.routing.is_finished_copy_of(&made.routing))- .map(Some),- };- if let (Some(routes), Some(after)) = (&routes, after)- && let Some(made) = cache- .routings- .iter()- .find(|made| made.after == after && made.routes == *routes)- {- let routing = made.routing.copy_for_another_engine();- drop(cache);- self.retained.routing = Arc::new(routing);- return;- }- after.filter(|_| cache.routings.len() < MAX_USER_AGENT_ROUTINGS)- };-- let retained = &mut self.retained;- let routing = Arc::make_mut(&mut retained.routing);- for &(rule, program) in deferred {- routing.add_rule(rule, program, &retained.programs);- }- let (Some(routes), Some(after)) = (routes, after) else {- return;- };- // Finish this engine's routing as well as the process's copy of it, so that the next user-agent sheet this- // engine records finds its routing as the one these rules made.- routing.finish_for_sharing();- let made = routing.copy_for_another_engine();- let mut cache = user_agent_selector_programs();- if cache.routings.len() < MAX_USER_AGENT_ROUTINGS- && !cache- .routings- .iter()- .any(|known| known.after == after && known.routes == routes)- {- cache.routings.push(UserAgentRouting {- after,- routes,- routing: made,- });- }- }-}diff --git a/Tests/LibWeb/Text/expected/DOM/selector-queries-by-class-in-subtrees.txt b/Tests/LibWeb/Text/expected/DOM/selector-queries-by-class-in-subtrees.txtnew file mode 100644index 00000000000..a17f0f018fa--- /dev/null+++ b/Tests/LibWeb/Text/expected/DOM/selector-queries-by-class-in-subtrees.txt@@ -0,0 +1,23 @@+from the parser: .early: b1+from the parser: section .early: b1+before any: .late:+class added deep in a subtree: .late: a2+class added deep in a subtree: #root .late: a2+class added deep in a subtree: .late span, section .late: a2+class replaced: .late:+class replaced: .other: a2+class removed: .other:+before insertion: .carried:+subtree inserted: .carried: moved2+subtree inserted: section .carried: moved2+clone: .cloned: clone2+innerHTML: .parsed: html1+toggled on: .toggled: a1+toggled off: .toggled:+left of the subject: .missing span:+left of the subject: .early ~ span, .missing span:+left of the subject: .parsed, .missing span: html1+attribute left of the subject: [nope] span:+attribute left of the subject: [nope] span: a2+disconnected: moved2+shadow: shadow1diff --git a/Tests/LibWeb/Text/expected/DOM/selector-queries-by-class.txt b/Tests/LibWeb/Text/expected/DOM/selector-queries-by-class.txtnew file mode 100644index 00000000000..5eb4c95f123--- /dev/null+++ b/Tests/LibWeb/Text/expected/DOM/selector-queries-by-class.txt@@ -0,0 +1,12 @@+.x: p1 p2 d1 s2 (first: p1)+.X: s1 (first: s1)+.x.y: p2 (first: p2)+p.x, div.x: p1 p2 d1 (first: p1)+.x, .y: p1 p2 d1 s1 s2 (first: p1)+.y.x, .x.z: p2 s2 (first: p2)+div .x: p1 p2 d1 s2 (first: p1)+.x:not(.y): p1 d1 s2 (first: p1)+.z .x: s2 (first: s2)+:is(.x): p1 p2 d1 s2 (first: p1)+.x, :not(.x): p1 p2 d1 s1 d2 s2 (first: p1)+after class change: d1 d2diff --git a/Tests/LibWeb/Text/expected/DOM/selector-queries-by-id.txt b/Tests/LibWeb/Text/expected/DOM/selector-queries-by-id.txtnew file mode 100644index 00000000000..5b22b45b806--- /dev/null+++ b/Tests/LibWeb/Text/expected/DOM/selector-queries-by-id.txt@@ -0,0 +1,30 @@+document #one: one.c (first: one.c)+document #missing: (none) (first: none)+document #missing .c: (none) (first: none)+document #dup: dup.first dup.nested dup.last (first: dup.first)+document p#dup: dup.first dup.last (first: dup.first)+document #dup.last: dup.last (first: dup.last)+document #dup .c: d1.c d2.c d3.c (first: d1.c)+document #dup > .c: d1.c d2.c d3.c (first: d1.c)+document #one .c: s1.c (first: s1.c)+document #one > span: s1.c s2. (first: s1.c)+document #sib ~ span: after1.c after2.c (first: after1.c)+document #sib + span: after1.c (first: after1.c)+document #sib ~ * .c: inside.c (first: inside.c)+document #root #one span: s1.c s2. (first: s1.c)+document #one ~ p span: d1.c d2.c d3.c (first: d1.c)+root #one: one.c (first: one.c)+root #root span: s1.c s2. d1.c d2.c d3.c after1.c inside.c after2.c (first: s1.c)+root #root > p: one.c dup.first dup.last (first: one.c)+one #one span: s1.c s2. (first: s1.c)+one #one: (none) (first: none)+one #sib ~ span: (none) (first: none)+s1 #one span: (none) (first: none)+shadow #one: one. (first: one.)+shadow #one span: shadow-span.c (first: shadow-span.c)+shadow #sib + span: shadow-after. (first: shadow-after.)+shadow #root: (none) (first: none)+detached #one span: detached-span. (first: detached-span.)+detached #one: one. (first: one.)+after id change: moved. (none)+after removal: dup.first dup.nested d1.c d2.cdiff --git a/Tests/LibWeb/Text/expected/DOM/selector-queries-never-matching-selectors.txt b/Tests/LibWeb/Text/expected/DOM/selector-queries-never-matching-selectors.txtnew file mode 100644index 00000000000..a15af788c36--- /dev/null+++ b/Tests/LibWeb/Text/expected/DOM/selector-queries-never-matching-selectors.txt@@ -0,0 +1,11 @@+:is(:unknown): (first: none) (p1 matches: false, closest: none)+:is(:unknown), :where(:unknown): (first: none) (p1 matches: false, closest: none)+p, :is(:unknown): p1 p2 (first: p1) (p1 matches: true, closest: p1)+:is(:unknown), .x: p1 b1 (first: p1) (p1 matches: true, closest: p1)+.x, b:where(:unknown), p:is(:unknown): p1 b1 (first: p1) (p1 matches: true, closest: p1)+#only, :is(:unknown): only (first: only) (p1 matches: false, closest: none)+:is(:unknown) #only, #root > span: only (first: only) (p1 matches: false, closest: none)+:is(:unknown) > p, b: b1 (first: b1) (p1 matches: false, closest: none)+:not(:is(:unknown)) ~ b: b1 (first: b1) (p1 matches: false, closest: none)+:is(:unknown) ~ b, [id=p2]: p2 (first: p2) (p1 matches: false, closest: none)+:where(:unknown) span, span: only (first: only) (p1 matches: false, closest: none)diff --git a/Tests/LibWeb/Text/expected/css/attribute-names-in-compound-bloom.txt b/Tests/LibWeb/Text/expected/css/attribute-names-in-compound-bloom.txtnew file mode 100644index 00000000000..4106ca3c2c8--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/attribute-names-in-compound-bloom.txt@@ -0,0 +1,23 @@+subject: rgb(0, 128, 0)+subject without: rgb(0, 0, 0)+ancestor: rgb(0, 128, 0)+no ancestor: rgb(0, 0, 0)+parent: rgb(0, 128, 0)+upper in the selector: rgb(0, 128, 0)+upper in the source: rgb(0, 128, 0)+value case: rgb(0, 128, 0)+any namespace: rgb(0, 128, 0)+named namespace: rgb(0, 128, 0)+no namespace on a namespaced attribute: rgb(0, 0, 0)+svg lowercase selector: rgb(0, 0, 0)+svg written selector: rgb(0, 128, 0)+late before: rgb(0, 0, 0)+late after: rgb(0, 128, 0)+late removed: rgb(0, 0, 0)+script before: rgb(0, 0, 0)+script set in another case: rgb(0, 128, 0)+ancestor before: rgb(0, 0, 0)+ancestor set: rgb(0, 128, 0)+ancestor removed: rgb(0, 0, 0)+withheld before: rgb(0, 0, 0)+withheld read by a rule arriving: rgb(0, 128, 0)diff --git a/Tests/LibWeb/Text/expected/css/document-rules-naming-the-host-of-a-use-element.txt b/Tests/LibWeb/Text/expected/css/document-rules-naming-the-host-of-a-use-element.txtnew file mode 100644index 00000000000..5925595c7c6--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/document-rules-naming-the-host-of-a-use-element.txt@@ -0,0 +1,2 @@+at load: display inline, z-index auto, --from-host ""+a later sheet: display inline, z-index auto, --from-host ""diff --git a/Tests/LibWeb/Text/expected/css/media-flips-in-a-sheet-kept-in-a-segment.txt b/Tests/LibWeb/Text/expected/css/media-flips-in-a-sheet-kept-in-a-segment.txtnew file mode 100644index 00000000000..ea4a7bb4f25--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/media-flips-in-a-sheet-kept-in-a-segment.txt@@ -0,0 +1,15 @@+wide: a rgb(0, 128, 0), b 0px, c 0px, d 0px+narrow 1: a rgb(0, 0, 255), b 0px, c 0px, d 0px+narrow, classes on 1: a rgb(0, 0, 255), b 3px, c 0px, d 4px+wide 1: a rgb(0, 128, 0), b 3px, c 2px, d 4px+wide, classes off 1: a rgb(0, 128, 0), b 0px, c 0px, d 0px+narrow 2: a rgb(0, 0, 255), b 0px, c 0px, d 0px+narrow, classes on 2: a rgb(0, 0, 255), b 3px, c 0px, d 4px+wide 2: a rgb(0, 128, 0), b 3px, c 2px, d 4px+wide, classes off 2: a rgb(0, 128, 0), b 0px, c 0px, d 0px+narrow 3: a rgb(0, 0, 255), b 0px, c 0px, d 0px+narrow, classes on 3: a rgb(0, 0, 255), b 3px, c 0px, d 4px+wide 3: a rgb(0, 128, 0), b 3px, c 2px, d 4px+wide, classes off 3: a rgb(0, 128, 0), b 0px, c 0px, d 0px+after a rule was deleted: a rgb(0, 128, 0), b 0px, c 0px, d 0px+after a rule was inserted: a rgb(1, 2, 3), b 0px, c 0px, d 0pxdiff --git a/Tests/LibWeb/Text/expected/css/nesting-selector-follows-cssom-edits.txt b/Tests/LibWeb/Text/expected/css/nesting-selector-follows-cssom-edits.txtnew file mode 100644index 00000000000..d187dfa50dd--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/nesting-selector-follows-cssom-edits.txt@@ -0,0 +1,6 @@+initial: 11px/1px/rgb(0, 0, 0) | 1px/1px/rgb(0, 0, 0)+grandparent edited: 1px/1px/rgb(0, 0, 0) | 11px/1px/rgb(0, 0, 0)+child inserted: 1px/1px/rgb(0, 0, 0) | 11px/7px/rgb(0, 0, 0)+scope inserted: 1px/1px/rgb(0, 0, 0) | 11px/7px/rgb(0, 128, 0)+grandparent restored: 11px/7px/rgb(0, 128, 0) | 1px/1px/rgb(0, 0, 0)+specificity through &: 11px/7px/rgb(0, 128, 0) | 1px/1px/rgb(0, 0, 0)diff --git a/Tests/LibWeb/Text/expected/css/position-try-replaced-rule-leaves-last-successful-option.txt b/Tests/LibWeb/Text/expected/css/position-try-replaced-rule-leaves-last-successful-option.txtnew file mode 100644index 00000000000..5c40628c153--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/position-try-replaced-rule-leaves-last-successful-option.txt@@ -0,0 +1 @@+0 of 200 kept an option of a replaced rulediff --git a/Tests/LibWeb/Text/expected/css/selector-left-of-a-subject-its-bucket-proves.txt b/Tests/LibWeb/Text/expected/css/selector-left-of-a-subject-its-bucket-proves.txtnew file mode 100644index 00000000000..4689b0eab6b--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/selector-left-of-a-subject-its-bucket-proves.txt@@ -0,0 +1,29 @@+<div class=class-subject></div> outside: rgb(0, 0, 0) rgba(0, 0, 0, 0)+<div class=class-subject></div> inside: rgb(0, 128, 0) rgb(0, 128, 0)+<div id=id-subject></div> outside: rgb(0, 0, 0) rgba(0, 0, 0, 0)+<div id=id-subject></div> inside: rgb(0, 128, 0) rgb(0, 128, 0)+<tag-subject></tag-subject> outside: rgb(0, 0, 0) rgba(0, 0, 0, 0)+<tag-subject></tag-subject> inside: rgb(0, 128, 0) rgb(0, 128, 0)+<tag-written-upper></tag-written-upper> outside: rgb(0, 0, 0) rgba(0, 0, 0, 0)+<tag-written-upper></tag-written-upper> inside: rgb(0, 128, 0) rgb(0, 128, 0)+<div class=UPPER-CLASS-SUBJECT></div> outside: rgb(0, 0, 0) rgba(0, 0, 0, 0)+<div class=UPPER-CLASS-SUBJECT></div> inside: rgb(0, 128, 0) rgb(0, 128, 0)+<input type=checkbox checked> outside: rgb(0, 0, 0) rgba(0, 0, 0, 0)+<input type=checkbox checked> inside: rgb(0, 128, 0) rgb(0, 128, 0)+<div class=two-part-subject></div> outside: rgb(0, 0, 0) rgba(0, 0, 0, 0)+<div class=two-part-subject></div> inside: rgb(0, 128, 0) rgb(0, 128, 0)+<p class=two-part-subject></p> outside: rgb(0, 0, 0) rgba(0, 0, 0, 0)+<p class=two-part-subject></p> inside: rgb(0, 0, 0) rgb(0, 128, 0)+<div class=scoped-subject></div> outside: rgb(0, 0, 0) rgba(0, 0, 0, 0)+<div class=scoped-subject></div> inside: rgb(0, 128, 0) rgb(0, 128, 0)+<div class=scope-subject></div> outside: rgb(0, 0, 0) rgba(0, 0, 0, 0)+<div class=scope-subject></div> inside: rgb(0, 128, 0) rgb(0, 128, 0)+next: rgb(0, 128, 0)+later: rgb(0, 128, 0)+next without: rgb(0, 0, 0)+later without: rgb(0, 0, 0)+pseudo: rgb(0, 128, 0)+pseudo without: rgb(0, 0, 0)+has: rgb(0, 128, 0)+has without: rgb(0, 0, 0)+folded tag: rgb(0, 0, 0)diff --git a/Tests/LibWeb/Text/expected/css/shared-link-style-sheet-compiles-once.txt b/Tests/LibWeb/Text/expected/css/shared-link-style-sheet-compiles-once.txtnew file mode 100644index 00000000000..baad4bdb884--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/shared-link-style-sheet-compiles-once.txt@@ -0,0 +1,5 @@+first: rgb(0, 128, 0)+others: rgb(0, 128, 0), rgb(0, 128, 0), rgb(0, 128, 0)+rules compiled for the other links: 0+after the first other stops matching: rgb(0, 0, 0), rgb(0, 128, 0), rgb(0, 128, 0)+after removing the second other: rgb(0, 0, 0), rgb(0, 128, 0)diff --git a/Tests/LibWeb/Text/expected/css/sheet-changes-rematch-what-they-changed.txt b/Tests/LibWeb/Text/expected/css/sheet-changes-rematch-what-they-changed.txtnew file mode 100644index 00000000000..b5a45e27ef3--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/sheet-changes-rematch-what-they-changed.txt@@ -0,0 +1,280 @@+start+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base next rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base a only-one rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base layered rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base inserted rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base other rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div a rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div inside rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+first arrived+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base next rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base a only-one rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base layered rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base inserted rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base other rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div a rgb(255, 0, 0) rgba(0, 0, 0, 0) rgb(255, 0, 0)+ div inside rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+second arrived, over the first+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(0, 128, 0)+ p below rgb(0, 128, 0) rgba(0, 0, 0, 0) rgb(0, 128, 0)+ div base next rgb(0, 128, 0) rgb(1, 1, 1) rgb(0, 128, 0)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(0, 128, 0)+ p below rgb(0, 128, 0) rgba(0, 0, 0, 0) rgb(0, 128, 0)+ div base a only-one rgb(1, 1, 1) rgb(1, 1, 1) rgb(0, 128, 0)+ div base layered rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base inserted rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base other rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(0, 128, 0)+ div a rgb(0, 128, 0) rgba(0, 0, 0, 0) rgb(0, 128, 0)+ div inside rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+first left, under the second+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(0, 128, 0)+ p below rgb(0, 128, 0) rgba(0, 0, 0, 0) rgb(0, 128, 0)+ div base next rgb(0, 128, 0) rgb(1, 1, 1) rgb(0, 128, 0)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(0, 128, 0)+ p below rgb(0, 128, 0) rgba(0, 0, 0, 0) rgb(0, 128, 0)+ div base a only-one rgb(1, 1, 1) rgb(1, 1, 1) rgb(0, 128, 0)+ div base layered rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base inserted rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base other rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(0, 128, 0)+ div a rgb(0, 128, 0) rgba(0, 0, 0, 0) rgb(0, 128, 0)+ div inside rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+swapped+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base next rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base a only-one rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base layered rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base inserted rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base other rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div a rgb(255, 0, 0) rgba(0, 0, 0, 0) rgb(255, 0, 0)+ div inside rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+both left+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base next rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base a only-one rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base layered rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base inserted rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base other rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div a rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div inside rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+all at once+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(0, 128, 0)+ p below rgb(0, 128, 0) rgba(0, 0, 0, 0) rgb(0, 128, 0)+ div base next rgb(0, 128, 0) rgb(1, 1, 1) rgb(0, 128, 0)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(0, 128, 0)+ p below rgb(0, 128, 0) rgba(0, 0, 0, 0) rgb(0, 128, 0)+ div base a only-one rgb(1, 1, 1) rgb(1, 1, 1) rgb(0, 128, 0)+ div base layered rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base inserted rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base other rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(0, 128, 0)+ div a rgb(0, 128, 0) rgba(0, 0, 0, 0) rgb(0, 128, 0)+ div inside rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+layers+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base next rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base a only-one rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base layered rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base inserted rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base other rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div a rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div inside rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+layer order moved+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base next rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base a only-one rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base layered rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base inserted rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base other rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div a rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div inside rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+layer order back+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base next rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base a only-one rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base layered rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base inserted rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base other rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div a rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div inside rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+layers left+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base next rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base a only-one rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base layered rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base inserted rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base other rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div a rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div inside rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+inserted+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base next rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base a only-one rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base layered rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base inserted rgb(0, 128, 0) rgb(1, 1, 1) rgb(0, 128, 0)+ div base other rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div a rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div inside rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+inserted over+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base next rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base a only-one rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base layered rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base inserted rgb(0, 128, 0) rgb(1, 1, 1) rgb(0, 128, 0)+ div base other rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div a rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div inside rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+deleted the one over+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base next rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base a only-one rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base layered rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base inserted rgb(0, 128, 0) rgb(1, 1, 1) rgb(0, 128, 0)+ div base other rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div a rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div inside rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+deleted+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base next rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base a only-one rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base layered rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base inserted rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base other rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div a rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div inside rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+shadow sheet arrived+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base next rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base a only-one rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base layered rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base inserted rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base other rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div a rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div inside rgb(0, 128, 0) rgba(0, 0, 0, 0) rgb(0, 128, 0)+ div rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+shadow sheet left+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base next rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base a only-one rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base layered rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base inserted rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base other rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div a rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div inside rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+many arrived+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base next rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base a only-one rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base layered rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base inserted rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base other rgb(0, 128, 0) rgb(1, 1, 1) rgb(0, 128, 0)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div a rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div inside rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+many left, with one arriving+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(0, 128, 0)+ p below rgb(0, 128, 0) rgba(0, 0, 0, 0) rgb(0, 128, 0)+ div base next rgb(0, 128, 0) rgb(1, 1, 1) rgb(0, 128, 0)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(0, 128, 0)+ p below rgb(0, 128, 0) rgba(0, 0, 0, 0) rgb(0, 128, 0)+ div base a only-one rgb(1, 1, 1) rgb(1, 1, 1) rgb(0, 128, 0)+ div base layered rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base inserted rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base other rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(0, 128, 0)+ div a rgb(0, 128, 0) rgba(0, 0, 0, 0) rgb(0, 128, 0)+ div inside rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+end+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base next rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ p below rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div base a only-one rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base layered rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base inserted rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base other rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div base a rgb(1, 1, 1) rgb(1, 1, 1) rgb(1, 1, 1)+ div a rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div inside rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)+ div rgb(1, 1, 1) rgba(0, 0, 0, 0) rgb(1, 1, 1)diff --git a/Tests/LibWeb/Text/expected/css/sheet-declarations-intern-once-per-process.txt b/Tests/LibWeb/Text/expected/css/sheet-declarations-intern-once-per-process.txtnew file mode 100644index 00000000000..11767e929ec--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/sheet-declarations-intern-once-per-process.txt@@ -0,0 +1,6 @@+first frame margin-top: 7px+first frame blocks interned: 50+first frame blocks shared: 0+second frame margin-top: 7px+second frame blocks interned: 0+second frame blocks shared: 50diff --git a/Tests/LibWeb/Text/expected/css/style-attribute-shared-text-edit.txt b/Tests/LibWeb/Text/expected/css/style-attribute-shared-text-edit.txtnew file mode 100644index 00000000000..5df6f61ffc5--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-attribute-shared-text-edit.txt@@ -0,0 +1,11 @@+a: rgb(0, 0, 255) 3.5px+a cssText: color: blue; margin-left: 3.5px;+a attribute: color: blue; margin-left: 3.5px;+b: rgb(255, 0, 0) 3.5px+b cssText: color: red; margin-left: 3.5px;+b attribute: color: red; margin-left: 3.5px+c: rgb(255, 0, 0) 3.5px+c cssText: color: red; margin-left: 3.5px;+c attribute: color: red; margin-left: 3.5px+b: rgb(0, 128, 0) 0px color: green;+c: rgb(0, 128, 0) 3.5px color: green; margin-left: 3.5px;diff --git a/Tests/LibWeb/Text/expected/css/style-engine/attr-in-custom-property-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/attr-in-custom-property.txtsimilarity index 51%rename from Tests/LibWeb/Text/expected/css/style-engine/attr-in-custom-property-engine-computed.txtrename to Tests/LibWeb/Text/expected/css/style-engine/attr-in-custom-property.txtindex 35d46287cf1..75ef4e9e434 100644--- a/Tests/LibWeb/Text/expected/css/style-engine/attr-in-custom-property-engine-computed.txt+++ b/Tests/LibWeb/Text/expected/css/style-engine/attr-in-custom-property.txt@@ -1,8 +1,4 @@-C++ recomputations: 0colors: rgb(0, 128, 0) rgb(128, 0, 128) rgb(0, 128, 0)-attribute change C++ recomputations: 0colors: rgb(255, 0, 0) rgb(128, 0, 128) rgb(255, 0, 0)-fallback C++ recomputations: 0fallback width: 1px-fallback attribute change C++ recomputations: 0attribute width: 5pxdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/attr-substitution-backing-element-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/attr-substitution-backing-element.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/attr-substitution-backing-element-engine-computed.txtrename to Tests/LibWeb/Text/expected/css/style-engine/attr-substitution-backing-element.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/attr-substitution-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/attr-substitution-pseudo.txtsimilarity index 50%rename from Tests/LibWeb/Text/expected/css/style-engine/attr-substitution-engine-computed.txtrename to Tests/LibWeb/Text/expected/css/style-engine/attr-substitution-pseudo.txtindex 06928286a79..2cb0804f4de 100644--- a/Tests/LibWeb/Text/expected/css/style-engine/attr-substitution-engine-computed.txt+++ b/Tests/LibWeb/Text/expected/css/style-engine/attr-substitution-pseudo.txt@@ -1,4 +1,2 @@-engine computed the readers: truecolors: rgb(0, 128, 0) rgb(128, 0, 128)-attribute change stays in the engine: truecolors: rgb(255, 0, 0) rgb(128, 0, 128)diff --git a/Tests/LibWeb/Text/expected/css/style-engine/attr-substitution-shorthand-engine-computed.txt b/Tests/LibWeb/Text/expected/css/style-engine/attr-substitution-shorthand.txtsimilarity index 53%rename from Tests/LibWeb/Text/expected/css/style-engine/attr-substitution-shorthand-engine-computed.txtrename to Tests/LibWeb/Text/expected/css/style-engine/attr-substitution-shorthand.txtindex 352bba31966..5045c0050af 100644--- a/Tests/LibWeb/Text/expected/css/style-engine/attr-substitution-shorthand-engine-computed.txt+++ b/Tests/LibWeb/Text/expected/css/style-engine/attr-substitution-shorthand.txt@@ -1,6 +1,4 @@-C++ recomputations on arrival: 0margin: 5pxinvalid color falls back: rgb(0, 128, 0)-C++ recomputations on attribute change: 0margin: 7pxcolor: rgb(0, 0, 255)diff --git a/Tests/LibWeb/Text/expected/css/style-engine/attr-substitution.txt b/Tests/LibWeb/Text/expected/css/style-engine/attr-substitution.txtnew file mode 100644index 00000000000..2cb0804f4de--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-engine/attr-substitution.txt@@ -0,0 +1,2 @@+colors: rgb(0, 128, 0) rgb(128, 0, 128)+colors: rgb(255, 0, 0) rgb(128, 0, 128)diff --git a/Tests/LibWeb/Text/expected/css/style-engine/attribute-writes-before-a-selector-reads-them.txt b/Tests/LibWeb/Text/expected/css/style-engine/attribute-writes-before-a-selector-reads-them.txtnew file mode 100644index 00000000000..b6ec1c38b63--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-engine/attribute-writes-before-a-selector-reads-them.txt@@ -0,0 +1,20 @@+no rules: changed: rgb(0, 0, 0)+no rules: added: rgb(0, 0, 0)+no rules: removed: rgb(0, 0, 0)+no rules: set-then-removed: rgb(0, 0, 0)+written, no rules: changed: rgb(0, 0, 0)+written, no rules: added: rgb(0, 0, 0)+written, no rules: removed: rgb(0, 0, 0)+written, no rules: set-then-removed: rgb(0, 0, 0)+read: changed: rgb(0, 128, 0)+read: added: rgb(0, 128, 0)+read: removed: rgb(0, 0, 0)+read: set-then-removed: rgb(0, 0, 0)+read: changed: rgb(1, 2, 3)+read: added: rgb(1, 2, 3)+read: removed: rgba(0, 0, 0, 0)+read: set-then-removed: rgba(0, 0, 0, 0)+written, read: changed: rgb(255, 0, 0)+written, read: added: rgb(0, 128, 0)+written, read: removed: rgb(0, 0, 0)+written, read: set-then-removed: rgb(255, 0, 0)diff --git a/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-matching.txt b/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-matching.txtnew file mode 100644index 00000000000..1fd3b4d569f--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-engine/cold-pass-matching.txt@@ -0,0 +1,5 @@+styled elements: true+ancestor filter rejected a candidate: true+computed every styled element: true+computed some directly: true+differences: 0diff --git a/Tests/LibWeb/Text/expected/css/style-engine/patched-answer-ranks-follow-dispatch.txt b/Tests/LibWeb/Text/expected/css/style-engine/declaration-edit-reuses-matching.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/patched-answer-ranks-follow-dispatch.txtrename to Tests/LibWeb/Text/expected/css/style-engine/declaration-edit-reuses-matching.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/incremental-sheet-edits.txt b/Tests/LibWeb/Text/expected/css/style-engine/incremental-sheet-edits.txtnew file mode 100644index 00000000000..310e80a8523--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-engine/incremental-sheet-edits.txt@@ -0,0 +1,9 @@+after three inserts: rgb(3, 3, 3)+after deleting the winner: rgb(2, 2, 2)+after retargeting: rgb(2, 2, 2)+after the group: rgb(5, 5, 5)+after deleting the group: rgb(2, 2, 2)+after retargeting all: rgb(2, 2, 2)+after deleting all: rgb(0, 0, 0)+after replaceSync: rgb(6, 6, 6)+after the second replaceSync: rgb(7, 7, 7)diff --git a/Tests/LibWeb/Text/expected/css/style-engine/losing-sheet-winners.txt b/Tests/LibWeb/Text/expected/css/style-engine/losing-sheet-winners.txtnew file mode 100644index 00000000000..dc7d5b070da--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-engine/losing-sheet-winners.txt@@ -0,0 +1,2 @@+ordinary item: rgb(0, 0, 0)+sentinel: rgb(0, 128, 0)diff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-attribute-any-namespace.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-attribute-any-namespace.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-attribute-any-namespace.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-attribute-any-namespace.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-attribute-case.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-attribute-case.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-attribute-case.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-attribute-case.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-attribute-name-case.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-attribute-name-case.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-attribute-name-case.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-attribute-name-case.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-attribute-namespaces.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-attribute-namespaces.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-attribute-namespaces.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-attribute-namespaces.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-combinator-prefilter.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-combinator-prefilter.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-combinator-prefilter.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-combinator-prefilter.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-computed-states.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-computed-states.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-computed-states.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-computed-states.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-conditions.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-conditions.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-conditions.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-conditions.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-default-namespace.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-default-namespace.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-default-namespace.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-default-namespace.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-featureless-host.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-featureless-host.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-featureless-host.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-featureless-host.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-host-argument-descendant.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-host-argument-descendant.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-host-argument-descendant.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-host-argument-descendant.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-host-descendant.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-host-descendant.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-host-descendant.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-host-descendant.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-imports.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-imports.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-imports.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-imports.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-layer-order.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-layer-order.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-layer-order.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-layer-order.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-namespaces.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-namespaces.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-namespaces.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-namespaces.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-nested-scope-retarget.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-nested-scope-retarget.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-nested-scope-retarget.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-nested-scope-retarget.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-nested-scope.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-nested-scope.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-nested-scope.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-nested-scope.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-part-compound.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-part-compound.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-part-compound.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-part-compound.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-part-forwarded.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-part-forwarded.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-part-forwarded.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-part-forwarded.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-part-published-late.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-part-published-late.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-part-published-late.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-part-published-late.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-part-scope.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-part-scope.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-part-scope.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-part-scope.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-part.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-part.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-part.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-part.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-pseudo-elements.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-pseudo-elements.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-pseudo-elements.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-pseudo-elements.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-scope-implicit.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-scope-implicit.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-scope-implicit.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-scope-implicit.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-scope-limit-instance.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-scope-limit-instance.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-scope-limit-instance.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-scope-limit-instance.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-scope-root.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-scope-root.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-scope-root.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-scope-root.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-selector-shapes.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-selector-shapes.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-selector-shapes.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-selector-shapes.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-unsatisfiable.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-unsatisfiable.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-unsatisfiable.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-unsatisfiable.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-use.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-use.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-use.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-use.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement-xml-document.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching-xml-document.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement-xml-document.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching-xml-document.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/match-agreement.txt b/Tests/LibWeb/Text/expected/css/style-engine/matching.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/match-agreement.txtrename to Tests/LibWeb/Text/expected/css/style-engine/matching.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/prefix-positional-truth-across-feature-and-tree-changes.txt b/Tests/LibWeb/Text/expected/css/style-engine/positional-selectors-across-feature-and-tree-changes.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/prefix-positional-truth-across-feature-and-tree-changes.txtrename to Tests/LibWeb/Text/expected/css/style-engine/positional-selectors-across-feature-and-tree-changes.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/rule-edit-activation.txt b/Tests/LibWeb/Text/expected/css/style-engine/rule-edit-activation.txtnew file mode 100644index 00000000000..316a4d682c0--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-engine/rule-edit-activation.txt@@ -0,0 +1,2 @@+active color: rgb(255, 0, 0)+inactive color: rgb(0, 0, 255)diff --git a/Tests/LibWeb/Text/expected/css/style-engine/selector-answer-patch-program-changes.txt b/Tests/LibWeb/Text/expected/css/style-engine/rule-edit-program-changes.txtsimilarity index 74%rename from Tests/LibWeb/Text/expected/css/style-engine/selector-answer-patch-program-changes.txtrename to Tests/LibWeb/Text/expected/css/style-engine/rule-edit-program-changes.txtindex 075b7f12f42..c8e1511db7d 100644--- a/Tests/LibWeb/Text/expected/css/style-engine/selector-answer-patch-program-changes.txt+++ b/Tests/LibWeb/Text/expected/css/style-engine/rule-edit-program-changes.txt@@ -1,10 +1,6 @@retargeted color: rgb(0, 128, 0)restored selector color: rgb(0, 0, 255)inserted rule color: rgb(255, 0, 0)-answer patches: 5-answer reuses: 4-cold node evaluations: 0-invalidated nodes: 4deleted rule color: rgb(0, 0, 255)selector-list winner color: rgb(0, 0, 255)removed selector-list winner color: rgb(0, 128, 0)diff --git a/Tests/LibWeb/Text/expected/css/style-engine/rule-edit-ranks-follow-dispatch.txt b/Tests/LibWeb/Text/expected/css/style-engine/rule-edit-ranks-follow-dispatch.txtnew file mode 100644index 00000000000..45ec1750ddb--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-engine/rule-edit-ranks-follow-dispatch.txt@@ -0,0 +1 @@+color: rgb(0, 0, 255)diff --git a/Tests/LibWeb/Text/expected/css/style-engine/rule-edit-sheet-activation.txt b/Tests/LibWeb/Text/expected/css/style-engine/rule-edit-sheet-activation.txtnew file mode 100644index 00000000000..316a4d682c0--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-engine/rule-edit-sheet-activation.txt@@ -0,0 +1,2 @@+active color: rgb(255, 0, 0)+inactive color: rgb(0, 0, 255)diff --git a/Tests/LibWeb/Text/expected/css/style-engine/rule-edit-sheet-attachment.txt b/Tests/LibWeb/Text/expected/css/style-engine/rule-edit-sheet-attachment.txtnew file mode 100644index 00000000000..858c1c79a66--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-engine/rule-edit-sheet-attachment.txt@@ -0,0 +1,2 @@+attached color: rgb(255, 0, 0)+detached color: rgb(0, 128, 0)diff --git a/Tests/LibWeb/Text/expected/css/style-engine/rule-edit-stops-at-unchanged-signature.txt b/Tests/LibWeb/Text/expected/css/style-engine/rule-edit-stops-at-unchanged-signature.txtnew file mode 100644index 00000000000..45ec1750ddb--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-engine/rule-edit-stops-at-unchanged-signature.txt@@ -0,0 +1 @@+color: rgb(0, 0, 255)diff --git a/Tests/LibWeb/Text/expected/css/style-engine/rule-edit-updates-signature.txt b/Tests/LibWeb/Text/expected/css/style-engine/rule-edit-updates-signature.txtnew file mode 100644index 00000000000..316a4d682c0--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-engine/rule-edit-updates-signature.txt@@ -0,0 +1,2 @@+active color: rgb(255, 0, 0)+inactive color: rgb(0, 0, 255)diff --git a/Tests/LibWeb/Text/expected/css/style-engine/rule-index-incremental-updates.txt b/Tests/LibWeb/Text/expected/css/style-engine/rule-index-incremental-updates.txtnew file mode 100644index 00000000000..d993c90a0f8--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-engine/rule-index-incremental-updates.txt@@ -0,0 +1,16 @@+appended sheet: index builds 0, entries indexed 1, full passes 0, hinted <= 2 true+target: rgb(0, 128, 0)+inserted rule: index builds 0, entries indexed 2, full passes 0, hinted <= 2 true+other: rgb(0, 0, 255)+edited rule: index builds 0, entries indexed 1, full passes 0, hinted <= 2 true+other: rgb(255, 165, 0)+deleted rule: index builds 0, entries indexed 0, full passes 0, hinted <= 2 true+other: rgb(0, 0, 0)+media off: index builds 0, entries indexed 0, full passes 0, hinted <= 2 true+target: rgb(0, 0, 0)+media on: index builds 0, entries indexed 1, full passes 0, hinted <= 2 true+target: rgb(0, 128, 0)+removed sheet: index builds 0, entries indexed 0, full passes 0, hinted <= 2 true+target: rgb(0, 0, 0)+sheet inserted before: index builds 0, entries indexed 1, full passes 0, hinted <= 2 true+target: rgb(0, 128, 0)diff --git a/Tests/LibWeb/Text/expected/css/style-engine/rule-inserted-after-attach-reaches-engine.txt b/Tests/LibWeb/Text/expected/css/style-engine/rule-inserted-after-attach-reaches-engine.txtnew file mode 100644index 00000000000..468d1725cf5--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-engine/rule-inserted-after-attach-reaches-engine.txt@@ -0,0 +1,5 @@+full pass: false+changed: [target, item]+styled only what changed: true+item color: rgb(0, 128, 0)+after delete: rgb(0, 0, 0)diff --git a/Tests/LibWeb/Text/expected/css/style-engine/prefix-convergence-settles-exactly.txt b/Tests/LibWeb/Text/expected/css/style-engine/selector-matching-settles-exactly.txtsimilarity index 90%rename from Tests/LibWeb/Text/expected/css/style-engine/prefix-convergence-settles-exactly.txtrename to Tests/LibWeb/Text/expected/css/style-engine/selector-matching-settles-exactly.txtindex 2c53b6c6ff9..8421560cb34 100644--- a/Tests/LibWeb/Text/expected/css/style-engine/prefix-convergence-settles-exactly.txt+++ b/Tests/LibWeb/Text/expected/css/style-engine/selector-matching-settles-exactly.txt@@ -12,5 +12,3 @@ and leaves the host again: settles exactlya subtree arrives as its guard does: settles exactlythe guard leaves the arrived subtree: settles exactlya state changes under the guard: settles exactly-convergence planned some of these: true-and stopped propagation somewhere: truediff --git a/Tests/LibWeb/Text/expected/css/style-engine/prefix-transition-memo-after-retention.txt b/Tests/LibWeb/Text/expected/css/style-engine/selector-memo-after-retention.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/prefix-transition-memo-after-retention.txtrename to Tests/LibWeb/Text/expected/css/style-engine/selector-memo-after-retention.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/prefix-transition-memo-local-deltas.txt b/Tests/LibWeb/Text/expected/css/style-engine/selector-memo-local-changes.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/prefix-transition-memo-local-deltas.txtrename to Tests/LibWeb/Text/expected/css/style-engine/selector-memo-local-changes.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-engine/prefix-relation-survives-foreign-scope-inputs.txt b/Tests/LibWeb/Text/expected/css/style-engine/selector-relation-survives-foreign-scope-inputs.txtsimilarity index 75%rename from Tests/LibWeb/Text/expected/css/style-engine/prefix-relation-survives-foreign-scope-inputs.txtrename to Tests/LibWeb/Text/expected/css/style-engine/selector-relation-survives-foreign-scope-inputs.txtindex 312849754cc..57342c17c94 100644--- a/Tests/LibWeb/Text/expected/css/style-engine/prefix-relation-survives-foreign-scope-inputs.txt+++ b/Tests/LibWeb/Text/expected/css/style-engine/selector-relation-survives-foreign-scope-inputs.txt@@ -1,7 +1,7 @@-a value arrives in the text control as a guard does: settles exactly, relation maintained+a value arrives in the text control as a guard does: settles exactlyguarded targets recolored: true-the control is cleared as the guard moves to the child: settles exactly, relation maintained-a guard arrives inside the shadow tree as the document guard leaves: settles exactly, relation maintained+the control is cleared as the guard moves to the child: settles exactly+a guard arrives inside the shadow tree as the document guard leaves: settles exactlyshadow guard recolored its inner element: true-the shadow guard leaves as a sibling guard arrives: settles exactly, relation maintained+the shadow guard leaves as a sibling guard arrives: settles exactlysibling guard reached the later target: truediff --git a/Tests/LibWeb/Text/expected/css/style-engine/selector-relation-survives-tree-scope-moves.txt b/Tests/LibWeb/Text/expected/css/style-engine/selector-relation-survives-tree-scope-moves.txtnew file mode 100644index 00000000000..717b714b21a--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-engine/selector-relation-survives-tree-scope-moves.txt@@ -0,0 +1,14 @@+a guarded target moves into the shadow tree: settles exactly+the document guard no longer reaches it: true+a guard arrives around it inside the shadow tree: settles exactly+it moves back under the document guard: settles exactly+the document guard reaches it again: true+the document guard leaves as the shadow guard does: settles exactly+a guard arrives in the shadow tree sharing the document's selector: settles exactly+the shadow tree's own guard rule reaches the node born there: true+that guard leaves: settles exactly+the other target moves into that shadow tree: settles exactly+a guard arrives around it there: settles exactly+the shadow tree's own guard rule reaches both: true+it moves back as the document guard returns: settles exactly+the document guard reaches both again: truediff --git a/Tests/LibWeb/Text/expected/css/style-engine/retained-prefix-states-settle-exactly.txt b/Tests/LibWeb/Text/expected/css/style-engine/selector-states-settle-exactly.txtsimilarity index 86%rename from Tests/LibWeb/Text/expected/css/style-engine/retained-prefix-states-settle-exactly.txtrename to Tests/LibWeb/Text/expected/css/style-engine/selector-states-settle-exactly.txtindex fda95ff02d5..f2f5b050303 100644--- a/Tests/LibWeb/Text/expected/css/style-engine/retained-prefix-states-settle-exactly.txt+++ b/Tests/LibWeb/Text/expected/css/style-engine/selector-states-settle-exactly.txt@@ -1,3 +1,2 @@-invalidation consumed retained selector state: truestale settlements: 0final: =rgb(0, 0, 0)/rgb(0, 0, 0)/rgb(0, 0, 0) =rgb(0, 0, 0)/rgb(0, 0, 0)/rgb(0, 0, 0) target=rgb(0, 0, 0)/rgb(0, 0, 0)/rgb(0, 0, 0) deep=rgb(0, 0, 0)/rgb(0, 0, 0)/rgb(0, 0, 0) =rgb(0, 0, 0)/rgb(0, 0, 0)/rgb(0, 0, 0) target=rgb(0, 0, 0)/rgb(0, 0, 0)/rgb(0, 0, 0) deep=rgb(0, 0, 0)/rgb(0, 0, 0)/rgb(0, 0, 0)diff --git a/Tests/LibWeb/Text/expected/css/style-engine/shared-match-answer-pseudo-kinds.txt b/Tests/LibWeb/Text/expected/css/style-engine/shared-matching-pseudo-kinds.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/shared-match-answer-pseudo-kinds.txtrename to Tests/LibWeb/Text/expected/css/style-engine/shared-matching-pseudo-kinds.txtdiff --git a/Tests/LibWeb/Text/expected/css/style-graph-patches-one-rule.txt b/Tests/LibWeb/Text/expected/css/style-engine/sheet-edit-moves-one-rule.txtsimilarity index 58%rename from Tests/LibWeb/Text/expected/css/style-graph-patches-one-rule.txtrename to Tests/LibWeb/Text/expected/css/style-engine/sheet-edit-moves-one-rule.txtindex 398cf5f5cbb..7b5171c7df1 100644--- a/Tests/LibWeb/Text/expected/css/style-graph-patches-one-rule.txt+++ b/Tests/LibWeb/Text/expected/css/style-engine/sheet-edit-moves-one-rule.txt@@ -1,7 +1,4 @@-rules compiled by insertRule: 1target colour: rgb(0, 128, 0)rule index 1: #target:focus-rules compiled by selectorText: 1target colour after edit: rgb(0, 128, 0)-rules compiled by deleteRule: 0target colour after delete: rgb(0, 0, 0)diff --git a/Tests/LibWeb/Text/expected/css/style-engine/stale-match-answer-retired-by-plan.txt b/Tests/LibWeb/Text/expected/css/style-engine/stale-matching-retired.txtsimilarity index 100%rename from Tests/LibWeb/Text/expected/css/style-engine/stale-match-answer-retired-by-plan.txtrename to Tests/LibWeb/Text/expected/css/style-engine/stale-matching-retired.txtdiff --git a/Tests/LibWeb/Text/input/DOM/selector-queries-by-class-in-subtrees.html b/Tests/LibWeb/Text/input/DOM/selector-queries-by-class-in-subtrees.htmlnew file mode 100644index 00000000000..7d5f0485ba1--- /dev/null+++ b/Tests/LibWeb/Text/input/DOM/selector-queries-by-class-in-subtrees.html@@ -0,0 +1,63 @@+<!DOCTYPE html>+<div id="root"><section id="a"><div id="a1"><span id="a2"></span></div></section><section id="b"><div id="b1" class="early"></div></section></div>+<script src="../include.js"></script>+<script>+ test(() => {+ const root = document.getElementById("root");+ const show = (label, selector) => println(`${label}: ${selector}: ${Array.from(document.querySelectorAll(selector), element => element.id).join(" ")}`);++ show("from the parser", ".early");+ show("from the parser", "section .early");+ show("before any", ".late");++ document.getElementById("a2").classList.add("late");+ show("class added deep in a subtree", ".late");+ show("class added deep in a subtree", "#root .late");+ show("class added deep in a subtree", ".late span, section .late");++ document.getElementById("a2").setAttribute("class", "other");+ show("class replaced", ".late");+ show("class replaced", ".other");+ document.getElementById("a2").removeAttribute("class");+ show("class removed", ".other");++ const detached = document.createElement("div");+ detached.id = "moved";+ detached.innerHTML = `<p id="moved1"><i id="moved2" class="carried"></i></p>`;+ show("before insertion", ".carried");+ document.getElementById("b1").append(detached);+ show("subtree inserted", ".carried");+ show("subtree inserted", "section .carried");++ const clone = document.getElementById("a").cloneNode(true);+ clone.id = "clone";+ clone.querySelector("span").id = "clone2";+ clone.querySelector("span").className = "cloned";+ root.append(clone);+ show("clone", ".cloned");++ const html = document.createElement("div");+ html.id = "html";+ root.append(html);+ html.innerHTML = `<b id="html1" class="parsed"></b>`;+ show("innerHTML", ".parsed");++ const list = document.getElementById("a1").classList;+ list.toggle("toggled");+ show("toggled on", ".toggled");+ list.toggle("toggled");+ show("toggled off", ".toggled");++ // A class left of the subject has to be in the tree as well.+ show("left of the subject", ".missing span");+ show("left of the subject", ".early ~ span, .missing span");+ show("left of the subject", ".parsed, .missing span");+ show("attribute left of the subject", "[nope] span");+ document.getElementById("a").setAttribute("nope", "");+ show("attribute left of the subject", "[nope] span");+ println(`disconnected: ${Array.from(detached.cloneNode(true).querySelectorAll(".carried"), element => element.id).join(" ")}`);+ const shadow = document.createElement("div").attachShadow({ mode: "open" });+ shadow.innerHTML = `<p class="in-shadow"><span id="shadow1"></span></p>`;+ println(`shadow: ${Array.from(shadow.querySelectorAll(".in-shadow span"), element => element.id).join(" ")}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/DOM/selector-queries-by-class.html b/Tests/LibWeb/Text/input/DOM/selector-queries-by-class.htmlnew file mode 100644index 00000000000..46e05809878--- /dev/null+++ b/Tests/LibWeb/Text/input/DOM/selector-queries-by-class.html@@ -0,0 +1,22 @@+<!DOCTYPE html>+<div id="root">+ <p id="p1" class="x"></p>+ <p id="p2" class="x y"></p>+ <div id="d1" class="x"><span id="s1" class="y X"></span></div>+ <div id="d2" class="z"><span id="s2" class="x z"></span></div>+</div>+<script src="../include.js"></script>+<script>+ test(() => {+ const root = document.getElementById("root");+ // The class every selector's subject requires decides which elements are matched at all.+ for (const selector of [".x", ".X", ".x.y", "p.x, div.x", ".x, .y", ".y.x, .x.z", "div .x", ".x:not(.y)", ".z .x", ":is(.x)", ".x, :not(.x)"]) {+ const ids = Array.from(root.querySelectorAll(selector), element => element.id);+ const first = root.querySelector(selector);+ println(`${selector}: ${ids.join(" ")} (first: ${first ? first.id : "none"})`);+ }+ // A class added after a query is found by the next one.+ document.getElementById("d2").classList.add("x");+ println(`after class change: ${Array.from(root.querySelectorAll("div.x"), element => element.id).join(" ")}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/DOM/selector-queries-by-id.html b/Tests/LibWeb/Text/input/DOM/selector-queries-by-id.htmlnew file mode 100644index 00000000000..4cebae426fd--- /dev/null+++ b/Tests/LibWeb/Text/input/DOM/selector-queries-by-id.html@@ -0,0 +1,65 @@+<!DOCTYPE html>+<div id="root">+ <p id="one" class="c"><span id="s1" class="c"></span><span id="s2"></span></p>+ <p id="dup" class="first"><span id="d1" class="c"></span><i id="dup" class="nested"><span id="d2" class="c"></span></i></p>+ <p id="dup" class="last"><span id="d3" class="c"></span></p>+ <b id="sib"></b><span id="after1" class="c"></span><em><span id="inside" class="c"></span></em><span id="after2" class="c"></span>+</div>+<div id="host"></div>+<script src="../include.js"></script>+<script>+ function ids(list) {+ return Array.from(list, element => `${element.id || element.tagName}.${element.className}`).join(" ") || "(none)";+ }++ test(() => {+ const root = document.getElementById("root");+ const one = document.getElementById("one");+ const shadow = document.getElementById("host").attachShadow({ mode: "open" });+ shadow.innerHTML = `<p id="one"><span id="shadow-span" class="c"></span></p><b id="sib"></b><span id="shadow-after"></span>`;+ const detached = document.createElement("div");+ detached.innerHTML = `<p id="one"><span id="detached-span"></span></p>`;++ const queries = [+ [document, "#one"],+ [document, "#missing"],+ [document, "#missing .c"],+ [document, "#dup"],+ [document, "p#dup"],+ [document, "#dup.last"],+ [document, "#dup .c"],+ [document, "#dup > .c"],+ [document, "#one .c"],+ [document, "#one > span"],+ [document, "#sib ~ span"],+ [document, "#sib + span"],+ [document, "#sib ~ * .c"],+ [document, "#root #one span"],+ [document, "#one ~ p span"],+ [root, "#one"],+ [root, "#root span"],+ [root, "#root > p"],+ [one, "#one span"],+ [one, "#one"],+ [one, "#sib ~ span"],+ [one.firstElementChild, "#one span"],+ [shadow, "#one"],+ [shadow, "#one span"],+ [shadow, "#sib + span"],+ [shadow, "#root"],+ [detached, "#one span"],+ [detached, "#one"],+ ];+ for (const [scope, selector] of queries) {+ const name = scope === document ? "document" : scope === shadow ? "shadow" : scope === detached ? "detached" : scope.id;+ const first = scope.querySelector(selector);+ println(`${name} ${selector}: ${ids(scope.querySelectorAll(selector))} (first: ${first ? ids([first]) : "none"})`);+ }++ // A query made again sees the ids the tree has now.+ document.getElementById("s2").id = "moved";+ println(`after id change: ${ids(document.querySelectorAll("#moved"))} ${ids(document.querySelectorAll("#s2"))}`);+ document.getElementById("d3").parentElement.remove();+ println(`after removal: ${ids(document.querySelectorAll("#dup"))} ${ids(document.querySelectorAll("#dup .c"))}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/DOM/selector-queries-never-matching-selectors.html b/Tests/LibWeb/Text/input/DOM/selector-queries-never-matching-selectors.htmlnew file mode 100644index 00000000000..d2161995968--- /dev/null+++ b/Tests/LibWeb/Text/input/DOM/selector-queries-never-matching-selectors.html@@ -0,0 +1,33 @@+<!DOCTYPE html>+<div id="root"><p id="p1" class="x"></p><p id="p2"></p><b id="b1" class="x"></b><span id="only"></span></div>+<script src="../include.js"></script>+<script>+ test(() => {+ const root = document.getElementById("root");+ // A selector no element can match leaves what the other selectors of the list need in charge.+ for (const selector of [+ ":is(:unknown)",+ ":is(:unknown), :where(:unknown)",+ "p, :is(:unknown)",+ ":is(:unknown), .x",+ ".x, b:where(:unknown), p:is(:unknown)",+ "#only, :is(:unknown)",+ ":is(:unknown) #only, #root > span",+ ":is(:unknown) > p, b",+ ":not(:is(:unknown)) ~ b",+ ":is(:unknown) ~ b, [id=p2]",+ ":where(:unknown) span, span",+ ]) {+ try {+ root.querySelector(selector);+ } catch (error) {+ println(`${selector}: ${error.name}`);+ continue;+ }+ const ids = Array.from(root.querySelectorAll(selector), element => element.id);+ const first = root.querySelector(selector);+ const p1 = document.getElementById("p1");+ println(`${selector}: ${ids.join(" ")} (first: ${first ? first.id : "none"}) (p1 matches: ${p1.matches(selector)}, closest: ${p1.closest(selector)?.id ?? "none"})`);+ }+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/attribute-names-in-compound-bloom.html b/Tests/LibWeb/Text/input/css/attribute-names-in-compound-bloom.htmlnew file mode 100644index 00000000000..d9d781dffbc--- /dev/null+++ b/Tests/LibWeb/Text/input/css/attribute-names-in-compound-bloom.html@@ -0,0 +1,88 @@+<!doctype html>+<script src="../include.js"></script>+<style>+ @namespace xlink url("http://www.w3.org/1999/xlink");+ .subject[data-lower] { color: rgb(0, 128, 0); }+ [data-ancestor] .below { color: rgb(0, 128, 0); }+ [data-parent] > .child { color: rgb(0, 128, 0); }+ .upper[DATA-UPPER] { color: rgb(0, 128, 0); }+ .written-upper[data-written-upper] { color: rgb(0, 128, 0); }+ .any-namespace[*|href] { color: rgb(0, 128, 0); }+ .named[xlink|href] { color: rgb(0, 128, 0); }+ .no-namespace[href] { color: rgb(0, 128, 0); }+ .svg-lower[viewbox] { color: rgb(0, 128, 0); }+ .svg-written[viewBox] { color: rgb(0, 128, 0); }+ .value[type="text" i] { color: rgb(0, 128, 0); }+ .late[data-late] { color: rgb(0, 128, 0); }+ .script[data-script] { color: rgb(0, 128, 0); }+</style>+<div id="root"></div>+<script>+ // Each compound here tests an attribute, which an element is rejected on before its selector is read where it can+ // carry no such name: a name written or carried in another case or namespace has to stay out of that.+ test(() => {+ const root = document.getElementById("root");+ const add = html => {+ const template = document.createElement("template");+ template.innerHTML = html;+ const element = template.content.firstElementChild;+ root.append(element);+ return element;+ };+ const report = (title, element) => println(`${title}: ${getComputedStyle(element).color}`);+ report("subject", add("<div class=subject data-lower></div>"));+ report("subject without", add("<div class=subject></div>"));+ report("ancestor", add("<div data-ancestor><p><b class=below></b></p></div>").querySelector("b"));+ report("no ancestor", add("<div><p><b class=below></b></p></div>").querySelector("b"));+ report("parent", add("<div data-parent><b class=child></b></div>").querySelector("b"));+ report("upper in the selector", add("<div class=upper data-upper></div>"));+ report("upper in the source", add("<div class=written-upper DATA-WRITTEN-UPPER></div>"));+ report("value case", add("<input class=value type=TEXT>"));++ const namespaced = name => {+ const element = document.createElement("div");+ element.setAttributeNS("http://www.w3.org/1999/xlink", name, "x");+ root.append(element);+ return element;+ };+ const anyNamespace = namespaced("xlink:href");+ anyNamespace.className = "any-namespace";+ report("any namespace", anyNamespace);+ const named = namespaced("xlink:href");+ named.className = "named";+ report("named namespace", named);+ const noNamespace = namespaced("xlink:href");+ noNamespace.className = "no-namespace";+ report("no namespace on a namespaced attribute", noNamespace);++ report("svg lowercase selector", add('<svg class=svg-lower viewBox="0 0 1 1"></svg>'));+ report("svg written selector", add('<svg class=svg-written viewBox="0 0 1 1"></svg>'));++ // A name set while no rule reads it, then read by a rule arriving later.+ const late = add("<div class=late></div>");+ late.setAttribute("data-unread", "");+ report("late before", late);+ late.setAttribute("data-late", "");+ report("late after", late);+ late.removeAttribute("data-late");+ report("late removed", late);++ const script = add("<div class=script></div>");+ report("script before", script);+ script.setAttribute("DATA-SCRIPT", "");+ report("script set in another case", script);+ const below = add("<div><b class=below></b></div>");+ report("ancestor before", below.firstElementChild);+ below.setAttribute("data-ancestor", "");+ report("ancestor set", below.firstElementChild);+ below.removeAttribute("data-ancestor");+ report("ancestor removed", below.firstElementChild);++ const style = document.createElement("style");+ style.textContent = ".arrives[data-withheld] { color: rgb(0, 128, 0); }";+ const withheld = add("<div class=arrives data-withheld></div>");+ report("withheld before", withheld);+ document.head.append(style);+ report("withheld read by a rule arriving", withheld);+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/document-rules-naming-the-host-of-a-use-element.html b/Tests/LibWeb/Text/input/css/document-rules-naming-the-host-of-a-use-element.htmlnew file mode 100644index 00000000000..860fb0ed048--- /dev/null+++ b/Tests/LibWeb/Text/input/css/document-rules-naming-the-host-of-a-use-element.html@@ -0,0 +1,28 @@+<!DOCTYPE html>+<style>+ :host {+ display: block;+ --from-host: "matched";+ }+</style>+<svg>+ <defs>+ <symbol id="symbol"><rect id="rect" width="10" height="10"></rect></symbol>+ </defs>+ <use id="use" href="#symbol"></use>+</svg>+<script src="../include.js"></script>+<script>+ function report(label) {+ const style = getComputedStyle(document.getElementById("use"));+ println(`${label}: display ${style.display}, z-index ${style.zIndex}, --from-host "${style.getPropertyValue("--from-host")}"`);+ }++ test(() => {+ report("at load");+ const sheet = document.createElement("style");+ sheet.textContent = ":host { z-index: 1; }";+ document.head.append(sheet);+ report("a later sheet");+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/media-flips-in-a-sheet-kept-in-a-segment.html b/Tests/LibWeb/Text/input/css/media-flips-in-a-sheet-kept-in-a-segment.htmlnew file mode 100644index 00000000000..26a8686c902--- /dev/null+++ b/Tests/LibWeb/Text/input/css/media-flips-in-a-sheet-kept-in-a-segment.html@@ -0,0 +1,57 @@+<!doctype html>+<script src="../include.js"></script>+<iframe id="frame" style="width: 600px; height: 100px"></iframe>+<script>+ // A rule under a media query that stops holding leaves the document alone: the sheet stays as it is for the rest of+ // its rules, however often the query flips, and what the rule tested still restyles the rest of them.+ asyncTest(async done => {+ const frame = document.getElementById("frame");+ const doc = frame.contentDocument;+ doc.open();+ doc.write("<!doctype html><body></body>");+ doc.close();+ let text = "";+ for (let i = 0; i < 100; ++i)+ text += `.filler${i} { top: ${i}px; }\n`;+ text += "@media (min-width: 300px) { .a { color: rgb(0, 128, 0); } .p > .c { padding-left: 2px; } }\n";+ text += "@media (max-width: 299px) { .a { color: rgb(0, 0, 255); } }\n";+ text += ".b { margin-left: 3px; } .p > .d { margin-top: 4px; }\n";+ const style = doc.createElement("style");+ style.textContent = text;+ doc.head.append(style);+ doc.body.innerHTML = '<div id="parent"><i id="a" class="a"></i><i id="b"></i><i id="c" class="c"></i><i id="d" class="d"></i></div>';+ const $ = id => doc.getElementById(id);+ const say = label => {+ const view = frame.contentWindow;+ const style = id => view.getComputedStyle($(id));+ println(`${label}: a ${style("a").color}, b ${style("b").marginLeft}, c ${style("c").paddingLeft}, d ${style("d").marginTop}`);+ };+ await animationFrame();+ say("wide");+ for (const round of [1, 2, 3]) {+ frame.style.width = "200px";+ await animationFrame();+ await animationFrame();+ say(`narrow ${round}`);+ $("parent").classList.add("p");+ $("b").classList.add("b");+ await animationFrame();+ say(`narrow, classes on ${round}`);+ frame.style.width = "600px";+ await animationFrame();+ await animationFrame();+ say(`wide ${round}`);+ $("parent").classList.remove("p");+ $("b").classList.remove("b");+ await animationFrame();+ say(`wide, classes off ${round}`);+ }+ style.sheet.deleteRule(0);+ await animationFrame();+ say("after a rule was deleted");+ style.sheet.insertRule(".a { color: rgb(1, 2, 3); }", style.sheet.cssRules.length);+ await animationFrame();+ say("after a rule was inserted");+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/nesting-selector-follows-cssom-edits.html b/Tests/LibWeb/Text/input/css/nesting-selector-follows-cssom-edits.htmlnew file mode 100644index 00000000000..6f217aed1e4--- /dev/null+++ b/Tests/LibWeb/Text/input/css/nesting-selector-follows-cssom-edits.html@@ -0,0 +1,46 @@+<!doctype html>+<meta charset="utf-8">+<script src="../include.js"></script>+<div class="a"><div class="b"><span class="c" id="first"></span></div></div>+<div class="x"><div class="b"><span class="c" id="second"></span></div></div>+<script>+test(() => {+ const sheet = new CSSStyleSheet();+ sheet.replaceSync(`.a {+ .b {+ & .c { width: 11px; }+ }+ }+ span { display: block; height: 1px; width: 1px; }`);+ document.adoptedStyleSheets = [sheet];+ const snapshot = label => println(`${label}: ${["first", "second"].map(id => {+ const style = getComputedStyle(document.getElementById(id));+ return `${style.width}/${style.height}/${style.color}`;+ }).join(" | ")}`);+ snapshot("initial");++ // A grandparent's selectors are what the grandchild's & reaches through its parent.+ const outer = sheet.cssRules[0];+ outer.selectorText = ".x";+ snapshot("grandparent edited");++ // A rule inserted under a nested rule names it with &.+ const middle = outer.cssRules[0];+ middle.insertRule("& > .c { height: 7px; }", 1);+ snapshot("child inserted");++ // An @scope inserted under a style rule roots at what its & names.+ outer.insertRule("@scope (&) { .c { color: rgb(0, 128, 0); } }", 1);+ snapshot("scope inserted");++ // Editing the outer rule again moves every one of them.+ outer.selectorText = ".a";+ snapshot("grandparent restored");++ // A more specific & wins over an equally written rule declared later.+ sheet.insertRule("#first.c { width: 3px; }", 1);+ outer.selectorText = "#nothing, .a";+ snapshot("specificity through &");+ document.adoptedStyleSheets = [];+});+</script>diff --git a/Tests/LibWeb/Text/input/css/position-try-replaced-rule-leaves-last-successful-option.html b/Tests/LibWeb/Text/input/css/position-try-replaced-rule-leaves-last-successful-option.htmlnew file mode 100644index 00000000000..59415844d21--- /dev/null+++ b/Tests/LibWeb/Text/input/css/position-try-replaced-rule-leaves-last-successful-option.html@@ -0,0 +1,33 @@+<!DOCTYPE html>+<style id="rules">+ @position-try --a { top: 0px; left: 200px; }+</style>+<style>+ #container { position: relative; width: 300px; height: 300px; }+ #box { position: absolute; top: 500px; left: 0; width: 50px; height: 50px; position-try-fallbacks: --a; }+</style>+<div id="container"><div id="box"></div></div>+<script src="../include.js"></script>+<script>+ // A box whose last successful position option came from a @position-try rule goes back to its base styles once that+ // rule is replaced, even where the replacing rule's declarations land on the address of the old ones, as they will+ // often enough over many edits with a style flush but no layout between.+ test(() => {+ const rules = document.getElementById("rules");+ const box = document.getElementById("box");+ let kept = 0;+ for (let i = 0; i < 200; ++i) {+ box.style.top = "500px";+ box.offsetWidth;+ // The base styles fit now, which the box only finds if it starts from them.+ box.style.top = "10px";+ rules.textContent = `@position-try --a { top: 0px; left: ${200 + i % 2}px; }`;+ getComputedStyle(box).color;+ rules.textContent = `@position-try --a { top: 0px; left: ${202 + i % 2}px; }`;+ getComputedStyle(box).color;+ if (box.getBoundingClientRect().left - container.getBoundingClientRect().left !== 0)+ ++kept;+ }+ println(`${kept} of 200 kept an option of a replaced rule`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/selector-left-of-a-subject-its-bucket-proves.html b/Tests/LibWeb/Text/input/css/selector-left-of-a-subject-its-bucket-proves.htmlnew file mode 100644index 00000000000..1cc8552e674--- /dev/null+++ b/Tests/LibWeb/Text/input/css/selector-left-of-a-subject-its-bucket-proves.html@@ -0,0 +1,79 @@+<!doctype html>+<script src="../include.js"></script>+<style>+ .a .class-subject { color: rgb(0, 128, 0); }+ .a #id-subject { color: rgb(0, 128, 0); }+ .a tag-subject { color: rgb(0, 128, 0); }+ .a TAG-WRITTEN-UPPER { color: rgb(0, 128, 0); }+ .a .UPPER-CLASS-SUBJECT { color: rgb(0, 128, 0); }+ .a * { background-color: rgb(0, 128, 0); }+ .a > :checked { color: rgb(0, 128, 0); }+ .a + .next-subject { color: rgb(0, 128, 0); }+ .a ~ .later-subject { color: rgb(0, 128, 0); }+ .a .pseudo-subject::before { color: rgb(0, 128, 0); }+ :has(.has-witness) .after-has { color: rgb(0, 128, 0); }+ .a div.two-part-subject { color: rgb(0, 128, 0); }+ @scope (.a) { .scoped-subject { color: rgb(0, 128, 0); } }+ @scope (.a) { :scope .scope-subject { color: rgb(0, 128, 0); } }+</style>+<svg id="svg-host"></svg>+<div id="root"></div>+<script>+ // The bucket an element reaches a selector by can prove the subject compound, so that matching starts left of it:+ // what the rest of the selector asks of other elements is still asked, for an element with and without them.+ test(() => {+ const root = document.getElementById("root");+ const add = (parent, html) => {+ const template = document.createElement("template");+ template.innerHTML = html;+ const element = template.content.firstElementChild;+ parent.append(element);+ return element;+ };+ const subjects = [+ "<div class=class-subject></div>",+ "<div id=id-subject></div>",+ "<tag-subject></tag-subject>",+ "<tag-written-upper></tag-written-upper>",+ "<div class=UPPER-CLASS-SUBJECT></div>",+ "<input type=checkbox checked>",+ "<div class=two-part-subject></div>",+ "<p class=two-part-subject></p>",+ "<div class=scoped-subject></div>",+ "<div class=scope-subject></div>",+ ];+ for (const html of subjects) {+ const outside = add(add(root, "<div></div>"), html);+ const inside = add(add(root, "<div class=a></div>"), html);+ println(`${html} outside: ${getComputedStyle(outside).color} ${getComputedStyle(outside).backgroundColor}`);+ println(`${html} inside: ${getComputedStyle(inside).color} ${getComputedStyle(inside).backgroundColor}`);+ }++ const siblings = add(root, "<div><i class=a></i><b class=next-subject></b><b class=later-subject></b></div>");+ println(`next: ${getComputedStyle(siblings.children[1]).color}`);+ println(`later: ${getComputedStyle(siblings.children[2]).color}`);+ siblings.firstElementChild.className = "";+ println(`next without: ${getComputedStyle(siblings.children[1]).color}`);+ println(`later without: ${getComputedStyle(siblings.children[2]).color}`);++ const pseudo = add(add(root, "<div class=a></div>"), "<div class=pseudo-subject></div>");+ println(`pseudo: ${getComputedStyle(pseudo, "::before").color}`);+ pseudo.parentElement.className = "";+ println(`pseudo without: ${getComputedStyle(pseudo, "::before").color}`);++ const has = add(root, "<div><i class=has-witness></i><b class=after-has></b></div>");+ println(`has: ${getComputedStyle(has.lastElementChild).color}`);+ has.firstElementChild.className = "";+ println(`has without: ${getComputedStyle(has.lastElementChild).color}`);++ // An element outside the HTML namespace is reached by the folding of its tag too.+ const svgRule = document.createElement("style");+ svgRule.textContent = ".a lineargradient { color: rgb(0, 128, 0); } .a svgwritten { color: rgb(255, 0, 0); }";+ document.head.append(svgRule);+ const svg = document.getElementById("svg-host");+ svg.setAttribute("class", "a");+ const gradient = document.createElementNS("http://www.w3.org/2000/svg", "linearGradient");+ svg.append(gradient);+ println(`folded tag: ${getComputedStyle(gradient).color}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/shared-link-style-sheet-compiles-once.html b/Tests/LibWeb/Text/input/css/shared-link-style-sheet-compiles-once.htmlnew file mode 100644index 00000000000..6faeddc2d31--- /dev/null+++ b/Tests/LibWeb/Text/input/css/shared-link-style-sheet-compiles-once.html@@ -0,0 +1,46 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // Components commonly style each shadow tree with a link to the same sheet. Every link loads a sheet of its own,+ // whose rules the parse cache answers with the same contents; the document compiles those rules once.+ function makeRoot() {+ const host = document.createElement("div");+ document.body.append(host);+ const root = host.attachShadow({ mode: "open" });+ const target = document.createElement("span");+ target.className = "target";+ root.append(target);+ return root;+ }+ function addLink(root) {+ const link = document.createElement("link");+ link.rel = "stylesheet";+ link.href = "resources/shared-link-component.css";+ const loaded = new Promise(resolve => (link.onload = resolve));+ root.append(link);+ return { link, loaded };+ }+ function color(root) {+ return getComputedStyle(root.querySelector(".target")).color;+ }++ promiseTest(async () => {+ // The first link has the document compile the sheet.+ const firstRoot = makeRoot();+ await addLink(firstRoot).loaded;+ println(`first: ${color(firstRoot)}`);++ const before = internals.styleEngineCounters().styleRulesCompiled;+ const roots = [makeRoot(), makeRoot(), makeRoot()];+ const links = roots.map(addLink);+ await Promise.all(links.map(({ loaded }) => loaded));+ println(`others: ${roots.map(color).join(", ")}`);+ println(`rules compiled for the other links: ${internals.styleEngineCounters().styleRulesCompiled - before}`);++ // Each link's sheet keeps conditions of its own.+ links[0].link.media = "not all";+ println(`after the first other stops matching: ${roots.map(color).join(", ")}`);+ links[1].link.remove();+ println(`after removing the second other: ${color(roots[0])}, ${color(roots[2])}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/sheet-changes-rematch-what-they-changed.html b/Tests/LibWeb/Text/input/css/sheet-changes-rematch-what-they-changed.htmlnew file mode 100644index 00000000000..48cdd5730f2--- /dev/null+++ b/Tests/LibWeb/Text/input/css/sheet-changes-rematch-what-they-changed.html@@ -0,0 +1,110 @@+<!doctype html>+<script src="../include.js"></script>+<style id="one" media="not all">+ .a { color: rgb(255, 0, 0); }+ .only-one { color: rgb(0, 0, 255); }+</style>+<style id="two" media="not all">+ .a { color: rgb(0, 128, 0); }+ .a .below { color: rgb(0, 128, 0); }+ .a::before { color: rgb(0, 128, 0); }+ .a + .next { color: rgb(0, 128, 0); }+</style>+<style>+ .base { color: rgb(1, 1, 1); background-color: rgb(1, 1, 1); }+ @layer low, high;+</style>+<div id="root"></div>+<script>+ // Each change here moves what elements match, in ways that must reach them, while they keep what they matched of+ // the rules that did not change: a sheet leaving, one arriving, both at once, a layer order moving, rules inserted+ // and deleted, enough rules dying that the index is built again, and elements in a shadow tree and with its host.+ test(() => {+ const root = document.getElementById("root");+ root.innerHTML = `+ <div class="base a" id="main"><p class="below"></p></div>+ <div class="base next"></div>+ <div class="base a"><p class="below"></p></div>+ <div class="base a only-one"></div>+ <div class="base layered"></div>+ <div class="base inserted"></div>+ <div class="base other"></div>`;+ const host = document.createElement("div");+ host.className = "base a";+ root.append(host);+ const shadow = host.attachShadow({ mode: "open" });+ shadow.innerHTML = "<style id=inner media='not all'>.inside { color: rgb(0, 128, 0); }</style><slot></slot><div class=inside></div><div part=p></div>";+ const slotted = document.createElement("div");+ slotted.className = "a";+ host.append(slotted);++ const report = title => {+ println(title);+ for (const element of [...root.querySelectorAll("*"), ...shadow.querySelectorAll("div")]) {+ const style = getComputedStyle(element);+ println(` ${element.localName} ${element.className} ${style.color} ${style.backgroundColor} ${getComputedStyle(element, "::before").color}`);+ }+ };+ const one = document.getElementById("one");+ const two = document.getElementById("two");+ report("start");+ one.media = "all";+ report("first arrived");+ two.media = "all";+ report("second arrived, over the first");+ one.media = "not all";+ report("first left, under the second");+ one.media = "all";+ two.media = "not all";+ report("swapped");+ one.media = "not all";+ report("both left");+ one.media = "all";+ two.media = "all";+ one.media = "not all";+ report("all at once");+ two.media = "not all";++ const layers = document.createElement("style");+ layers.textContent = "@layer low { .layered { color: rgb(255, 0, 0); } } @layer high { .layered { color: rgb(0, 128, 0); } }";+ document.head.append(layers);+ report("layers");+ const order = document.createElement("style");+ order.textContent = "@layer high, low;";+ document.head.prepend(order);+ report("layer order moved");+ order.remove();+ report("layer order back");+ layers.remove();+ report("layers left");++ const sheet = new CSSStyleSheet();+ document.adoptedStyleSheets = [sheet];+ sheet.insertRule(".inserted { color: rgb(0, 128, 0); }");+ report("inserted");+ sheet.insertRule(".inserted { color: rgb(255, 0, 0); }");+ report("inserted over");+ sheet.deleteRule(0);+ report("deleted the one over");+ sheet.deleteRule(0);+ report("deleted");++ shadow.getElementById("inner").media = "all";+ report("shadow sheet arrived");+ shadow.getElementById("inner").media = "not all";+ report("shadow sheet left");++ const many = document.createElement("style");+ let text = "";+ for (let i = 0; i < 700; ++i)+ text += `.rule-${i} { color: rgb(255, 0, 0); }\n`;+ many.textContent = text + ".other { color: rgb(0, 128, 0); }";+ document.head.append(many);+ report("many arrived");+ many.remove();+ two.media = "all";+ report("many left, with one arriving");+ two.media = "not all";+ report("end");+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/sheet-declarations-intern-once-per-process.html b/Tests/LibWeb/Text/input/css/sheet-declarations-intern-once-per-process.htmlnew file mode 100644index 00000000000..da73f58feb8--- /dev/null+++ b/Tests/LibWeb/Text/input/css/sheet-declarations-intern-once-per-process.html@@ -0,0 +1,29 @@+<!DOCTYPE html>+<script src="../include.js"></script>+<script>+ // Two frames load the same sheet, as the frames of one site do: the parse cache gives both the same parsed+ // contents, whose declaration blocks the process interns once.+ // NB: The process keeps what it interned, so the blocks of each run of this test are its own.+ const run = crypto.randomUUID();+ const rules = Array.from({ length: 50 }, (_, index) => `.c${index} { margin-top: ${index}px; color: rgb(${index}, 0, 0); --run: ${run}; }`);+ const frame = `<style>${rules.join("\n")}</style><p class=c7>x</p>`;+ asyncTest(async done => {+ const load = () =>+ new Promise(resolve => {+ const iframe = document.createElement("iframe");+ iframe.onload = () => resolve(iframe);+ iframe.srcdoc = frame;+ document.body.appendChild(iframe);+ });+ const first = await load();+ const second = await load();+ for (const [name, iframe] of [["first", first], ["second", second]]) {+ const p = iframe.contentDocument.querySelector("p");+ const counters = iframe.contentWindow.internals.styleEngineCounters();+ println(`${name} frame margin-top: ${iframe.contentWindow.getComputedStyle(p).marginTop}`);+ println(`${name} frame blocks interned: ${counters.sheetDeclarationsInterned}`);+ println(`${name} frame blocks shared: ${counters.sheetDeclarationsShared}`);+ }+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/style-attribute-shared-text-edit.html b/Tests/LibWeb/Text/input/css/style-attribute-shared-text-edit.htmlnew file mode 100644index 00000000000..c3838d9abbe--- /dev/null+++ b/Tests/LibWeb/Text/input/css/style-attribute-shared-text-edit.html@@ -0,0 +1,20 @@+<!DOCTYPE html>+<div id="a" style="color: red; margin-left: 3.5px"></div>+<div id="b" style="color: red; margin-left: 3.5px"></div>+<div id="c" style="color: red; margin-left: 3.5px"></div>+<script src="../include.js"></script>+<script>+ test(() => {+ a.style.setProperty("color", "blue");+ for (const element of [a, b, c]) {+ println(`${element.id}: ${getComputedStyle(element).color} ${getComputedStyle(element).marginLeft}`);+ println(`${element.id} cssText: ${element.style.cssText}`);+ println(`${element.id} attribute: ${element.getAttribute("style")}`);+ }+ b.setAttribute("style", "color: green; margin-left: 3.5px");+ c.setAttribute("style", "color: green; margin-left: 3.5px");+ b.style.removeProperty("margin-left");+ println(`b: ${getComputedStyle(b).color} ${getComputedStyle(b).marginLeft} ${b.style.cssText}`);+ println(`c: ${getComputedStyle(c).color} ${getComputedStyle(c).marginLeft} ${c.style.cssText}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/style-engine/attr-in-custom-property-engine-computed.html b/Tests/LibWeb/Text/input/css/style-engine/attr-in-custom-property.htmlsimilarity index 63%rename from Tests/LibWeb/Text/input/css/style-engine/attr-in-custom-property-engine-computed.htmlrename to Tests/LibWeb/Text/input/css/style-engine/attr-in-custom-property.htmlindex 67cf16f3472..76738a2a0ea 100644--- a/Tests/LibWeb/Text/input/css/style-engine/attr-in-custom-property-engine-computed.html+++ b/Tests/LibWeb/Text/input/css/style-engine/attr-in-custom-property.html@@ -14,34 +14,22 @@// value, and an attribute change reaches the element the engine computes.test(() => {internals.updateStyle();- let before = internals.getStyleInvalidationCounters();document.getElementById("parent").classList.add("attribute");internals.updateStyle();- let after = internals.getStyleInvalidationCounters();- println(`C++ recomputations: ${after.elementStyleRecomputations - before.elementStyleRecomputations}`);println(`colors: ${getComputedStyle(first).color} ${getComputedStyle(second).color} ${getComputedStyle(child).color}`);- before = internals.getStyleInvalidationCounters();first.dataset.color = "red";internals.updateStyle();- after = internals.getStyleInvalidationCounters();- println(`attribute change C++ recomputations: ${after.elementStyleRecomputations - before.elementStyleRecomputations}`);println(`colors: ${getComputedStyle(first).color} ${getComputedStyle(second).color} ${getComputedStyle(child).color}`);// A declaration whose attr() takes the fallback the parent holds resolves to the parent's- // environment, and still reads the attribute; the engine computes the element both times.+ // environment, and still reads the attribute.const fallback = document.createElement("div");fallback.id = "fallback";- before = internals.getStyleInvalidationCounters();document.getElementById("fallback-parent").appendChild(fallback);internals.updateStyle();- after = internals.getStyleInvalidationCounters();- println(`fallback C++ recomputations: ${after.elementStyleRecomputations - before.elementStyleRecomputations}`);println(`fallback width: ${getComputedStyle(fallback).width}`);- before = internals.getStyleInvalidationCounters();fallback.dataset.length = "5px";internals.updateStyle();- after = internals.getStyleInvalidationCounters();- println(`fallback attribute change C++ recomputations: ${after.elementStyleRecomputations - before.elementStyleRecomputations}`);println(`attribute width: ${getComputedStyle(fallback).width}`);});</script>diff --git a/Tests/LibWeb/Text/input/css/style-engine/attr-substitution-backing-element-engine-computed.html b/Tests/LibWeb/Text/input/css/style-engine/attr-substitution-backing-element.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/attr-substitution-backing-element-engine-computed.htmlrename to Tests/LibWeb/Text/input/css/style-engine/attr-substitution-backing-element.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/attr-substitution-pseudo-engine-computed.html b/Tests/LibWeb/Text/input/css/style-engine/attr-substitution-pseudo.htmlsimilarity index 63%rename from Tests/LibWeb/Text/input/css/style-engine/attr-substitution-pseudo-engine-computed.htmlrename to Tests/LibWeb/Text/input/css/style-engine/attr-substitution-pseudo.htmlindex 9f984da5dd4..acc037560cc 100644--- a/Tests/LibWeb/Text/input/css/style-engine/attr-substitution-pseudo-engine-computed.html+++ b/Tests/LibWeb/Text/input/css/style-engine/attr-substitution-pseudo.html@@ -8,21 +8,15 @@<script>// A pseudo-element's attr() substitutes its originating element's attributes: two// pseudo-elements alike in everything else take their own values, and an attribute change- // reaches the pseudo-element the engine computes.+ // reaches the pseudo-element.test(() => {const color = element => getComputedStyle(element, "::before").color;internals.updateStyle();- let before = internals.getStyleInvalidationCounters();document.getElementById("parent").classList.add("attribute");internals.updateStyle();- let after = internals.getStyleInvalidationCounters();- println(`computation stays in the engine: ${after.elementStyleRecomputations - before.elementStyleRecomputations === 0}`);println(`colors: ${color(first)} ${color(second)}`);- before = internals.getStyleInvalidationCounters();first.dataset.color = "red";internals.updateStyle();- after = internals.getStyleInvalidationCounters();- println(`attribute change stays in the engine: ${after.elementStyleRecomputations - before.elementStyleRecomputations === 0}`);println(`colors: ${color(first)} ${color(second)}`);});</script>diff --git a/Tests/LibWeb/Text/input/css/style-engine/attr-substitution-shorthand.html b/Tests/LibWeb/Text/input/css/style-engine/attr-substitution-shorthand.htmlnew file mode 100644index 00000000000..8358abdfb4e--- /dev/null+++ b/Tests/LibWeb/Text/input/css/style-engine/attr-substitution-shorthand.html@@ -0,0 +1,28 @@+<!DOCTYPE html>+<script src="../../include.js"></script>+<style>+ .item { margin: attr(data-margin type(<length>)); }+ .colored { background: attr(data-color type(<color>), rgb(0, 128, 0)); }+</style>+<div class="item" id="item" data-margin="5px"></div>+<div class="colored" id="colored" data-color="qqffuutt"></div>+<script>+ // A shorthand written with attr() leaves its longhands pending the shorthand's substitution,+ // which reads the element's attributes, and follows an attribute change.+ test(() => {+ internals.updateStyle();+ for (const element of [item, colored]) {+ const clone = element.cloneNode();+ clone.removeAttribute("id");+ document.body.append(clone);+ }+ internals.updateStyle();+ println(`margin: ${getComputedStyle(item).marginLeft}`);+ println(`invalid color falls back: ${getComputedStyle(colored).backgroundColor}`);+ item.dataset.margin = "7px";+ colored.dataset.color = "rgb(0, 0, 255)";+ internals.updateStyle();+ println(`margin: ${getComputedStyle(item).marginLeft}`);+ println(`color: ${getComputedStyle(colored).backgroundColor}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/style-engine/attr-substitution-engine-computed.html b/Tests/LibWeb/Text/input/css/style-engine/attr-substitution.htmlsimilarity index 63%rename from Tests/LibWeb/Text/input/css/style-engine/attr-substitution-engine-computed.htmlrename to Tests/LibWeb/Text/input/css/style-engine/attr-substitution.htmlindex e62bd93b9c9..b7798178af4 100644--- a/Tests/LibWeb/Text/input/css/style-engine/attr-substitution-engine-computed.html+++ b/Tests/LibWeb/Text/input/css/style-engine/attr-substitution.html@@ -7,20 +7,14 @@<div id="parent"><span class="item" id="first" data-color="green"></span><span class="item" id="second" data-color="purple"></span></div><script>// An attr() substitutes the element's own attributes: two elements alike in everything else- // take their own values, and an attribute change reaches the element the engine computes.+ // take their own values, and an attribute change reaches the element.test(() => {internals.updateStyle();- let before = internals.getStyleInvalidationCounters();document.getElementById("parent").classList.add("attribute");internals.updateStyle();- let after = internals.getStyleInvalidationCounters();- println(`engine computed the readers: ${after.engineComputedStyleRecords - before.engineComputedStyleRecords >= 2}`);println(`colors: ${getComputedStyle(first).color} ${getComputedStyle(second).color}`);- before = internals.getStyleInvalidationCounters();first.dataset.color = "red";internals.updateStyle();- after = internals.getStyleInvalidationCounters();- println(`attribute change stays in the engine: ${after.elementStyleRecomputations - before.elementStyleRecomputations === 0}`);println(`colors: ${getComputedStyle(first).color} ${getComputedStyle(second).color}`);});</script>diff --git a/Tests/LibWeb/Text/input/css/style-engine/attribute-writes-before-a-selector-reads-them.html b/Tests/LibWeb/Text/input/css/style-engine/attribute-writes-before-a-selector-reads-them.htmlnew file mode 100644index 00000000000..440a1bcf9cb--- /dev/null+++ b/Tests/LibWeb/Text/input/css/style-engine/attribute-writes-before-a-selector-reads-them.html@@ -0,0 +1,35 @@+<!DOCTYPE html>+<script src="../../include.js"></script>+<div id="changed" data-x="a"></div>+<div id="added"></div>+<div id="removed" data-x="a"></div>+<div id="set-then-removed"></div>+<script>+ // Attributes written while no selector reads them are published once one comes to.+ test(() => {+ const elements = ["changed", "added", "removed", "set-then-removed"].map(id => document.getElementById(id));+ const report = label => {+ for (const element of elements)+ println(`${label}: ${element.id}: ${getComputedStyle(element).color}`);+ };+ report("no rules");++ elements[0].setAttribute("data-x", "b");+ elements[1].setAttribute("data-x", "b");+ elements[2].removeAttribute("data-x");+ elements[3].setAttribute("data-x", "b");+ elements[3].removeAttribute("data-x");+ report("written, no rules");++ const style = document.createElement("style");+ style.textContent = `[data-x="a"] { color: rgb(255, 0, 0); } [data-x="b"] { color: rgb(0, 128, 0); } [data-x] { background-color: rgb(1, 2, 3); }`;+ document.head.appendChild(style);+ report("read");+ for (const element of elements)+ println(`read: ${element.id}: ${getComputedStyle(element).backgroundColor}`);++ elements[0].setAttribute("data-x", "a");+ elements[3].setAttribute("data-x", "a");+ report("written, read");+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/style-engine/cold-pass-matching.html b/Tests/LibWeb/Text/input/css/style-engine/cold-pass-matching.htmlnew file mode 100644index 00000000000..286587c267d--- /dev/null+++ b/Tests/LibWeb/Text/input/css/style-engine/cold-pass-matching.html@@ -0,0 +1,36 @@+<!DOCTYPE html>+<style>+ .theme .item { color: red; }+ .theme > .item { color: green; }+ #main .list li:nth-child(2n) { background: blue; }+ ul.list > li + li { margin-top: 1px; }+ li ~ li.last { font-weight: bold; }+ [data-kind="card"] span { padding: 2px; }+ :is(h1, h2) .title { text-decoration: underline; }+ div:not(.theme) > p { opacity: 0.5; }+ section a[href^="https"] { color: purple; }+ .unused-ancestor .item { color: orange; }+</style>+<div id="main" class="theme">+ <ul class="list">+ <li class="item">one</li>+ <li class="item">two</li>+ <li class="item last">three</li>+ </ul>+ <div data-kind="card"><span>card</span><p>paragraph</p></div>+ <h2><span class="title">title</span></h2>+ <section><a href="https://example.com">link</a><a href="http://example.com">plain</a></section>+ <p style="color: teal">inline</p>+</div>+<script src="../../include.js"></script>+<script>+ test(() => {+ internals.updateStyle();+ const report = internals.styleColdPass();+ println(`styled elements: ${report.elements > 15}`);+ println(`ancestor filter rejected a candidate: ${report.bloomRejections > 0}`);+ println(`computed every styled element: ${report.computedElements == report.elements}`);+ println(`computed some directly: ${report.directlyComputedElements > 0}`);+ println(`differences: ${report.differences}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/style-engine/declaration-edit-reuses-matching.html b/Tests/LibWeb/Text/input/css/style-engine/declaration-edit-reuses-matching.htmlnew file mode 100644index 00000000000..47b11ed55db--- /dev/null+++ b/Tests/LibWeb/Text/input/css/style-engine/declaration-edit-reuses-matching.html@@ -0,0 +1,24 @@+<!DOCTYPE html>+<script src="../../include.js"></script>+<style>+ .target { color: green }+ .target { color: red }+</style>+<div class="target" id="target"></div>+<script>+ test(() => {+ const sheet = document.styleSheets[0];+ // The first CSSOM edit recompiles shared contents into a private stylesheet. Insert and remove+ // a dummy rule first, so the declaration edit below is an incremental edit.+ sheet.insertRule(":not(*) {}", 0);+ sheet.deleteRule(0);++ const target = document.getElementById("target");+ internals.updateStyle();++ document.styleSheets[0].cssRules[0].style.setProperty("color", "blue", "important");+ internals.updateStyle();++ println(`color: ${getComputedStyle(target).color}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/style-engine/incremental-sheet-edits.html b/Tests/LibWeb/Text/input/css/style-engine/incremental-sheet-edits.htmlnew file mode 100644index 00000000000..26f31326f4b--- /dev/null+++ b/Tests/LibWeb/Text/input/css/style-engine/incremental-sheet-edits.html@@ -0,0 +1,80 @@+<!DOCTYPE html>+<script src="../../include.js"></script>+<style id="sheet">+ #target { --a: 1 }+ #target { --b: 1 }+ #target { --c: 1 }+ #target { --d: 1 }+</style>+<div id="target" tabindex="0"></div>+<script>+ const sheet = document.getElementById("sheet").sheet;+ const target = document.getElementById("target");++ function edit(mutate) {+ mutate();+ // Reading a value flushes, so the whole edit is styled and not just the call.+ getComputedStyle(target).getPropertyValue("--a");+ }++ function color() {+ return getComputedStyle(target).color;+ }++ test(() => {+ document.body.offsetWidth;++ // One rule arriving lands where it was asked to. The rules around it keep their order.+ edit(() => sheet.insertRule("#target:focus { color: rgb(1, 1, 1) }", 0));+ edit(() => sheet.insertRule("#target:focus { color: rgb(2, 2, 2) }", 2));+ edit(() => sheet.insertRule("#target:focus { color: rgb(3, 3, 3) }", sheet.cssRules.length));++ // Each landed where it was asked to, so the last one wins on equal specificity.+ target.focus();+ println(`after three inserts: ${color()}`);++ // Deleting the winner lets the rule behind it take over.+ edit(() => sheet.deleteRule(sheet.cssRules.length - 1));+ println(`after deleting the winner: ${color()}`);++ // Retargeting a rule is that one rule changing. Its position is untouched, so it still+ // cascades where it did.+ edit(() => { sheet.cssRules[2].selectorText = "#target:focus, .unrelated"; });+ println(`after retargeting: ${color()}`);++ // A group arriving brings its own rules.+ edit(() => sheet.insertRule("@media all { #target:focus { color: rgb(4, 4, 4) } #target:focus { color: rgb(5, 5, 5) } }", sheet.cssRules.length));+ println(`after the group: ${color()}`);++ // Deleting the group takes its rules with it.+ edit(() => sheet.deleteRule(sheet.cssRules.length - 1));+ println(`after deleting the group: ${color()}`);++ // Every rule can be edited in turn.+ const count = sheet.cssRules.length;+ edit(() => {+ for (let index = 0; index < count; ++index)+ sheet.cssRules[index].selectorText = `#target:focus, .all-${index}`;+ });+ println(`after retargeting all: ${color()}`);++ // Every rule can be deleted in turn.+ edit(() => {+ while (sheet.cssRules.length > 0)+ sheet.deleteRule(sheet.cssRules.length - 1);+ });+ println(`after deleting all: ${color()}`);++ // `replace()` swaps the whole rule list.+ const constructed = new CSSStyleSheet();+ document.adoptedStyleSheets = [constructed];+ edit(() => {+ constructed.replaceSync("#target:focus { color: rgb(6, 6, 6) } .x { color: red } .y { color: red }");+ });+ println(`after replaceSync: ${color()}`);+ edit(() => {+ constructed.replaceSync("#target:focus { color: rgb(7, 7, 7) }");+ });+ println(`after the second replaceSync: ${color()}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/style-engine/losing-sheet-uses-retained-winners.html b/Tests/LibWeb/Text/input/css/style-engine/losing-sheet-winners.htmlsimilarity index 66%rename from Tests/LibWeb/Text/input/css/style-engine/losing-sheet-uses-retained-winners.htmlrename to Tests/LibWeb/Text/input/css/style-engine/losing-sheet-winners.htmlindex 2639c4c7e76..1dd278e0f11 100644--- a/Tests/LibWeb/Text/input/css/style-engine/losing-sheet-uses-retained-winners.html+++ b/Tests/LibWeb/Text/input/css/style-engine/losing-sheet-winners.html@@ -15,8 +15,6 @@root.lastElementChild.id = "sentinel";internals.updateStyle();- const before = internals.styleEngineCounters();- println(`winner groups cover the document: ${before.cascadeNodeHandlesPublished >= 100}`);const sheet = document.createElement("style");sheet.textContent = `.item { color: red }@@ -24,10 +22,7 @@`;document.head.appendChild(sheet);internals.updateStyle();- const after = internals.styleEngineCounters();- println(`losing candidates rejected: ${after.programCandidatesRejectedByCascade - before.programCandidatesRejectedByCascade}`);- println(`only local nodes invalidated: ${after.invalidatedStyleNodes - before.invalidatedStyleNodes < 10}`);println(`ordinary item: ${getComputedStyle(root.firstElementChild).color}`);println(`sentinel: ${getComputedStyle(root.lastElementChild).outlineColor}`);});diff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-attribute-any-namespace.html b/Tests/LibWeb/Text/input/css/style-engine/matching-attribute-any-namespace.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-attribute-any-namespace.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-attribute-any-namespace.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-attribute-case.html b/Tests/LibWeb/Text/input/css/style-engine/matching-attribute-case.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-attribute-case.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-attribute-case.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-attribute-name-case.html b/Tests/LibWeb/Text/input/css/style-engine/matching-attribute-name-case.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-attribute-name-case.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-attribute-name-case.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-attribute-namespaces.html b/Tests/LibWeb/Text/input/css/style-engine/matching-attribute-namespaces.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-attribute-namespaces.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-attribute-namespaces.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-combinator-prefilter.html b/Tests/LibWeb/Text/input/css/style-engine/matching-combinator-prefilter.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-combinator-prefilter.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-combinator-prefilter.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-computed-states.html b/Tests/LibWeb/Text/input/css/style-engine/matching-computed-states.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-computed-states.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-computed-states.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-conditions.html b/Tests/LibWeb/Text/input/css/style-engine/matching-conditions.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-conditions.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-conditions.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-default-namespace.html b/Tests/LibWeb/Text/input/css/style-engine/matching-default-namespace.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-default-namespace.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-default-namespace.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-featureless-host.html b/Tests/LibWeb/Text/input/css/style-engine/matching-featureless-host.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-featureless-host.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-featureless-host.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-host-argument-descendant.html b/Tests/LibWeb/Text/input/css/style-engine/matching-host-argument-descendant.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-host-argument-descendant.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-host-argument-descendant.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-host-descendant.html b/Tests/LibWeb/Text/input/css/style-engine/matching-host-descendant.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-host-descendant.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-host-descendant.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-imports.html b/Tests/LibWeb/Text/input/css/style-engine/matching-imports.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-imports.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-imports.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-layer-order.html b/Tests/LibWeb/Text/input/css/style-engine/matching-layer-order.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-layer-order.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-layer-order.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-namespaces.html b/Tests/LibWeb/Text/input/css/style-engine/matching-namespaces.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-namespaces.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-namespaces.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-nested-scope-retarget.html b/Tests/LibWeb/Text/input/css/style-engine/matching-nested-scope-retarget.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-nested-scope-retarget.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-nested-scope-retarget.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-nested-scope.html b/Tests/LibWeb/Text/input/css/style-engine/matching-nested-scope.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-nested-scope.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-nested-scope.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-part-compound.html b/Tests/LibWeb/Text/input/css/style-engine/matching-part-compound.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-part-compound.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-part-compound.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-part-forwarded.html b/Tests/LibWeb/Text/input/css/style-engine/matching-part-forwarded.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-part-forwarded.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-part-forwarded.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-part-published-late.html b/Tests/LibWeb/Text/input/css/style-engine/matching-part-published-late.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-part-published-late.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-part-published-late.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-part-scope.html b/Tests/LibWeb/Text/input/css/style-engine/matching-part-scope.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-part-scope.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-part-scope.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-part.html b/Tests/LibWeb/Text/input/css/style-engine/matching-part.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-part.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-part.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-pseudo-elements.html b/Tests/LibWeb/Text/input/css/style-engine/matching-pseudo-elements.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-pseudo-elements.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-pseudo-elements.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-scope-implicit.html b/Tests/LibWeb/Text/input/css/style-engine/matching-scope-implicit.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-scope-implicit.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-scope-implicit.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-scope-limit-instance.html b/Tests/LibWeb/Text/input/css/style-engine/matching-scope-limit-instance.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-scope-limit-instance.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-scope-limit-instance.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-scope-root.html b/Tests/LibWeb/Text/input/css/style-engine/matching-scope-root.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-scope-root.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-scope-root.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-selector-shapes.html b/Tests/LibWeb/Text/input/css/style-engine/matching-selector-shapes.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-selector-shapes.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-selector-shapes.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-unsatisfiable.html b/Tests/LibWeb/Text/input/css/style-engine/matching-unsatisfiable.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-unsatisfiable.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-unsatisfiable.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-use.html b/Tests/LibWeb/Text/input/css/style-engine/matching-use.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-use.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-use.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement-xml-document.xhtml b/Tests/LibWeb/Text/input/css/style-engine/matching-xml-document.xhtmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement-xml-document.xhtmlrename to Tests/LibWeb/Text/input/css/style-engine/matching-xml-document.xhtmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/match-agreement.html b/Tests/LibWeb/Text/input/css/style-engine/matching.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/match-agreement.htmlrename to Tests/LibWeb/Text/input/css/style-engine/matching.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/prefix-positional-truth-across-feature-and-tree-changes.html b/Tests/LibWeb/Text/input/css/style-engine/positional-selectors-across-feature-and-tree-changes.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/prefix-positional-truth-across-feature-and-tree-changes.htmlrename to Tests/LibWeb/Text/input/css/style-engine/positional-selectors-across-feature-and-tree-changes.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/selector-answer-patch-activation.html b/Tests/LibWeb/Text/input/css/style-engine/rule-edit-activation.htmlsimilarity index 57%rename from Tests/LibWeb/Text/input/css/style-engine/selector-answer-patch-activation.htmlrename to Tests/LibWeb/Text/input/css/style-engine/rule-edit-activation.htmlindex 303feb88ef9..14d3576e72c 100644--- a/Tests/LibWeb/Text/input/css/style-engine/selector-answer-patch-activation.html+++ b/Tests/LibWeb/Text/input/css/style-engine/rule-edit-activation.html@@ -12,7 +12,7 @@test(() => {const sheet = document.getElementById("sheet").sheet;// The first CSSOM edit recompiles shared contents into a private stylesheet. Insert and remove- // a dummy rule before measuring, so the counters cover only subsequent incremental edits.+ // a dummy rule first, so the edits below are incremental.sheet.insertRule(":not(*) {}", 0);sheet.deleteRule(0);@@ -20,20 +20,11 @@const group = document.getElementById("sheet").sheet.cssRules[1];internals.updateStyle();- const before = internals.styleEngineCounters();group.media.mediaText = "all";internals.updateStyle();println(`active color: ${getComputedStyle(target).color}`);group.media.mediaText = "(width < 1px)";internals.updateStyle();- const after = internals.styleEngineCounters();-- const answerPatches = after.retainedMatchAnswerPatches - before.retainedMatchAnswerPatches- + after.retainedMatchAnswerDeltaPatches - before.retainedMatchAnswerDeltaPatches;- println(`answer patches: ${answerPatches}`);- println(`answer reuses: ${after.retainedMatchAnswerReuses - before.retainedMatchAnswerReuses}`);- println(`cold node evaluations: ${after.coldNodesEvaluated - before.coldNodesEvaluated}`);- println(`invalidated nodes: ${after.invalidatedStyleNodes - before.invalidatedStyleNodes}`);println(`inactive color: ${getComputedStyle(target).color}`);});</script>diff --git a/Tests/LibWeb/Text/input/css/style-engine/selector-answer-patch-program-changes.html b/Tests/LibWeb/Text/input/css/style-engine/rule-edit-program-changes.htmlsimilarity index 69%rename from Tests/LibWeb/Text/input/css/style-engine/selector-answer-patch-program-changes.htmlrename to Tests/LibWeb/Text/input/css/style-engine/rule-edit-program-changes.htmlindex 1d4df0f7907..894caaa366e 100644--- a/Tests/LibWeb/Text/input/css/style-engine/selector-answer-patch-program-changes.html+++ b/Tests/LibWeb/Text/input/css/style-engine/rule-edit-program-changes.html@@ -13,12 +13,11 @@const target = document.getElementById("target");const sheet = document.getElementById("sheet").sheet;// The first CSSOM edit recompiles shared contents into a private stylesheet. Insert and remove- // a dummy rule before measuring, so the counters cover only subsequent incremental edits.+ // a dummy rule first, so the edits below are incremental.sheet.insertRule(":not(*) {}", 0);sheet.deleteRule(0);internals.updateStyle();- const before = internals.styleEngineCounters();sheet.cssRules[0].selectorText = ".nobody";internals.updateStyle();println(`retargeted color: ${getComputedStyle(target).color}`);@@ -30,14 +29,6 @@println(`inserted rule color: ${getComputedStyle(target).color}`);sheet.deleteRule(sheet.cssRules.length - 1);internals.updateStyle();- const after = internals.styleEngineCounters();-- const answerPatches = after.retainedMatchAnswerPatches - before.retainedMatchAnswerPatches- + after.retainedMatchAnswerDeltaPatches - before.retainedMatchAnswerDeltaPatches;- println(`answer patches: ${answerPatches}`);- println(`answer reuses: ${after.retainedMatchAnswerReuses - before.retainedMatchAnswerReuses}`);- println(`cold node evaluations: ${after.coldNodesEvaluated - before.coldNodesEvaluated}`);- println(`invalidated nodes: ${after.invalidatedStyleNodes - before.invalidatedStyleNodes}`);println(`deleted rule color: ${getComputedStyle(target).color}`);const selectorListTarget = document.getElementById("selector-list-target");diff --git a/Tests/LibWeb/Text/input/css/style-engine/patched-answer-ranks-follow-dispatch.html b/Tests/LibWeb/Text/input/css/style-engine/rule-edit-ranks-follow-dispatch.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/patched-answer-ranks-follow-dispatch.htmlrename to Tests/LibWeb/Text/input/css/style-engine/rule-edit-ranks-follow-dispatch.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/selector-answer-patch-sheet-activation.html b/Tests/LibWeb/Text/input/css/style-engine/rule-edit-sheet-activation.htmlsimilarity index 54%rename from Tests/LibWeb/Text/input/css/style-engine/selector-answer-patch-sheet-activation.htmlrename to Tests/LibWeb/Text/input/css/style-engine/rule-edit-sheet-activation.htmlindex ac325893319..51ffce27ced 100644--- a/Tests/LibWeb/Text/input/css/style-engine/selector-answer-patch-sheet-activation.html+++ b/Tests/LibWeb/Text/input/css/style-engine/rule-edit-sheet-activation.html@@ -15,20 +15,11 @@sheet.disabled = true;internals.updateStyle();- const before = internals.styleEngineCounters();sheet.disabled = false;internals.updateStyle();println(`active color: ${getComputedStyle(target).color}`);sheet.disabled = true;internals.updateStyle();- const after = internals.styleEngineCounters();-- const answerPatches = after.retainedMatchAnswerPatches - before.retainedMatchAnswerPatches- + after.retainedMatchAnswerDeltaPatches - before.retainedMatchAnswerDeltaPatches;- println(`answer patches: ${answerPatches}`);- println(`answer reuses: ${after.retainedMatchAnswerReuses - before.retainedMatchAnswerReuses}`);- println(`cold node evaluations: ${after.coldNodesEvaluated - before.coldNodesEvaluated}`);- println(`invalidated nodes: ${after.invalidatedStyleNodes - before.invalidatedStyleNodes}`);println(`inactive color: ${getComputedStyle(target).color}`);});</script>diff --git a/Tests/LibWeb/Text/input/css/style-engine/selector-answer-patch-sheet-attachment.html b/Tests/LibWeb/Text/input/css/style-engine/rule-edit-sheet-attachment.htmlsimilarity index 50%rename from Tests/LibWeb/Text/input/css/style-engine/selector-answer-patch-sheet-attachment.htmlrename to Tests/LibWeb/Text/input/css/style-engine/rule-edit-sheet-attachment.htmlindex 059a1a5b55c..5c30c728fa5 100644--- a/Tests/LibWeb/Text/input/css/style-engine/selector-answer-patch-sheet-attachment.html+++ b/Tests/LibWeb/Text/input/css/style-engine/rule-edit-sheet-attachment.html@@ -11,20 +11,11 @@sheet.replaceSync("#target { color: red }");internals.updateStyle();- const before = internals.styleEngineCounters();document.adoptedStyleSheets = [sheet];internals.updateStyle();println(`attached color: ${getComputedStyle(target).color}`);document.adoptedStyleSheets = [];internals.updateStyle();- const after = internals.styleEngineCounters();-- const answerPatches = after.retainedMatchAnswerPatches - before.retainedMatchAnswerPatches- + after.retainedMatchAnswerDeltaPatches - before.retainedMatchAnswerDeltaPatches;- println(`answer patches: ${answerPatches}`);- println(`answer reuses: ${after.retainedMatchAnswerReuses - before.retainedMatchAnswerReuses}`);- println(`cold node evaluations: ${after.coldNodesEvaluated - before.coldNodesEvaluated}`);- println(`invalidated nodes: ${after.invalidatedStyleNodes - before.invalidatedStyleNodes}`);println(`detached color: ${getComputedStyle(target).color}`);});</script>diff --git a/Tests/LibWeb/Text/input/css/style-engine/selector-answer-patch-stops-at-unchanged-signature.html b/Tests/LibWeb/Text/input/css/style-engine/rule-edit-stops-at-unchanged-signature.htmlsimilarity index 52%rename from Tests/LibWeb/Text/input/css/style-engine/selector-answer-patch-stops-at-unchanged-signature.htmlrename to Tests/LibWeb/Text/input/css/style-engine/rule-edit-stops-at-unchanged-signature.htmlindex cb8b99f73c0..823ee84d01e 100644--- a/Tests/LibWeb/Text/input/css/style-engine/selector-answer-patch-stops-at-unchanged-signature.html+++ b/Tests/LibWeb/Text/input/css/style-engine/rule-edit-stops-at-unchanged-signature.html@@ -10,17 +10,11 @@const witness = document.getElementById("witness");internals.updateStyle();- const before = internals.styleEngineCounters();witness.classList.add("witness");internals.updateStyle();witness.classList.remove("witness");internals.updateStyle();- const after = internals.styleEngineCounters();- println(`delta patches: ${after.retainedMatchAnswerDeltaPatches - before.retainedMatchAnswerDeltaPatches}`);- println(`patch upqueries: ${after.retainedMatchAnswerPatches - before.retainedMatchAnswerPatches}`);- println(`unchanged stops: ${after.retainedMatchAnswerPatchStops - before.retainedMatchAnswerPatchStops}`);- println(`invalidated nodes: ${after.invalidatedStyleNodes - before.invalidatedStyleNodes}`);println(`color: ${getComputedStyle(target).color}`);});</script>diff --git a/Tests/LibWeb/Text/input/css/style-engine/rule-edit-updates-signature.html b/Tests/LibWeb/Text/input/css/style-engine/rule-edit-updates-signature.htmlnew file mode 100644index 00000000000..c88d4cf45ea--- /dev/null+++ b/Tests/LibWeb/Text/input/css/style-engine/rule-edit-updates-signature.html@@ -0,0 +1,21 @@+<!DOCTYPE html>+<script src="../../include.js"></script>+<style>+ #target { color: blue }+ #target.active { color: red }+</style>+<div id="target"></div>+<script>+ test(() => {+ const target = document.getElementById("target");+ internals.updateStyle();++ target.classList.add("active");+ internals.updateStyle();+ println(`active color: ${getComputedStyle(target).color}`);+ target.classList.remove("active");+ internals.updateStyle();++ println(`inactive color: ${getComputedStyle(target).color}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/style-engine/rule-index-incremental-updates.html b/Tests/LibWeb/Text/input/css/style-engine/rule-index-incremental-updates.htmlnew file mode 100644index 00000000000..d62594c3398--- /dev/null+++ b/Tests/LibWeb/Text/input/css/style-engine/rule-index-incremental-updates.html@@ -0,0 +1,76 @@+<!DOCTYPE html>+<script src="../../include.js"></script>+<style>+ .base { color: red; }+</style>+<div id="container"></div>+<script>+ function color(element) {+ return getComputedStyle(element).color;+ }++ function step(label, change) {+ internals.resetStyleCounters();+ change();+ internals.updateStyle();+ const counters = internals.styleCounters();+ println(`${label}: index builds ${counters.indexBuilds}, entries indexed ${counters.indexedEntries}, full passes ${counters.fullPasses}, hinted <= 2 ${counters.hintedElements <= 2}`);+ }++ test(() => {+ for (let i = 0; i < 50; ++i) {+ const div = document.createElement("div");+ div.className = "base";+ container.appendChild(div);+ }+ const target = document.createElement("div");+ target.id = "target";+ container.appendChild(target);+ const other = document.createElement("div");+ other.className = "other";+ container.appendChild(other);+ internals.updateStyle();++ // An appended sheet indexes its own rules alone, and restyles what they match.+ const style = document.createElement("style");+ step("appended sheet", () => {+ style.textContent = "#target { color: green; }";+ document.head.appendChild(style);+ });+ println(`target: ${color(target)}`);++ // A rule inserted into a sheet indexes that rule alone.+ step("inserted rule", () => style.sheet.insertRule(".other { color: blue; }", 1));+ println(`other: ${color(other)}`);++ // A rule edited in place indexes that rule again alone.+ step("edited rule", () => (style.sheet.cssRules[1].style.color = "orange"));+ println(`other: ${color(other)}`);++ // A deleted rule restyles what it matched.+ step("deleted rule", () => style.sheet.deleteRule(1));+ println(`other: ${color(other)}`);++ // A sheet whose media stops matching takes its rules out, and back in.+ step("media off", () => (style.media = "print"));+ println(`target: ${color(target)}`);+ step("media on", () => (style.media = "all"));+ println(`target: ${color(target)}`);++ // A removed sheet restyles what its rules matched.+ step("removed sheet", () => style.remove());+ println(`target: ${color(target)}`);++ // A sheet inserted before another ranks below it.+ const first = document.createElement("style");+ first.textContent = "#target { color: green; }";+ document.head.appendChild(first);+ internals.updateStyle();+ const second = document.createElement("style");+ step("sheet inserted before", () => {+ second.textContent = "#target { color: purple; }";+ document.head.insertBefore(second, first);+ });+ println(`target: ${color(target)}`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/style-graph-recompiles-mutated-sheets.html b/Tests/LibWeb/Text/input/css/style-engine/rule-inserted-after-attach-reaches-engine.htmlsimilarity index 55%rename from Tests/LibWeb/Text/input/css/style-graph-recompiles-mutated-sheets.htmlrename to Tests/LibWeb/Text/input/css/style-engine/rule-inserted-after-attach-reaches-engine.htmlindex 65106aca651..ca113c25f90 100644--- a/Tests/LibWeb/Text/input/css/style-graph-recompiles-mutated-sheets.html+++ b/Tests/LibWeb/Text/input/css/style-engine/rule-inserted-after-attach-reaches-engine.html@@ -1,27 +1,25 @@<!DOCTYPE html>-<script src="../include.js"></script>+<script src="../../include.js"></script><style id="sheet"></style><div id="target" tabindex="0"><span id="item"></span></div><script>test(() => {const sheet = document.getElementById("sheet").sheet;const item = document.getElementById("item");- document.body.offsetWidth;- internals.styleEngineTransactionReactions();+ internals.updateStyle();+ internals.resetStyleCounters();// The sheet was empty when it attached. A rule inserted afterwards still has to reach the// engine, or focusing #target routes to nothing and #item keeps the colour it started with.sheet.insertRule("#target:focus #item { color: rgb(0, 128, 0) }");document.getElementById("target").focus({ preventScroll: true });- const plan = internals.styleEngineTransactionReactions();- println(`plan: wholeDocument=${plan.wholeDocument} elements=${plan.elements.join(",")}`);+ internals.updateStyle();+ const pass = internals.styleLastPass();+ println(`full pass: ${pass.fullPass}`);+ println(`changed: [${pass.changed.join(", ")}]`);+ println(`styled only what changed: ${pass.styled.join() === pass.changed.join()}`);- // Inspecting the plan consumes that transaction. Generate a fresh state transition for the- // style update whose result is checked below.- document.getElementById("target").blur();- getComputedStyle(item).color;- document.getElementById("target").focus({ preventScroll: true });- println(`item colour: ${getComputedStyle(item).color}`);+ println(`item color: ${getComputedStyle(item).color}`);// Deleting it has to take it back out again. A rule that stays compiled keeps winning// wherever it was winning.diff --git a/Tests/LibWeb/Text/input/css/style-engine/prefix-convergence-settles-exactly.html b/Tests/LibWeb/Text/input/css/style-engine/selector-matching-settles-exactly.htmlsimilarity index 89%rename from Tests/LibWeb/Text/input/css/style-engine/prefix-convergence-settles-exactly.htmlrename to Tests/LibWeb/Text/input/css/style-engine/selector-matching-settles-exactly.htmlindex 788e2ed2008..19034e8d2c6 100644--- a/Tests/LibWeb/Text/input/css/style-engine/prefix-convergence-settles-exactly.html+++ b/Tests/LibWeb/Text/input/css/style-engine/selector-matching-settles-exactly.html@@ -27,8 +27,6 @@shadow.innerHTML = `<style>.guard ::slotted(.slotted) { color: rgb(9, 9, 9) }</style><slot></slot>`;let forced = 0;- let passes = 0;- let stops = 0;function snapshot() {return Array.from(document.querySelectorAll("#fixture *"))@@ -42,13 +40,8 @@function settlesExactly(name, mutate) {internals.updateStyle();- const before = internals.styleEngineCounters();mutate();internals.updateStyle();- const after = internals.styleEngineCounters();- passes += after.prefixConvergencePasses - before.prefixConvergencePasses;- stops += after.prefixConvergenceStops - before.prefixConvergenceStops- + after.prefixRelationStops - before.prefixRelationStops;const incremental = snapshot();internals.setUserStyle(`/* force complete style ${forced++} */`);internals.updateStyle();@@ -117,9 +110,5 @@});settlesExactly("the guard leaves the arrived subtree", () => outer.classList.remove("guard"));settlesExactly("a state changes under the guard", () => target.classList.toggle("deep"));-- // Without these the cases above would pass whether or not convergence ever ran.- println(`convergence planned some of these: ${passes > 0}`);- println(`and stopped propagation somewhere: ${stops > 0}`);});</script>diff --git a/Tests/LibWeb/Text/input/css/style-engine/prefix-transition-memo-after-retention.html b/Tests/LibWeb/Text/input/css/style-engine/selector-memo-after-retention.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/prefix-transition-memo-after-retention.htmlrename to Tests/LibWeb/Text/input/css/style-engine/selector-memo-after-retention.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/prefix-transition-memo-local-deltas.html b/Tests/LibWeb/Text/input/css/style-engine/selector-memo-local-changes.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/prefix-transition-memo-local-deltas.htmlrename to Tests/LibWeb/Text/input/css/style-engine/selector-memo-local-changes.htmldiff --git a/Tests/LibWeb/Text/input/css/style-engine/prefix-relation-survives-foreign-scope-inputs.html b/Tests/LibWeb/Text/input/css/style-engine/selector-relation-survives-foreign-scope-inputs.htmlsimilarity index 91%rename from Tests/LibWeb/Text/input/css/style-engine/prefix-relation-survives-foreign-scope-inputs.htmlrename to Tests/LibWeb/Text/input/css/style-engine/selector-relation-survives-foreign-scope-inputs.htmlindex ec8245b2956..daf9b26889c 100644--- a/Tests/LibWeb/Text/input/css/style-engine/prefix-relation-survives-foreign-scope-inputs.html+++ b/Tests/LibWeb/Text/input/css/style-engine/selector-relation-survives-foreign-scope-inputs.html@@ -36,18 +36,14 @@function settlesExactly(name, mutate) {internals.updateStyle();- const before = internals.styleEngineCounters();mutate();internals.updateStyle();- const after = internals.styleEngineCounters();- const maintained = after.prefixRelationUpdates - before.prefixRelationUpdates === 1- && after.prefixRelationBuilds - before.prefixRelationBuilds === 0;const incremental = snapshot();internals.setUserStyle(`/* force complete style ${forced++} */`);internals.updateStyle();const complete = snapshot();internals.setUserStyle("");- println(`${name}: ${incremental === complete ? "settles exactly" : "STALE"}, relation ${maintained ? "maintained" : "REBUILT"}`);+ println(`${name}: ${incremental === complete ? "settles exactly" : "STALE"}`);if (incremental !== complete) {println(` incremental: ${incremental}`);println(` complete: ${complete}`);diff --git a/Tests/LibWeb/Text/input/css/style-engine/prefix-relation-survives-tree-scope-moves.html b/Tests/LibWeb/Text/input/css/style-engine/selector-relation-survives-tree-scope-moves.htmlsimilarity index 92%rename from Tests/LibWeb/Text/input/css/style-engine/prefix-relation-survives-tree-scope-moves.htmlrename to Tests/LibWeb/Text/input/css/style-engine/selector-relation-survives-tree-scope-moves.htmlindex 6d582b0b0dc..a9143af90a7 100644--- a/Tests/LibWeb/Text/input/css/style-engine/prefix-relation-survives-tree-scope-moves.html+++ b/Tests/LibWeb/Text/input/css/style-engine/selector-relation-survives-tree-scope-moves.html@@ -29,18 +29,14 @@function settlesExactly(name, mutate) {internals.updateStyle();- const before = internals.styleEngineCounters();mutate();internals.updateStyle();- const after = internals.styleEngineCounters();- const maintained = after.prefixRelationUpdates - before.prefixRelationUpdates === 1- && after.prefixRelationBuilds - before.prefixRelationBuilds === 0;const incremental = snapshot();internals.setUserStyle(`/* force complete style ${forced++} */`);internals.updateStyle();const complete = snapshot();internals.setUserStyle("");- println(`${name}: ${incremental === complete ? "settles exactly" : "STALE"}, relation ${maintained ? "maintained" : "REBUILT"}`);+ println(`${name}: ${incremental === complete ? "settles exactly" : "STALE"}`);if (incremental !== complete) {println(` incremental: ${incremental}`);println(` complete: ${complete}`);diff --git a/Tests/LibWeb/Text/input/css/style-engine/retained-prefix-states-settle-exactly.html b/Tests/LibWeb/Text/input/css/style-engine/selector-states-settle-exactly.htmlsimilarity index 88%rename from Tests/LibWeb/Text/input/css/style-engine/retained-prefix-states-settle-exactly.htmlrename to Tests/LibWeb/Text/input/css/style-engine/selector-states-settle-exactly.htmlindex 78ea11b6695..522962af113 100644--- a/Tests/LibWeb/Text/input/css/style-engine/retained-prefix-states-settle-exactly.html+++ b/Tests/LibWeb/Text/input/css/style-engine/selector-states-settle-exactly.html@@ -19,7 +19,6 @@// retained transition still describes the element that left. Cycle the same subtree out and// back often enough to reuse identities, and settle exactly every time.let forced = 0;- let cacheHits = 0;function snapshot() {return Array.from(document.querySelectorAll("#fixture *"))@@ -32,12 +31,8 @@function settlesExactly(name, mutate) {internals.updateStyle();- const before = internals.styleEngineCounters();mutate();internals.updateStyle();- const after = internals.styleEngineCounters();- cacheHits += after.prefixTransitionCacheHits - before.prefixTransitionCacheHits- + after.prefixRelationUpdates - before.prefixRelationUpdates;const incremental = snapshot();CSS.registerProperty({ name: `--force-${forced++}`, syntax: "*", inherits: false, initialValue: "1px" });internals.updateStyle();@@ -91,8 +86,6 @@if (!settlesExactly("the guard moves again with it in place", () => outer.classList.toggle("guard")))++stale;- // Without these the cycles above would pass whether or not anything was ever retained.- println(`invalidation consumed retained selector state: ${cacheHits > 0}`);println(`stale settlements: ${stale}`);println(`final: ${snapshot()}`);});diff --git a/Tests/LibWeb/Text/input/css/style-engine/shared-match-answer-pseudo-kinds.html b/Tests/LibWeb/Text/input/css/style-engine/shared-matching-pseudo-kinds.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/shared-match-answer-pseudo-kinds.htmlrename to Tests/LibWeb/Text/input/css/style-engine/shared-matching-pseudo-kinds.htmldiff --git a/Tests/LibWeb/Text/input/css/style-graph-patches-one-rule.html b/Tests/LibWeb/Text/input/css/style-engine/sheet-edit-moves-one-rule.htmlsimilarity index 51%rename from Tests/LibWeb/Text/input/css/style-graph-patches-one-rule.htmlrename to Tests/LibWeb/Text/input/css/style-engine/sheet-edit-moves-one-rule.htmlindex b32ccf34087..da517c62195 100644--- a/Tests/LibWeb/Text/input/css/style-graph-patches-one-rule.html+++ b/Tests/LibWeb/Text/input/css/style-engine/sheet-edit-moves-one-rule.html@@ -1,5 +1,5 @@<!DOCTYPE html>-<script src="../include.js"></script>+<script src="../../include.js"></script><style id="sheet">.a { color: rgb(1, 0, 0) }.b { color: rgb(2, 0, 0) }@@ -9,19 +9,11 @@<script>test(() => {const sheet = document.getElementById("sheet").sheet;- // The first CSSOM edit recompiles shared contents into a private stylesheet. Insert and remove- // a dummy rule before measuring, so the counters cover only subsequent incremental edits.- sheet.insertRule(":not(*) {}", 0);- sheet.deleteRule(0);const target = document.getElementById("target");document.body.offsetWidth;- // Editing a sheet moves one rule; the rules around it are untouched. Compiling the whole- // sheet again would retire every identity in it and turn a one-rule edit into a program- // change over all of them.- const before = internals.styleEngineCounters().styleRulesCompiled;+ // Editing a sheet moves one rule; the rules around it are untouched.sheet.insertRule("#target:focus { color: rgb(0, 128, 0) }", 1);- println(`rules compiled by insertRule: ${internals.styleEngineCounters().styleRulesCompiled - before}`);// The rule landed where it was asked to, and it routes.target.focus();@@ -30,14 +22,10 @@// Its selector can change without the sheet being rebuilt, and the old selector stops// reaching anything.- const beforeEdit = internals.styleEngineCounters().styleRulesCompiled;sheet.cssRules[1].selectorText = "#target:focus, .unrelated";- println(`rules compiled by selectorText: ${internals.styleEngineCounters().styleRulesCompiled - beforeEdit}`);println(`target colour after edit: ${getComputedStyle(target).color}`);- const beforeDelete = internals.styleEngineCounters().styleRulesCompiled;sheet.deleteRule(1);- println(`rules compiled by deleteRule: ${internals.styleEngineCounters().styleRulesCompiled - beforeDelete}`);println(`target colour after delete: ${getComputedStyle(target).color}`);});</script>diff --git a/Tests/LibWeb/Text/input/css/style-engine/stale-match-answer-retired-by-plan.html b/Tests/LibWeb/Text/input/css/style-engine/stale-matching-retired.htmlsimilarity index 100%rename from Tests/LibWeb/Text/input/css/style-engine/stale-match-answer-retired-by-plan.htmlrename to Tests/LibWeb/Text/input/css/style-engine/stale-matching-retired.htmldiff --git a/Tests/LibWeb/Text/input/css/withheld-attribute-resource.css b/Tests/LibWeb/Text/input/css/withheld-attribute-resource.cssnew file mode 100644index 00000000000..b8345080484--- /dev/null+++ b/Tests/LibWeb/Text/input/css/withheld-attribute-resource.css@@ -0,0 +1 @@+[data-shared] { color: rgb(0, 128, 0); }