Truly independent web browser
LibWeb: Check the style engine against cold passes and report its work
Andreas Kling732da341400f
diff --git a/Libraries/LibWeb/Internals/Internals.cpp b/Libraries/LibWeb/Internals/Internals.cppindex 023e97e19fc..24924fa2bc1 100644--- a/Libraries/LibWeb/Internals/Internals.cpp+++ b/Libraries/LibWeb/Internals/Internals.cpp@@ -19,6 +19,7 @@#include <LibCore/EventLoop.h>#include <LibCore/TimeZone.h>#include <LibGC/Heap.h>+#include <LibGC/RootVector.h>#include <LibGfx/Cursor.h>#include <LibHTTP/HSTS/ParsedHSTSPolicy.h>#include <LibJS/Runtime/AbstractOperations.h>@@ -45,7 +46,9 @@#include <LibWeb/CSS/CSSNestedDeclarations.h>#include <LibWeb/CSS/CSSStyleRule.h>#include <LibWeb/CSS/ComputedValues.h>+#include <LibWeb/CSS/CustomPropertyData.h>#include <LibWeb/CSS/FontFace.h>+#include <LibWeb/CSS/InstalledStyle.h>#include <LibWeb/CSS/PropertyID.h>#include <LibWeb/CSS/PseudoElement.h>#include <LibWeb/CSS/StyleComputer.h>@@ -2542,6 +2545,15 @@ Utf16String Internals::frame_scheduler_state() constvoid Internals::hold_next_frame(Utf16String const& hold){+ if (hold == "claim"sv) {+ Layout::RustFFI::render_state_hold_next_style_flight_claim_for_testing();+ return;+ }+ if (hold == "style"sv) {+ Layout::RustFFI::render_state_hold_next_style_flight_for_testing();+ HTML::main_thread_event_loop().hold_next_frame_for_testing();+ return;+ }Layout::RustFFI::render_state_hold_next_recording_for_testing();if (hold == "layout"sv) {HTML::main_thread_event_loop().hold_next_layout_for_testing();@@ -2673,6 +2685,68 @@ GC::Ref<JS::Object> Internals::style_ffi_counters()return object;}+GC::Ref<JS::Object> Internals::style_memory_report()+{+ auto& document = window().associated_document();+ Layout::ForcedReadScope read { document };+ auto& realm = HTML::relevant_realm(window());+ auto owners = JS::Object::create(realm, nullptr);+ auto define = [&](JS::Object& object, StringView name, u64 value) {+ object.define_direct_property(Utf16FlyString::from_utf8(name), JS::Value(static_cast<double>(value)), JS::default_attributes);+ };++ Vector<u64> bytes;+ for (size_t index = 0;; ++index) {+ size_t name_length = 0;+ if (!CSS::StyleEngineFFI::style_engine_memory_owner_name(index, &name_length))+ break;+ bytes.append(0);+ }+ u64 elements = 0;+ u64 styled_elements = 0;+ auto count = CSS::StyleEngineFFI::style_engine_memory_report(document.style_computer().style_engine().host(), read, bytes.data(), bytes.size(), &elements, &styled_elements);+ VERIFY(count == bytes.size());+ for (size_t index = 0; index < bytes.size(); ++index) {+ size_t name_length = 0;+ auto const* name = CSS::StyleEngineFFI::style_engine_memory_owner_name(index, &name_length);+ define(*owners, StringView { name, name_length }, bytes[index]);+ }++ // NB: What the elements hold of style on the C++ side: the installed style view each carries and the presentational+ // hints it published. The custom-property environments they hold are the style engine's stores.+ u64 installed_style_bytes = 0;+ u64 hint_bytes = 0;+ document.for_each_in_inclusive_subtree_of_type<DOM::Element>([&](DOM::Element& element) {+ installed_style_bytes += sizeof(CSS::InstalledStyle);+ hint_bytes += element.published_presentational_hint_properties_heap_size();+ return TraversalDecision::Continue;+ });+ define(*owners, "cppInstalledStyles"sv, installed_style_bytes);+ define(*owners, "cppHintProperties"sv, hint_bytes);++ auto object = JS::Object::create(realm, nullptr);+ object->define_direct_property("owners"_utf16_fly_string, owners, JS::default_attributes);+ define(*object, "elements"sv, elements);+ define(*object, "styledElements"sv, styled_elements);+ return object;+}++u64 Internals::style_memory_of_frames()+{+ auto* sizer = CSS::StyleEngineFFI::style_engine_memory_sizer_create();+ u64 bytes = 0;+ for (auto const& navigable : window().associated_document().inclusive_descendant_navigables()) {+ auto* local_navigable = as_if<HTML::LocalNavigable>(*navigable);+ if (!local_navigable || !local_navigable->active_document())+ continue;+ auto document = local_navigable->active_document();+ Layout::ForcedReadScope read { *document };+ bytes += CSS::StyleEngineFFI::style_engine_memory_beyond(document->style_computer().style_engine().host(), read, sizer);+ }+ CSS::StyleEngineFFI::style_engine_memory_sizer_destroy(sizer);+ return bytes;+}+GC::Ref<JS::Object> Internals::style_engine_counters(){Layout::ForcedReadScope read { window().associated_document() };@@ -2687,10 +2761,6 @@ GC::Ref<JS::Object> Internals::style_engine_counters()JS::Value(static_cast<double>(value)),JS::default_attributes);}- object->define_direct_property(- "computedStyleRecordViewPins"_utf16_fly_string,- JS::Value(static_cast<double>(window().associated_document().style_computer().computed_style_record_view_pin_count())),- JS::default_attributes);return object;}@@ -2757,48 +2827,151 @@ u64 Internals::layout_arena_shell_count()return Layout::RustFFI::render_state_shell_count(document.layout_node_arena().host());}-GC::Ref<JS::Object> Internals::style_engine_transaction_reactions()+GC::Ref<JS::Object> Internals::style_cold_pass(bool verify, u32 threads){// A script reads the render state, which waits for a frame in flight.Layout::ForcedReadScope read { window().associated_document() };- auto& realm = HTML::relevant_realm(window());- auto& document = window().associated_document();- auto& style_computer = document.style_computer();+ auto& realm = window().principal_realm();auto object = JS::Object::create(realm, nullptr);+ auto& document = window().associated_document();+ auto* root = document.document_element();+ if (!root || root->style_node_id() == 0)+ return object;+ auto host = document.style_computer().style_engine().host();+ auto nanoseconds = CSS::StyleEngineFFI::style_engine_cold_pass(host, read, root->style_node_id(), verify, threads);+ object->define_direct_property("milliseconds"_utf16_fly_string, JS::Value(static_cast<double>(nanoseconds) / 1'000'000.0), JS::default_attributes);+ // NB: In the order of the report fields of the Rust style engine.+ static constexpr Array field_names {+ "elements"sv,+ "indexedEntries"sv,+ "indexNanoseconds"sv,+ "styleNanoseconds"sv,+ "threads"sv,+ "candidates"sv,+ "bloomRejections"sv,+ "evaluations"sv,+ "matches"sv,+ "winners"sv,+ "computedElements"sv,+ "directlyComputedElements"sv,+ "sharedElements"sv,+ "reusedElements"sv,+ "pseudoElements"sv,+ "differences"sv,+ };+ for (u32 index = 0; index < field_names.size(); ++index) {+ auto value = CSS::StyleEngineFFI::style_engine_cold_pass_report(host, read, index);+ object->define_direct_property(Utf16FlyString::from_utf8(field_names[index]), JS::Value(static_cast<double>(value)), JS::default_attributes);+ }+ return object;+}+GC::Ref<JS::Object> Internals::style_live_report(bool verify)+{+ // A script reads the render state, which waits for a frame in flight.+ Layout::ForcedReadScope read { window().associated_document() };+ auto& realm = window().principal_realm();+ auto object = JS::Object::create(realm, nullptr);+ auto& document = window().associated_document();auto* root = document.document_element();if (!root || root->style_node_id() == 0)return object;+ auto host = document.style_computer().style_engine().host();+ // NB: In the order of the live report fields of the Rust style engine.+ static constexpr Array field_names {+ "passes"sv,+ "fullPasses"sv,+ "styledElements"sv,+ "invalidationNanoseconds"sv,+ "styleNanoseconds"sv,+ "verifiedElements"sv,+ "missingRecords"sv,+ "differences"sv,+ "hintedElements"sv,+ "hintedSubtrees"sv,+ "changedElements"sv,+ "invalidationVisits"sv,+ "invalidationTests"sv,+ "coldPasses"sv,+ };+ for (u32 index = 0; index < field_names.size(); ++index) {+ auto value = CSS::StyleEngineFFI::style_engine_live_report(host, read, root->style_node_id(), verify && index == 0, index);+ object->define_direct_property(Utf16FlyString::from_utf8(field_names[index]), JS::Value(static_cast<double>(value)), JS::default_attributes);+ }+ return object;+}- auto tags = MUST(JS::Array::create(realm, 0));- u32 index = 0;- Function<void(ReadonlySpan<CSS::StyleNodeID>)> consume = [&](ReadonlySpan<CSS::StyleNodeID> style_node_ids) {- for (auto style_node_id : style_node_ids) {- auto element = style_computer.element_for_style_node(style_node_id);- if (!element)- continue;- auto identity = element->id().has_value() ? *element->id() : element->local_name();- MUST(tags->create_data_property_or_throw(index++, JS::PrimitiveString::create(vm(), identity)));- }+GC::Ref<JS::Object> Internals::style_counters()+{+ // A script reads the render state, which waits for a frame in flight.+ Layout::ForcedReadScope read { window().associated_document() };+ auto& realm = window().principal_realm();+ auto object = JS::Object::create(realm, nullptr);+ auto host = window().associated_document().style_computer().style_engine().host();+ // NB: In the order of StyleCounter in the Rust style engine.+ static constexpr Array field_names {+ "passes"sv,+ "fullPasses"sv,+ "styledElements"sv,+ "changedElements"sv,+ "hintedElements"sv,+ "hintedSubtrees"sv,+ "invalidationVisits"sv,+ "invalidationTests"sv,+ "coldPasses"sv,+ "sharedElements"sv,+ "reusedElements"sv,+ "indexBuilds"sv,+ "indexedEntries"sv,+ "compiledSelectors"sv,+ "userAgentIndexBuilds"sv,+ "matchedElements"sv,+ "relativeWalks"sv,};- auto transaction_is_scoped = style_computer.style_engine().take_diagnostic_style_transaction(read, root->style_node_id(), move(consume));- object->define_direct_property("wholeDocument"_utf16_fly_string, JS::Value(!transaction_is_scoped), JS::default_attributes);- object->define_direct_property("elements"_utf16_fly_string, tags, JS::default_attributes);+ for (u32 index = 0; index < field_names.size(); ++index) {+ auto value = CSS::StyleEngineFFI::style_engine_style_counter(host, read, index);+ object->define_direct_property(Utf16FlyString::from_utf8(field_names[index]), JS::Value(static_cast<double>(value)), JS::default_attributes);+ }return object;}-double Internals::style_engine_match_document()+void Internals::reset_style_counters()+{+ // A script reads the render state, which waits for a frame in flight.+ Layout::ForcedReadScope read { window().associated_document() };+ (void)CSS::StyleEngineFFI::style_engine_reset_style_counters(window().associated_document().style_computer().style_engine().host(), read);+}++GC::Ref<JS::Object> Internals::style_last_pass(){// A script reads the render state, which waits for a frame in flight.Layout::ForcedReadScope read { window().associated_document() };+ auto& realm = window().principal_realm();auto& document = window().associated_document();+ auto& style_computer = document.style_computer();+ auto host = style_computer.style_engine().host();+ auto object = JS::Object::create(realm, nullptr);auto* root = document.document_element();- if (!root || root->style_node_id() == 0)- return -1;- auto matches = CSS::StyleEngineFFI::style_engine_match_document(document.style_computer().style_engine().host(), read, root->style_node_id());- if (matches == NumericLimits<size_t>::max())- return -1;- return static_cast<double>(matches);+ auto root_id = root ? root->style_node_id() : CSS::StyleNodeID {};+ object->define_direct_property("fullPass"_utf16_fly_string, JS::Value(CSS::StyleEngineFFI::style_engine_last_pass_is_full(host, read)), JS::default_attributes);+ auto elements = [&](bool changed) {+ auto array = MUST(JS::Array::create(realm, 0));+ if (root_id == 0)+ return array;+ u32 index = 0;+ auto size = CSS::StyleEngineFFI::style_engine_last_pass_size(host, read, root_id, changed);+ for (u32 position = 0; position < size; ++position) {+ auto element = style_computer.element_for_style_node(CSS::StyleNodeID { CSS::StyleEngineFFI::style_engine_last_pass_element(host, read, root_id, changed, position) });+ if (!element)+ continue;+ auto identity = element->id().has_value() ? *element->id() : element->local_name();+ MUST(array->create_data_property_or_throw(index++, JS::PrimitiveString::create(vm(), identity)));+ }+ return array;+ };+ object->define_direct_property("styled"_utf16_fly_string, elements(false), JS::default_attributes);+ object->define_direct_property("changed"_utf16_fly_string, elements(true), JS::default_attributes);+ return object;}// Names every rule identity StyleEngine was given, so a disagreement can be reported as the selector@@ -2829,12 +3002,11 @@ static void collect_style_engine_rule_names(Layout::BegunRead const& read, CSS::}}-// What StyleEngine matches, element by element, in the order the cascade applies it.+// What the style engine matches, element by element, in the order the cascade applies it.//// This is a snapshot of the engine's own answer rather than a comparison against a second matcher:// a shape whose matching changes shows up as a diff, and the expectation is readable enough to say-// whether the change was meant. It is the regression guard the agreement report used to be, without-// a second engine to be right or wrong about.+// whether the change was meant.Utf16String Internals::style_engine_matched_rules(){// A script reads the render state, which waits for a frame in flight.@@ -2843,23 +3015,15 @@ Utf16String Internals::style_engine_matched_rules()document.update_style();auto& style_computer = document.style_computer();- // The page's own rules are what a test is about. A user-agent rule reaching an element is not- // this page's business and would bury the answer, so it is named and then left out.+ // The page's own rules are what a test is about, so the engine leaves user-agent rules out and+ // only the page's are named.HashMap<CSS::StyleEngineRuleID, Utf16String> rule_names;HashMap<CSS::StyleEngineRuleID, Utf16String> rule_places;- HashTable<CSS::StyleEngineRuleID> user_agent_rules;auto name_sheet = [&](CSS::StyleSheetState& source_sheet, StringView place) {auto& sheet = source_sheet.shared_compiled_style_sheet() ? source_sheet.shared_compiled_style_sheet()->contents() : source_sheet;- HashMap<CSS::StyleEngineRuleID, Utf16String> names;for (size_t index = 0; index < sheet.css_rules()->length(); ++index)- collect_style_engine_rule_names(read, style_computer, *sheet.css_rules()->item(index), names, rule_places, Utf16String::from_utf8(place));- for (auto const& [rule_id, name] : names) {- rule_names.set(rule_id, name);- if (place == "user-agent"sv)- user_agent_rules.set(rule_id);- }+ collect_style_engine_rule_names(read, style_computer, *sheet.css_rules()->item(index), rule_names, rule_places, Utf16String::from_utf8(place));};- document.style_scope().for_each_stylesheet(CSS::CascadeOrigin::UserAgent, [&](CSS::StyleSheetState& sheet) { name_sheet(sheet, "user-agent"sv); });document.style_scope().for_each_stylesheet(CSS::CascadeOrigin::User, [&](CSS::StyleSheetState& sheet) { name_sheet(sheet, "user"sv); });document.style_scope().for_each_stylesheet(CSS::CascadeOrigin::Author, [&](CSS::StyleSheetState& sheet) { name_sheet(sheet, "author"sv); });for (auto& sheet : document.style_scope().style_sheets())@@ -2870,7 +3034,28 @@ Utf16String Internals::style_engine_matched_rules()name_sheet(*sheet, "shadow"sv);});- Utf16StringBuilder builder;+ GC::RootVector<GC::Ref<DOM::Element>> elements;+ Vector<u32> nodes;+ document.for_each_shadow_including_descendant([&](DOM::Node& node) {+ if (auto* element = as_if<DOM::Element>(node); element && element->style_node_id() != 0) {+ elements.append(*element);+ nodes.append(element->style_node_id().value());+ }+ return TraversalDecision::Continue;+ });++ auto host = style_computer.style_engine().host();+ Vector<CSS::StyleEngineFFI::FfiMatchedRule> matches;+ matches.resize(max(nodes.size() * 4, 16uz));+ auto count = CSS::StyleEngineFFI::style_engine_matched_rules(host, read, nodes.data(), nodes.size(), matches.data(), matches.size(), false);+ if (count > matches.size()) {+ // Nothing was written, so grow and ask again.+ matches.resize(count);+ count = CSS::StyleEngineFFI::style_engine_matched_rules(host, read, nodes.data(), nodes.size(), matches.data(), matches.size(), false);+ VERIFY(count <= matches.size());+ }+ matches.shrink(count);+auto describe = [&](DOM::Element const& element) {Utf16StringBuilder description;description.append(element.local_name());@@ -2881,33 +3066,34 @@ Utf16String Internals::style_engine_matched_rules()return description.to_string();};- document.for_each_shadow_including_descendant([&](DOM::Node& node) {- auto* element = as_if<DOM::Element>(node);- if (!element || element->style_node_id() == 0)- return TraversalDecision::Continue;- Vector<CSS::StyleEngine::RuleMatch> matches;- if (!style_computer.style_engine().match_element(read, element->style_node_id(), matches, CSS::StyleEngine::MatchPurpose::Exact)) {- builder.appendff("{}: the engine could not answer\n", describe(*element));- return TraversalDecision::Continue;- }+ Utf16StringBuilder builder;+ size_t next_match = 0;+ for (u32 position = 0; position < elements.size(); ++position) {+ auto const& element = *elements[position];Utf16StringBuilder line;- for (auto const& match : matches) {- auto rule_id = CSS::StyleEngineRuleID { match.rule };- if (user_agent_rules.contains(rule_id))+ bool answered = true;+ for (; next_match < matches.size() && matches[next_match].node == position; ++next_match) {+ auto const& match = matches[next_match];+ if (match.rule == 0) {+ answered = false;continue;- auto name = rule_names.get(rule_id).value_or(Utf16String::formatted("<rule {}>", match.rule));+ }+ auto name = rule_names.get(CSS::StyleEngineRuleID { match.rule }).value_or(Utf16String::formatted("<rule {}>", match.rule));line.appendff(" {}", name);if (match.pseudo_element != NumericLimits<u32>::max())line.appendff("[pseudo {}]", match.pseudo_element);}+ if (!answered) {+ builder.appendff("{}: the engine could not answer\n", describe(element));+ continue;+ }if (line.is_empty())- return TraversalDecision::Continue;- builder.append(describe(*element));+ continue;+ builder.append(describe(element));builder.append(":"sv);builder.append(line.to_string());builder.append("\n"sv);- return TraversalDecision::Continue;- });+ }return builder.to_string();}@@ -3249,9 +3435,10 @@ GC::Ref<WebIDL::Promise> Internals::request_writing_suggestion_for_testing(Utf16Utf16String Internals::writing_suggestion(){for (auto const& navigable : page().hosted_navigables()) {- auto document = navigable->active_document();- if (!document)+ auto* local_navigable = as_if<HTML::LocalNavigable>(*navigable);+ if (!local_navigable || !local_navigable->active_document())continue;+ auto document = local_navigable->active_document();if (auto* controller = document->writing_suggestion_controller_if_exists(); controller && controller->showing().has_value())return controller->showing()->remainder;}@@ -3329,21 +3516,12 @@ GC::Ref<JS::Object> Internals::style_invalidation_counters_object() constobject->define_direct_property("styleEngineReactionBatchRuns"_utf16_fly_string, JS::Value(counters.style_engine_reaction_batch_runs), JS::default_attributes);object->define_direct_property("styleEngineReactionElements"_utf16_fly_string, JS::Value(counters.style_engine_reaction_elements), JS::default_attributes);object->define_direct_property("styleEnginePublishedReactions"_utf16_fly_string, JS::Value(counters.style_engine_published_reactions), JS::default_attributes);- object->define_direct_property("styleEngineRecordDeltasApplied"_utf16_fly_string, JS::Value(counters.style_engine_record_deltas_applied), JS::default_attributes);object->define_direct_property("layoutStyleRecordPublications"_utf16_fly_string, JS::Value(counters.layout_style_record_publications), JS::default_attributes);- object->define_direct_property("styleEngineMaterializedGaps"_utf16_fly_string, JS::Value(counters.style_engine_materialized_gaps), JS::default_attributes);- object->define_direct_property("elementStyleRecomputations"_utf16_fly_string, JS::Value(counters.element_style_recomputations), JS::default_attributes);- object->define_direct_property("elementStyleNoopRecomputations"_utf16_fly_string, JS::Value(counters.element_style_noop_recomputations), JS::default_attributes);- object->define_direct_property("styleRecordPropertyDamageCacheHits"_utf16_fly_string, JS::Value(counters.style_record_property_damage_cache_hits), JS::default_attributes);- object->define_direct_property("elementComputedStyleChanges"_utf16_fly_string, JS::Value(counters.element_computed_style_changes), JS::default_attributes);- object->define_direct_property("elementStyleSharedComputations"_utf16_fly_string, JS::Value(counters.element_style_shared_computations), JS::default_attributes);- object->define_direct_property("elementStyleInputChangedByParentStyle"_utf16_fly_string, JS::Value(counters.element_style_input_changed_by_parent_style), JS::default_attributes);- object->define_direct_property("elementStyleInputChangedByParentCustomProperties"_utf16_fly_string, JS::Value(counters.element_style_input_changed_by_parent_custom_properties), JS::default_attributes);- object->define_direct_property("elementStyleInputReused"_utf16_fly_string, JS::Value(counters.element_style_input_reused), JS::default_attributes);- object->define_direct_property("engineComputedStyleRecords"_utf16_fly_string, JS::Value(counters.engine_computed_style_records), JS::default_attributes);- object->define_direct_property("animatedStyleReconstructionFallbacks"_utf16_fly_string, JS::Value(counters.animated_style_reconstruction_fallbacks), JS::default_attributes);- object->define_direct_property("animatedStyleOverlayBuilds"_utf16_fly_string, JS::Value(counters.animated_style_overlay_builds), JS::default_attributes);- object->define_direct_property("animatedStyleFullBuilds"_utf16_fly_string, JS::Value(counters.animated_style_full_builds), JS::default_attributes);+ auto animated_style_samples = [&](bool rebuilt_every_group) {+ return static_cast<double>(CSS::StyleEngineFFI::style_engine_animated_style_samples(document.style_computer().style_engine().host(), read, rebuilt_every_group, false));+ };+ object->define_direct_property("animatedStyleOverlayBuilds"_utf16_fly_string, JS::Value(animated_style_samples(false)), JS::default_attributes);+ object->define_direct_property("animatedStyleFullBuilds"_utf16_fly_string, JS::Value(animated_style_samples(true)), JS::default_attributes);object->define_direct_property("animationFramePumpRequests"_utf16_fly_string, JS::Value(counters.animation_frame_pump_requests), JS::default_attributes);object->define_direct_property("animationStyleSkipCacheHits"_utf16_fly_string, JS::Value(counters.animation_style_skip_cache_hits), JS::default_attributes);object->define_direct_property("animationStyleSkipCacheMisses"_utf16_fly_string, JS::Value(counters.animation_style_skip_cache_misses), JS::default_attributes);@@ -3374,15 +3552,12 @@ GC::Ref<JS::Object> Internals::style_invalidation_counters_object() constobject->define_direct_property("documentTimelineCurrentTime"_utf16_fly_string, document_timeline_current_time.has_value() ? JS::Value(document_timeline_current_time->value) : JS::js_null(), JS::default_attributes);object->define_direct_property("compositorAnimationWakeupTimerActive"_utf16_fly_string, JS::Value(document.compositor_animation_wakeup_timer_is_active()), JS::default_attributes);object->define_direct_property("compositorAnimationObservationTimerActive"_utf16_fly_string, JS::Value(document.compositor_animation_observation_timer_is_active()), JS::default_attributes);- object->define_direct_property("baseStylePartialBuilds"_utf16_fly_string, JS::Value(counters.base_style_partial_builds), JS::default_attributes);- object->define_direct_property("baseStyleFullBuilds"_utf16_fly_string, JS::Value(counters.base_style_full_builds), JS::default_attributes);- object->define_direct_property("computedLonghandEvaluations"_utf16_fly_string, JS::Value(counters.computed_longhand_evaluations), JS::default_attributes);- object->define_direct_property("computedLonghandDrivesStarted"_utf16_fly_string, JS::Value(counters.computed_longhand_drives_started), JS::default_attributes);object->define_direct_property("longhandWrappersMinted"_utf16_fly_string, JS::Value(CSS::longhand_wrappers_minted()), JS::default_attributes);object->define_direct_property("styleStabilizationEpochs"_utf16_fly_string, JS::Value(counters.style_stabilization_epochs), JS::default_attributes);object->define_direct_property("styleStabilizationFeedbackEpochs"_utf16_fly_string, JS::Value(counters.style_stabilization_feedback_epochs), JS::default_attributes);object->define_direct_property("provisionalStylePasses"_utf16_fly_string, JS::Value(counters.provisional_style_passes), JS::default_attributes);object->define_direct_property("styleStabilizationRoundGuardHits"_utf16_fly_string, JS::Value(counters.style_stabilization_round_guard_hits), JS::default_attributes);+ object->define_direct_property("compositeOrderDocumentPositionCompares"_utf16_fly_string, JS::Value(counters.composite_order_document_position_compares), JS::default_attributes);object->define_direct_property("styleUpdatePassGuardHits"_utf16_fly_string, JS::Value(counters.style_update_pass_guard_hits), JS::default_attributes);object->define_direct_property("exactStabilizationPasses"_utf16_fly_string, JS::Value(counters.exact_stabilization_passes), JS::default_attributes);object->define_direct_property("styleStabilizationBoundFailures"_utf16_fly_string, JS::Value(counters.style_stabilization_bound_failures), JS::default_attributes);@@ -3405,13 +3580,6 @@ GC::Ref<JS::Object> Internals::style_invalidation_counters_object() constobject->define_direct_property("styleUpdateBridgeMicroseconds"_utf16_fly_string, JS::Value(counters.style_update_bridge_microseconds), JS::default_attributes);object->define_direct_property("styleUpdateApplyMicroseconds"_utf16_fly_string, JS::Value(counters.style_update_apply_microseconds), JS::default_attributes);object->define_direct_property("styleUpdateRemainderMicroseconds"_utf16_fly_string, JS::Value(counters.style_update_remainder_microseconds), JS::default_attributes);- object->define_direct_property("customPropertyResolutions"_utf16_fly_string, JS::Value(counters.custom_property_resolutions), JS::default_attributes);- object->define_direct_property("customPropertyElements"_utf16_fly_string, JS::Value(counters.custom_property_elements), JS::default_attributes);- object->define_direct_property("customPropertyValueComputations"_utf16_fly_string, JS::Value(counters.custom_property_value_computations), JS::default_attributes);- object->define_direct_property("customPropertyOverlayHits"_utf16_fly_string, JS::Value(counters.custom_property_overlay_hits), JS::default_attributes);- object->define_direct_property("customPropertyCycleParticipants"_utf16_fly_string, JS::Value(counters.custom_property_cycle_participants), JS::default_attributes);- object->define_direct_property("styleCascadeMicroseconds"_utf16_fly_string, JS::Value(counters.style_cascade_microseconds), JS::default_attributes);- object->define_direct_property("styleValuesMicroseconds"_utf16_fly_string, JS::Value(counters.style_values_microseconds), JS::default_attributes);object->define_direct_property("scrollableOverflowRecalculations"_utf16_fly_string, JS::Value(Layout::RustFFI::render_state_scrollable_overflow_recalculation_count(document.layout_node_arena().host(), false)), JS::default_attributes);return object;}diff --git a/Libraries/LibWeb/Internals/Internals.h b/Libraries/LibWeb/Internals/Internals.hindex 9034c9844e5..1b035e3ba41 100644--- a/Libraries/LibWeb/Internals/Internals.h+++ b/Libraries/LibWeb/Internals/Internals.h@@ -314,6 +314,8 @@ public:GC::Ref<JS::Object> computed_values_stats();GC::Ref<JS::Object> style_ffi_counters();GC::Ref<JS::Object> style_engine_counters();+ GC::Ref<JS::Object> style_memory_report();+ u64 style_memory_of_frames();u64 style_record_identity(DOM::Element&);u64 layout_style_record_identity(DOM::Element&);u64 before_style_record_identity(DOM::Element&);@@ -323,9 +325,12 @@ public:u64 layout_arena_live_slot_count();void panic_render_state_for_testing();u64 layout_arena_shell_count();- double style_engine_match_document();+ GC::Ref<JS::Object> style_cold_pass(bool verify, u32 threads);+ GC::Ref<JS::Object> style_live_report(bool verify);+ GC::Ref<JS::Object> style_counters();+ void reset_style_counters();+ GC::Ref<JS::Object> style_last_pass();Utf16String style_engine_matched_rules();- GC::Ref<JS::Object> style_engine_transaction_reactions();void reset_style_ffi_counters();GC::Ref<JS::Object> style_group_sharing_info(DOM::Element&);void update_style();diff --git a/Libraries/LibWeb/Internals/Internals.idl b/Libraries/LibWeb/Internals/Internals.idlindex ba978ce4922..506622b9ab9 100644--- a/Libraries/LibWeb/Internals/Internals.idl+++ b/Libraries/LibWeb/Internals/Internals.idl@@ -343,7 +343,9 @@ interface Internals {undefined synchronizeCompositor();// Keeps the next recording that flies in flight, before it reads its frame, until releaseHeldFrame(), or until a// read waits for it. With "layout", only the next rendering update's layout that flies, or recording, is held,- // before it reads anything.+ // before it reads anything. With "style", the next style update that flies is held, before it reads anything.+ // With "claim", the Render thread does not begin the next style update that flies, which the read that waits for it+ // takes back and runs itself, and the event loop treats its rendering update as it treats any other.undefined holdNextFrame(optional DOMString hold = "");// What presented the last frame of the document's navigable: "commit" for a frame a rendering update committed,// "clock" for a tick of the document's clock lane, or "none" before the first frame.@@ -376,6 +378,12 @@ interface Internals {// operation, counting calls into the Rust style core and callbacks it makes into C++.object styleFfiCounters();object styleEngineCounters();+ // What the document's style engine holds on the heap, by owner, with the C++ style state its elements hold:+ // { owners: { name: bytes }, elements, styledElements }.+ object styleMemoryReport();+ // What the style engines of the document and the documents in its frames hold on the heap, each allocation counted+ // once however many of them share it.+ unsigned long long styleMemoryOfFrames();unsigned long long styleRecordIdentity(Element element);unsigned long long layoutStyleRecordIdentity(Element element);unsigned long long beforeStyleRecordIdentity(Element element);@@ -388,10 +396,27 @@ interface Internals {// Makes the document's render state panic answering this call, which waits for it: the WebContent process crashes.undefined panicRenderStateForTesting();unsigned long long layoutArenaShellCount();- double styleEngineMatchDocument();+ // Styles the whole document from scratch in a cold pass, without installing anything, and reports what it measured+ // and how its answers compared with the records installed.+ object styleColdPass(optional boolean verify = true, optional unsigned long threads = 0);+ // Reports what live style measured since it started, checking the records it holds against the records installed+ // when asked to.+ object styleLiveReport(optional boolean verify = true);+ // Reports what live style did since the counters were last reset, on the render state the+ // host writes. Keys: passes, fullPasses, styledElements, changedElements, hintedElements,+ // hintedSubtrees, invalidationVisits, invalidationTests, coldPasses, sharedElements,+ // reusedElements, indexBuilds, indexedEntries, compiledSelectors, userAgentIndexBuilds (see+ // StyleCounter in pipeline/counters.rs).+ object styleCounters();+ // Zeroes the counters styleCounters() reports and forgets the last pass.+ undefined resetStyleCounters();+ // Reports the most recent pass of live style, with the passes after it that restyled what it+ // left waiting on fonts, as { fullPass, styled, changed }: whether it restyled every element,+ // the elements it styled, and those whose records it changed, each as its id, or its tag name+ // without one, in tree order.+ object styleLastPass();// Reports a snapshot of StyleEngine's matched rules for the whole document.DOMString styleEngineMatchedRules();- object styleEngineTransactionReactions();undefined resetStyleFfiCounters();// Returns, for each ComputedValues style value group of the given element, whether the// group payload is shared with the parent element, whether it is the default payload,diff --git a/Libraries/LibWeb/Rust/src/css/style/differential_tests.rs b/Libraries/LibWeb/Rust/src/css/style/differential_tests.rsdeleted file mode 100644index 582a70bcdde..00000000000--- a/Libraries/LibWeb/Rust/src/css/style/differential_tests.rs+++ /dev/null@@ -1,704 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--use std::hash::Hash;-use std::hash::Hasher;-use std::sync::Arc;--use super::StyleEngine;-use super::batch_matcher::AncestorRequirements;-use super::batch_matcher::BatchMatchState;-use super::batch_matcher::BatchMatcher;-use super::batch_matcher::RuleMatch;-use super::batch_matcher::RuleMatches;-use super::cascade::PropertyWinner;-use super::cascade::WinnerGroupKey;-use super::computed::ComputedMetadataInput;-use super::fast_hash::fast_hasher;-use super::index::DispatchCandidateWorkspace;-use super::index::FeatureValue;-use super::index::LocalFeatureKey;-use super::index::StyleAtomID;-use super::instrumentation::Counters;-use super::partial_view::Lookup;-use super::program::CascadeOrigin;-use super::program::DeclarationBlockID;-use super::program::RuleID;-use super::program::RuleKind;-use super::program::StyleSheetObjectID;-use super::selector::FeatureTest;-use super::selector::MatchScratch;-use super::selector::SelectorOp;-use super::selector::SelectorProgramBuilder;-use super::transaction::InputKey;-use super::transaction::InputValue;-use super::transaction::TreeRelations;-use super::tree::StyleNodeID;-use super::tree::TreeScopeID;--// Cover hundreds of committed mutation batches while staying cheap enough for every Rust run.-const CONTAINERS: usize = 6;-const CHILDREN: usize = 8;-const CLASSES: usize = 8;-const RULES: usize = 16;-const SEEDS: u64 = 12;-const STEPS: usize = 48;--struct Lcg(u64);--impl Lcg {- fn next(&mut self) -> u64 {- self.0 = self- .0- .wrapping_mul(6364136223846793005)- .wrapping_add(1442695040888963407);- self.0 >> 33- }-- fn under(&mut self, bound: usize) -> usize {- (self.next() % bound as u64) as usize- }-}--fn relations(parent: Option<StyleNodeID>, previous: Option<StyleNodeID>, next: Option<StyleNodeID>) -> TreeRelations {- TreeRelations {- parent,- previous_element_sibling: previous,- next_element_sibling: next,- ..TreeRelations::detached(TreeScopeID::DOCUMENT)- }-}--fn class_atom(index: usize) -> StyleAtomID {- StyleAtomID(200 + index as u32)-}--fn tag_atom(node: StyleNodeID) -> StyleAtomID {- StyleAtomID(100 + node.raw() % 3)-}--struct Workload {- engine: StyleEngine,- nodes: Vec<StyleNodeID>,- root: StyleNodeID,- containers: Vec<StyleNodeID>,- children: Vec<Vec<StyleNodeID>>,- classes: Vec<Vec<usize>>,- rules: Vec<RuleID>,- rule_conditions: Vec<bool>,-}--impl Workload {- fn new(seed: u64) -> Self {- let mut engine = StyleEngine::new();- let mut raw = vec![0; 1 + CONTAINERS + CONTAINERS * CHILDREN];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<_> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let root = nodes[0];- let containers = nodes[1..1 + CONTAINERS].to_vec();- let children: Vec<Vec<_>> = (0..CONTAINERS)- .map(|container| {- nodes[1 + CONTAINERS + container * CHILDREN..1 + CONTAINERS + (container + 1) * CHILDREN].to_vec()- })- .collect();-- engine.record_tree_delta(root, None, Some(relations(None, None, None)));- for (index, &container) in containers.iter().enumerate() {- engine.record_tree_delta(- container,- None,- Some(relations(- Some(root),- index.checked_sub(1).map(|previous| containers[previous]),- containers.get(index + 1).copied(),- )),- );- }- for (container, list) in children.iter().enumerate() {- for (index, &child) in list.iter().enumerate() {- engine.record_tree_delta(- child,- None,- Some(relations(- Some(containers[container]),- index.checked_sub(1).map(|previous| list[previous]),- list.get(index + 1).copied(),- )),- );- }- }-- let mut rng = Lcg(seed);- let mut classes = vec![Vec::new(); nodes.len()];- for (index, &node) in nodes.iter().enumerate() {- engine.record_input(- InputKey::LocalFeature(node, LocalFeatureKey::TagName),- InputValue::Feature(FeatureValue::Absent),- InputValue::Feature(FeatureValue::Atom(tag_atom(node))),- );- for _ in 0..rng.under(3) {- let class = rng.under(CLASSES);- if classes[index].contains(&class) {- continue;- }- classes[index].push(class);- engine.record_input(- InputKey::LocalFeature(node, LocalFeatureKey::Class(class_atom(class))),- InputValue::Feature(FeatureValue::Absent),- InputValue::Feature(FeatureValue::Present),- );- }- }-- let mut rules = Vec::new();- for index in 0..RULES {- let a = class_atom(index % CLASSES);- let b = class_atom((index + 3) % CLASSES);- let c = class_atom((index + 5) % CLASSES);- let mut builder = SelectorProgramBuilder::new();- let a = builder.push_feature(FeatureTest::Class(a));- let b = builder.push_feature(FeatureTest::Class(b));- let c = builder.push_feature(FeatureTest::Class(c));- let selector = match index % 8 {- 0 => a,- 1 => {- let ancestor = builder.push(SelectorOp::Ancestor(a));- builder.push_compound(&[b, ancestor])- }- 2 => {- let parent = builder.push(SelectorOp::Parent(a));- builder.push_compound(&[b, parent])- }- 3 => {- let preceding = builder.push(SelectorOp::PrecedingSibling(a));- builder.push_compound(&[b, preceding])- }- 4 => {- let previous = builder.push(SelectorOp::PreviousSibling(a));- builder.push_compound(&[b, previous])- }- 5 => {- let preceding = builder.push(SelectorOp::PrecedingSibling(a));- let sibling = builder.push_compound(&[b, preceding]);- let ancestor = builder.push(SelectorOp::Ancestor(sibling));- builder.push_compound(&[c, ancestor])- }- 6 => {- let ancestor = builder.push(SelectorOp::Ancestor(a));- let below = builder.push_compound(&[b, ancestor]);- let preceding = builder.push(SelectorOp::PrecedingSibling(below));- builder.push_compound(&[c, preceding])- }- _ => {- let previous = builder.push(SelectorOp::PreviousSibling(a));- let middle = builder.push_compound(&[b, previous]);- let previous = builder.push(SelectorOp::PreviousSibling(middle));- builder.push_compound(&[c, previous])- }- };- builder.push_entry(selector);- let selector = engine.programs.add(builder.finish());- let sheet = engine.add_sheet(StyleSheetObjectID(1000 + index as u32), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, selector);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(selector);- version.declaration_block = Some(DeclarationBlockID(1000 + index as u32));- engine.replace_rule_version(rule, version);- engine.set_rule_declared_properties(rule, &[(1 + index as u16 % 5, index % 7 == 0)]);- rules.push(rule);- }-- Self {- engine,- nodes,- root,- containers,- children,- classes,- rules,- rule_conditions: vec![true; RULES],- }- }-- fn node_relations(&self, node: StyleNodeID) -> TreeRelations {- if node == self.root {- return relations(None, None, None);- }- if let Some(index) = self.containers.iter().position(|&candidate| candidate == node) {- return relations(- Some(self.root),- index.checked_sub(1).map(|previous| self.containers[previous]),- self.containers.get(index + 1).copied(),- );- }- self.children- .iter()- .enumerate()- .find_map(|(container, children)| {- let index = children.iter().position(|&candidate| candidate == node)?;- Some(relations(- Some(self.containers[container]),- index.checked_sub(1).map(|previous| children[previous]),- children.get(index + 1).copied(),- ))- })- .expect("every workload node remains connected")- }-- fn mutate(&mut self, rng: &mut Lcg) -> (Option<StyleNodeID>, bool, String) {- match rng.under(10) {- 0..=5 => {- let index = 1 + rng.under(self.nodes.len() - 1);- let node = self.nodes[index];- let class = rng.under(CLASSES);- let (old, new) = if self.classes[index].contains(&class) {- self.classes[index].retain(|&existing| existing != class);- (FeatureValue::Present, FeatureValue::Absent)- } else {- self.classes[index].push(class);- (FeatureValue::Absent, FeatureValue::Present)- };- self.engine.record_input(- InputKey::LocalFeature(node, LocalFeatureKey::Class(class_atom(class))),- InputValue::Feature(old),- InputValue::Feature(new),- );- (None, false, format!("toggle {node:?} class{class}: {old:?} -> {new:?}"))- }- 6..=7 => {- let from = rng.under(CONTAINERS);- if self.children[from].is_empty() {- return (None, false, format!("skip empty container {from}"));- }- let from_index = rng.under(self.children[from].len());- let node = self.children[from][from_index];- let old = self.node_relations(node);- self.children[from].remove(from_index);- let to = rng.under(CONTAINERS);- let to_index = rng.under(self.children[to].len() + 1);- self.children[to].insert(to_index, node);- let new = self.node_relations(node);- if old == new {- return (None, false, format!("skip no-op move of {node:?}"));- }- self.engine.record_tree_delta(node, Some(old), Some(new));- (Some(node), false, format!("move {node:?}: {old:?} -> {new:?}"))- }- _ => {- let index = rng.under(self.rules.len());- self.rule_conditions[index] = !self.rule_conditions[index];- self.engine- .set_rule_conditions_hold(self.rules[index], self.rule_conditions[index]);- (- None,- true,- format!(- "set {:?} conditions_hold={}",- self.rules[index], self.rule_conditions[index]- ),- )- }- }- }-}--fn exact_matches(engine: &mut StyleEngine, node: StyleNodeID) -> Vec<RuleMatch> {- engine.match_element_with_exact_matcher(node, false).unwrap()-}--fn retained_matches(engine: &mut StyleEngine, node: StyleNodeID) -> Option<Vec<RuleMatch>> {- let retained = Arc::clone(engine.retained_match_answer(node).sparse().ok()?);- if !matches!(- engine.retained_match_answers.cascade_input_lookup(node),- Lookup::Known(_)- ) || !engine.match_answer_is_comparable_across_elements(node)- {- return None;- }-- let (_, dispatch) = engine.prepare_scope_program(TreeScopeID::DOCUMENT);- let mut orders: Vec<_> = (0..dispatch.entry_count())- .map(|index| dispatch.entry_at(index))- .map(|entry| (entry.rule, entry.program, entry.entry, entry.cascade_order))- .collect();- orders.sort_unstable_by_key(|&(rule, program, entry, _)| (rule, program, entry));- orders.dedup_by_key(|&mut (rule, program, entry, _)| (rule, program, entry));- let materialized = retained- .iter()- .copied()- .filter(|entry| engine.program.rule_can_decide(entry.rule))- .map(|entry| {- let index = orders- .binary_search_by_key(- &(entry.rule, entry.program, entry.entry),- |&(rule, program, entry, _)| (rule, program, entry),- )- .ok()?;- entry.materialize(node, &engine.programs, orders[index].3)- })- .collect::<Option<Vec<_>>>()?;- Some(engine.in_cascade_order(materialized, false))-}--fn batch_matches(- engine: &mut StyleEngine,- node: StyleNodeID,- ancestor_cache: bool,- scratch: Option<&mut MatchScratch>,-) -> Vec<RuleMatch> {- let (_, dispatch) = engine.prepare_scope_program(TreeScopeID::DOCUMENT);- let requirements =- ancestor_cache.then(|| AncestorRequirements::build(&engine.tree, engine.facts.primary(), &dispatch));- let mut matcher = BatchMatcher::new(- &engine.tree,- engine.facts.primary(),- &dispatch,- &engine.programs,- &engine.program,- );- if let Some(requirements) = &requirements {- matcher = matcher.with_ancestor_requirements(requirements);- }- let mut matches = RuleMatches::new();- matcher- .match_node_collecting_requests(- node,- &mut matches,- &Counters::new(),- BatchMatchState {- match_workspace: scratch,- witness_effects: None,- dispatch_workspace: &mut DispatchCandidateWorkspace::default(),- requests: None,- completed: None,- prefix_states: None,- deferred_prefix_matches: None,- },- )- .result- .unwrap();- matches.as_slice().to_vec()-}--fn normalized_rows(mut matches: Vec<RuleMatch>) -> Vec<RuleMatch> {- for matched in &mut matches {- matched.cascade_order = 0;- }- matches.sort_unstable();- matches-}--fn winners(engine: &mut StyleEngine, node: StyleNodeID, matches: &[RuleMatch]) -> Vec<PropertyWinner> {- engine.resolved_cascade_winners_for_properties(node, matches, None, None)-}--fn style_record_for_winners(engine: &mut StyleEngine, winners: &[PropertyWinner], dependency_flags: u8) -> u64 {- // The Rust harness has no C++ computed-group payloads. Project the winner inventory into the- // opaque custom-property-environment input, then ask the real style-record interner for its- // identity. Winner equality is checked directly; this also checks downstream canonicalization.- let mut hasher = fast_hasher();- winners.hash(&mut hasher);- engine- .intern_computed_groups(- &[],- 0,- hasher.finish(),- ComputedMetadataInput {- pseudo_element_styles: 0,- dependency_flags,- counter_style_environment_identity: 0,- animation_overlay_identity: 0,- animated_overlay: crate::css::host_shared::HostShared::null(),- animation_overlay_payloads: &[],- longhand_table: crate::css::host_shared::HostShared::null(),- },- )- .style_record_identity- .raw()-}--fn compare_mode(- engine: &mut StyleEngine,- node: StyleNodeID,- exact: &[RuleMatch],- actual: Vec<RuleMatch>,- mode: &str,- seed: u64,- step: usize,-) {- assert_eq!(- normalized_rows(actual.clone()),- normalized_rows(exact.to_vec()),- "selector rows diverged in {mode}; seed={seed:#018x}, first step={step}, node={node:?}"- );- let expected_winners = winners(engine, node, exact);- let actual_winners = winners(engine, node, &actual);- assert_eq!(- actual_winners, expected_winners,- "property winners diverged in {mode}; seed={seed:#018x}, first step={step}, node={node:?}"- );- let expected_style = style_record_for_winners(engine, &expected_winners, 0);- let actual_style = style_record_for_winners(engine, &actual_winners, 0);- assert_eq!(- actual_style, expected_style,- "style-record IDs diverged in {mode}; seed={seed:#018x}, first step={step}, node={node:?}"- );-}--fn verify_step(- workload: &mut Workload,- planned: &[StyleNodeID],- compare_retained: bool,- history: &[String],- seed: u64,- step: usize,-) -> usize {- let mut unplanned_retained_checks = 0;- if compare_retained {- for &node in &workload.nodes {- if planned.contains(&node) {- continue;- }- let Some(retained) = retained_matches(&mut workload.engine, node) else {- continue;- };- let exact = exact_matches(&mut workload.engine, node);- assert_eq!(- normalized_rows(retained),- normalized_rows(exact),- "unplanned retained selector rows diverged; seed={seed:#018x}, step={step}, node={node:?}\noperation history:\n{}",- history.join("\n")- );- unplanned_retained_checks += 1;- }- }-- let mut incremental = Vec::with_capacity(workload.nodes.len());- for &node in &workload.nodes {- incremental.push(- workload- .engine- .match_element_for_purpose(node, false)- .expect("a committed workload node has complete facts"),- );- }- workload.engine.end_cold_matching_batch();-- // Reuse private scratch in both orders. In reverse order the sibling cursor- // must restart exactly; cache presence and the asking order cannot change truth.- for reverse in [false, true] {- let mut scratch = MatchScratch::default();- for index in 0..workload.nodes.len() {- let index = if reverse {- workload.nodes.len() - 1 - index- } else {- index- };- let node = workload.nodes[index];- let actual = batch_matches(&mut workload.engine, node, true, Some(&mut scratch));- compare_mode(- &mut workload.engine,- node,- &incremental[index],- actual,- "private scratch with reordered asks",- seed,- step,- );- }- }-- for (&node, incremental) in workload.nodes.iter().zip(incremental) {- let exact = exact_matches(&mut workload.engine, node);- compare_mode(- &mut workload.engine,- node,- &exact,- incremental,- "incremental",- seed,- step,- );- let prefix_off = batch_matches(&mut workload.engine, node, true, None);- compare_mode(&mut workload.engine, node, &exact, prefix_off, "prefix-off", seed, step);- let caches_off = batch_matches(&mut workload.engine, node, false, None);- compare_mode(- &mut workload.engine,- node,- &exact,- caches_off,- "optional-caches-off",- seed,- step,- );- }-- for &node in &workload.nodes {- workload- .engine- .match_element_with_exact_matcher(node, true)- .expect("a committed workload node has complete facts");- }- workload.engine.end_cold_matching_batch();- unplanned_retained_checks-}--#[test]-fn seeded_transactions_match_the_cache_free_floor_in_every_mode() {- for seed_index in 0..SEEDS {- let seed = 0x5EED_5400_0000_0000_u64 | seed_index;- let mut workload = Workload::new(seed);- let mut rng = Lcg(seed ^ 0xD1FF_E2E1_71A1_0001);- assert!(!workload.engine.take_style_transaction(workload.root, |_, _, _| {}));- let initially_planned = workload.nodes.clone();- let mut unplanned_retained_checks = verify_step(&mut workload, &initially_planned, true, &[], seed, 0);- let mut history = Vec::new();-- for step in 1..=STEPS {- history.push(format!("--- step {step}"));- let mut caller_planned = Vec::new();- let mut changed_rule_conditions = false;- for _ in 0..3 {- let (moved, conditions_changed, description) = workload.mutate(&mut rng);- caller_planned.extend(moved);- changed_rule_conditions |= conditions_changed;- history.push(description);- }- let mut planned = Vec::new();- let scoped = workload- .engine- .take_style_transaction(workload.root, |_, _, reactions| {- planned.extend(- reactions- .iter()- .map(|reaction| StyleNodeID::from_raw(reaction.style_node).unwrap()),- );- });- if scoped {- planned.extend(caller_planned);- planned.sort_unstable();- planned.dedup();- } else {- planned.clone_from(&workload.nodes);- }- history.push(format!("planned: {planned:?}"));- unplanned_retained_checks +=- verify_step(&mut workload, &planned, !changed_rule_conditions, &history, seed, step);- }- assert!(- unplanned_retained_checks > 0,- "seed {seed:#018x} never checked an unplanned retained answer"- );- }-}--#[test]-fn incomplete_answer_batches_preserve_pending_lookups_and_release_ownership() {- for discard in [false, true] {- let mut workload = Workload::new(19);- let transaction = workload.engine.take_transaction();- workload.engine.release_transaction(transaction);- let len = workload.nodes.len();- let nodes = [- workload.nodes[len - 2],- workload.nodes[len - 3],- workload.nodes[len - 1],- ];- let expected: Vec<_> = nodes- .iter()- .map(|&node| {- let exact = exact_matches(&mut workload.engine, node);- normalized_rows(workload.engine.matches_for_cascade(exact, false, Some(node)))- })- .collect();- for &node in &nodes {- let state = &mut workload.engine.retained;- state.retained_match_answers.forget(&mut state.match_answers, node);- state.winner_groups.remove(node);- }- // NB: Deliberately leave the final subject's fact row unavailable. Earlier- // subjects can complete without it, in descending identity order.- workload.engine.facts.forget(nodes[2]);- workload.engine.begin_adaptive_cold_matching_batch(workload.root);- assert!(- workload- .engine- .complete_published_match_answers_for_closure(&nodes)- .is_err()- );- assert!(workload.engine.match_answers.pending_reference_count() > 0);- assert!(workload.engine.winner_groups.pending_reference_count() > 0);- for index in 0..2 {- assert!(- workload- .engine- .retained_match_answers- .answer_identity(nodes[index])- .is_none()- );- assert_eq!(- normalized_rows(workload.engine.consume_published_match_answer(nodes[index]).unwrap()),- expected[index]- );- assert!(- super::RetainedState::published_answer_lookup(- &workload.engine.published_match_answers,- workload.engine.batch_matching_traversal.as_deref(),- nodes[index],- )- .is_some_and(|(_, answer)| answer.cascade_input.is_some())- );- let key = WinnerGroupKey::current(nodes[index], workload.engine.program.version());- assert!(matches!(workload.engine.winner_groups.lookup(key), Lookup::Missing(_)));- assert!(matches!(- workload.engine.current_winner_groups().lookup(key),- Lookup::Known(_)- ));- }- if discard {- workload.engine.discard_published_match_answers();- assert_eq!(workload.engine.match_answers.pending_reference_count(), 0);- assert_eq!(workload.engine.winner_groups.pending_reference_count(), 0);- for &node in &nodes[..2] {- assert!(workload.engine.current_published_answer(node).is_none());- assert!(workload.engine.retained_match_answers.answer_identity(node).is_none());- }- } else {- // NB: Refill the same facts without starting another transaction or- // installing the pending prefix before this completion call resumes it.- let node = nodes[2];- let node_index = workload.nodes.iter().position(|&candidate| candidate == node).unwrap();- let state = &mut workload.engine.retained;- state.facts.set_tag(node, tag_atom(node));- for &class in &workload.classes[node_index] {- state.facts.set_class(node, class_atom(class), true);- }- state.facts.apply_staged();- workload- .engine- .complete_published_match_answers_for_closure(&nodes)- .unwrap();- assert!(workload.engine.match_answers.pending_reference_count() > 0);- for &node in &nodes {- assert!(workload.engine.retained_match_answers.answer_identity(node).is_none());- }- }- workload.engine.end_cold_matching_batch();- assert_eq!(workload.engine.match_answers.pending_reference_count(), 0);- assert_eq!(workload.engine.winner_groups.pending_reference_count(), 0);- if !discard {- for &node in &nodes {- assert!(workload.engine.retained_match_answers.answer_identity(node).is_some());- assert_eq!(- normalized_rows(retained_matches(&mut workload.engine, node).unwrap()),- normalized_rows(exact_matches(&mut workload.engine, node))- );- }- }- }-}diff --git a/Libraries/LibWeb/Rust/src/css/style/instrumentation.rs b/Libraries/LibWeb/Rust/src/css/style/instrumentation.rsindex 566627c655b..a243eb60708 100644--- a/Libraries/LibWeb/Rust/src/css/style/instrumentation.rs+++ b/Libraries/LibWeb/Rust/src/css/style/instrumentation.rs@@ -6,9 +6,7 @@//! Counters for StyleEngine's own decisions.//!-//! The engine chooses between selective and batch plans, between resident state and cold-//! evaluation, and between narrow and widened impact regions. Those choices are only defensible if-//! they are visible, so each one bumps a counter.+//! Each decision is only defensible if it is visible, so each one bumps a counter.use std::sync::atomic::{AtomicU64, Ordering};@@ -44,22 +42,14 @@ define_counters! {LocalFeatureDeltas => "localFeatureDeltas",StateDeltas => "stateDeltas",ElementDeclarationDeltas => "elementDeclarationDeltas",- ElementDeclarationRepairMatches => "elementDeclarationRepairMatches",ProgramDeltas => "programDeltas",CascadeTopologyDeltas => "cascadeTopologyDeltas",EnvironmentDeltas => "environmentDeltas",- InitialBulkLoads => "initialBulkLoads",- InitialBulkTreeRows => "initialBulkTreeRows",- InitialBulkMatchLoads => "initialBulkMatchLoads",- InitialBulkMatchRows => "initialBulkMatchRows",- // Normalization journal. Raw mutation count is not the default work multiplier, and the gap- // between these two numbers is the evidence for that.+ // Raw input records against the unique keys transactions take. Raw mutation count is not the+ // default work multiplier, and the gap between these two numbers is the evidence for that.RawMutationRecords => "rawMutationRecords",NormalizedUniqueKeys => "normalizedUniqueKeys",- JournalCancellations => "journalCancellations",- CoarsenedScopeMarkers => "coarsenedScopeMarkers",AtomSweeps => "atomSweeps",- AtomSweepsDeferredForActiveTraversal => "atomSweepsDeferredForActiveTraversal",AtomSweepRootSlotsVisited => "atomSweepRootSlotsVisited",StyleAtomsReclaimed => "styleAtomsReclaimed",LanguageTextsPublished => "languageTextsPublished",@@ -69,258 +59,43 @@ define_counters! {// Exclusive transaction intervals. Fused stages retain one name until execution splits.TransactionMicroseconds => "transactionMicroseconds",CommitMicroseconds => "commitMicroseconds",- RoutingPlanningMicroseconds => "routingPlanningMicroseconds",- PrepareMicroseconds => "prepareMicroseconds",- MatchingCascadeMicroseconds => "matchingCascadeMicroseconds",- ComputationPublicationMicroseconds => "computationPublicationMicroseconds",- EmitMicroseconds => "emitMicroseconds",TransactionRemainderMicroseconds => "transactionRemainderMicroseconds",- // The passes inside those phases, clocked only when `LIBWEB_STYLE_PASS_CLOCKS` is set. The- // phase clocks say which quarter of the transaction a millisecond is in; these say which- // pass, which is what decides whether a pass is per-node work or bookkeeping around it.- RoutingSetupMicroseconds => "routingSetupMicroseconds",- RoutingInputsMicroseconds => "routingInputsMicroseconds",- SequenceRoutingMicroseconds => "sequenceRoutingMicroseconds",- PendingRouteFlushMicroseconds => "pendingRouteFlushMicroseconds",- BatchCompilationMicroseconds => "batchCompilationMicroseconds",- WinnerVersionAdvanceMicroseconds => "winnerVersionAdvanceMicroseconds",- RetainedAnswerPatchLoopMicroseconds => "retainedAnswerPatchLoopMicroseconds",- CompletionBatchBeginMicroseconds => "completionBatchBeginMicroseconds",- CompletionBatchMaterializeMicroseconds => "completionBatchMaterializeMicroseconds",- CompletionBatchRelationMicroseconds => "completionBatchRelationMicroseconds",- CompletionPassMicroseconds => "completionPassMicroseconds",- ComputationLoopMicroseconds => "computationLoopMicroseconds",+// Physical work, including drives whose output is later abandoned.- RootFontInputsPrepared => "rootFontInputsPrepared",- RootFontInputsUnprovenFallbacks => "rootFontInputsUnprovenFallbacks",FontRefillRounds => "fontRefillRounds",FontResolutionRequests => "fontResolutionRequests",FontRefillResumedDrives => "fontRefillResumedDrives",FontRefillPreservedLonghands => "fontRefillPreservedLonghands",FontRefillBlockedDepth => "fontRefillBlockedDepth",EngineFullDrivesStarted => "engineFullDrivesStarted",- EnginePartialDrivesStarted => "enginePartialDrivesStarted",EnginePhysicalLonghandEvaluations => "enginePhysicalLonghandEvaluations",- EnginePartialLonghandEvaluations => "enginePartialLonghandEvaluations",- EngineDriveCopiedTableSlots => "engineDriveCopiedTableSlots",- ReachedStyleNodes => "reachedStyleNodes",// Stylesheet program.StyleRulesCompiled => "styleRulesCompiled",- ExactSelectorEntries => "exactSelectorEntries",- // Why an entry had to be conservative, so the remaining gap is a list rather than a feeling.- UnsupportedPseudoClass => "unsupportedPseudoClass",- UnsupportedUninternedName => "unsupportedUninternedName",- UnsupportedMalformed => "unsupportedMalformed",- UnsupportedCombinator => "unsupportedCombinator",- UnsupportedPseudoElement => "unsupportedPseudoElement",-- // Executed selector primitives, by category.- LocalFeatureTests => "localFeatureTests",- StateTests => "stateTests",- CombinatorSteps => "combinatorSteps",- StructuralTests => "structuralTests",- RelationalTests => "relationalTests",- // Candidate enumeration and cold evaluation.- ColdMatchingBatchMissingRows => "coldMatchingBatchMissingRows",- ColdMatchingBatchRows => "coldMatchingBatchRows",- PreparedMatchingBatchCompletenessRowsInspected => "preparedMatchingBatchCompletenessRowsInspected",- PreparedMatchingBatchRowsCloned => "preparedMatchingBatchRowsCloned",- ColdNodesEvaluated => "coldNodesEvaluated",- CandidateChecks => "candidateChecks",- RuleMatchesEmitted => "ruleMatchesEmitted",- PrefixCompoundsEvaluated => "prefixCompoundsEvaluated",- PrefixRelationUpdates => "prefixRelationUpdates",- PrefixRelationStops => "prefixRelationStops",- PrefixRelationCascadeStops => "prefixRelationCascadeStops",- PrefixRelationBuilds => "prefixRelationBuilds",- PrefixConvergencePasses => "prefixConvergencePasses",- PrefixConvergenceNodes => "prefixConvergenceNodes",- PrefixConvergenceStops => "prefixConvergenceStops",- PrefixConvergenceBypasses => "prefixConvergenceBypasses",- PrefixConvergenceUpqueries => "prefixConvergenceUpqueries",- PrefixDeadDeltaTransitions => "prefixDeadDeltaTransitions",- EngineComputedRecordDeltas => "engineComputedRecordDeltas",- EngineComputedRecordCohortHits => "engineComputedRecordCohortHits",- EngineComputedRecordSharedHits => "engineComputedRecordSharedHits",- EngineComputedPseudoRecords => "engineComputedPseudoRecords",- PseudoRecordDemandsLeftToHost => "pseudoRecordDemandsLeftToHost",- EngineComputedRecordUnchangedWinners => "engineComputedRecordUnchangedWinners",- EngineComputedRecordsAbandoned => "engineComputedRecordsAbandoned",- EngineComputedRecordGateAncestors => "engineComputedRecordGateAncestors",- EngineComputedLonghandEvaluations => "engineComputedLonghandEvaluations",- EngineComputedRecordBailIncompleteWinners => "engineComputedRecordBailIncompleteWinners",- EngineComputedRecordBailProperty => "engineComputedRecordBailProperty",- EngineComputedRecordBailWinner => "engineComputedRecordBailWinner",- EngineComputedRecordBailWinnerOperator => "engineComputedRecordBailWinnerOperator",- EngineComputedRecordBailWinnerElement => "engineComputedRecordBailWinnerElement",- EngineComputedRecordBailWinnerAnimated => "engineComputedRecordBailWinnerAnimated",- EngineComputedRecordBailUnhosted => "engineComputedRecordBailUnhosted",- EngineComputedRecordBailCustomProperties => "engineComputedRecordBailCustomProperties",- EngineComputedRecordBailSubstitution => "engineComputedRecordBailSubstitution",- EngineComputedRecordSubstitutions => "engineComputedRecordSubstitutions",- EngineComputedRecordSubstitutionMemoHits => "engineComputedRecordSubstitutionMemoHits",- EngineCustomPropertyEnvironmentsResolved => "engineCustomPropertyEnvironmentsResolved",- EngineCustomPropertyEnvironmentMemoHits => "engineCustomPropertyEnvironmentMemoHits",- EngineCustomPropertyEnvironmentAnswerHits => "engineCustomPropertyEnvironmentAnswerHits",- EngineCustomPropertyEnvironmentBails => "engineCustomPropertyEnvironmentBails",- EngineComputedRecordBailMonospaceQuirk => "engineComputedRecordBailMonospaceQuirk",- EngineComputedRecordBailRecordParent => "engineComputedRecordBailRecordParent",- EngineComputedRecordBailDrive => "engineComputedRecordBailDrive",- EngineComputedRecordBailValue => "engineComputedRecordBailValue",- EngineComputedRecordBailRecordOverlay => "engineComputedRecordBailRecordOverlay",- PrefixDeadDeltaBailMatched => "prefixDeadDeltaBailMatched",- PrefixDeadDeltaBailOwnAdditions => "prefixDeadDeltaBailOwnAdditions",- PrefixDeadDeltaBailEndpoints => "prefixDeadDeltaBailEndpoints",- PendingSelectorRoutes => "pendingSelectorRoutes",- PrefixEligibleRoutes => "prefixEligibleRoutes",- GroupedExactSelectorRoutes => "groupedExactSelectorRoutes",- PrefixTransitionCacheHits => "prefixTransitionCacheHits",- PrefixTransitionCacheMatchHits => "prefixTransitionCacheMatchHits",- PrefixTransitionCacheMatchMisses => "prefixTransitionCacheMatchMisses",- PrefixTransitionInputAsks => "prefixTransitionInputAsks",- PrefixTransitionInputsReady => "prefixTransitionInputsReady",- PrefixTransitionMemoHits => "prefixTransitionMemoHits",- PrefixTransitionMemoMisses => "prefixTransitionMemoMisses",- PrefixLocalFactIdentityHits => "prefixLocalFactIdentityHits",- PrefixLocalFactIdentityMisses => "prefixLocalFactIdentityMisses",- PrefixAnswerCacheHits => "prefixAnswerCacheHits",- PrefixAnswerCacheMisses => "prefixAnswerCacheMisses",- MatchAnswerSignatures => "matchAnswerSignatures",- MatchAnswerSignatureReuses => "matchAnswerSignatureReuses",- SelectorTruthSetMisses => "selectorTruthSetMisses",- SelectorTruthSetHits => "selectorTruthSetHits",- SelectorTruthSetRows => "selectorTruthSetRows",- SelectorTruthDerivedAnswerMisses => "selectorTruthDerivedAnswerMisses",- SelectorTruthDerivedAnswerHits => "selectorTruthDerivedAnswerHits",- RetainedMatchAnswerReuses => "retainedMatchAnswerReuses",- DeferredCascadeCompletions => "deferredCascadeCompletions",- RetainedSelectorIncidenceBatchPrograms => "retainedSelectorIncidenceBatchPrograms",- RetainedSelectorIncidenceBatchRows => "retainedSelectorIncidenceBatchRows",- RetainedSelectorIncidenceBatchMissingRows => "retainedSelectorIncidenceBatchMissingRows",- PublishedMatchAnswerConsumptions => "publishedMatchAnswerConsumptions",- PublishedMatchAnswerIdentityReads => "publishedMatchAnswerIdentityReads",- PublishedMatchAnswerRecords => "publishedMatchAnswerRecords",- PublishedMatchAnswerSharedPayloads => "publishedMatchAnswerSharedPayloads",- PublishedMatchAnswerSharedPayloadReuses => "publishedMatchAnswerSharedPayloadReuses",- PublishedMatchAnswerContextualPayloads => "publishedMatchAnswerContextualPayloads",- PublishedMatchAnswerIdentityRepairs => "publishedMatchAnswerIdentityRepairs",- PublishedMatchAnswerIdentityRepairStops => "publishedMatchAnswerIdentityRepairStops",- PublishedMatchAnswerRetainedIdentityComparisons => "publishedMatchAnswerRetainedIdentityComparisons",- PublishedMatchAnswerRetainedIdentityMatches => "publishedMatchAnswerRetainedIdentityMatches",- PublishedExactCascadeStops => "publishedExactCascadeStops",- PublishedMatchAnswerClosureCompletions => "publishedMatchAnswerClosureCompletions",- PublishedClosureRetainedIdentityStops => "publishedClosureRetainedIdentityStops",- MatchElementCallsDuringPublishedStyleTransaction => "matchElementCallsDuringPublishedStyleTransaction",- RetainedMatchAnswerPatches => "retainedMatchAnswerPatches",- RetainedMatchAnswerDeltaPatches => "retainedMatchAnswerDeltaPatches",- RetainedMatchAnswerDeltaMemoHits => "retainedMatchAnswerDeltaMemoHits",- RetainedMatchAnswerDeltaEntries => "retainedMatchAnswerDeltaEntries",- RetainedMatchAnswerFilteredPatches => "retainedMatchAnswerFilteredPatches",- RetainedPatchesUnattributed => "retainedPatchesUnattributed",- RetainedPatchesPoisoned => "retainedPatchesPoisoned",- RetainedPatchesCoarseCovered => "retainedPatchesCoarseCovered",- RetainedMatchAnswerPatchMisses => "retainedMatchAnswerPatchMisses",- RetainedMatchAnswerPatchStops => "retainedMatchAnswerPatchStops",- // Consolidated semantic reactions and typed exact repair asks. These count the rows which- // cross operator boundaries, not the routes or evaluator work which produced them.- SelectorTruthAdditions => "selectorTruthAdditions",- SelectorTruthRemovals => "selectorTruthRemovals",- SelectorTruthCancellations => "selectorTruthCancellations",- SelectorTruthRefreshes => "selectorTruthRefreshes",- SelectorTruthRepairUpqueries => "selectorTruthRepairUpqueries",- SelectorTruthRepairAdditions => "selectorTruthRepairAdditions",- SelectorTruthRepairRemovals => "selectorTruthRepairRemovals",- MatchAnswerChanges => "matchAnswerChanges",- MatchAnswerUpqueries => "matchAnswerUpqueries",- CascadeMatchesBeforeCompaction => "cascadeMatchesBeforeCompaction",- CascadeNodeHandlesPublished => "cascadeNodeHandlesPublished",- CascadeStatesInterned => "cascadeStatesInterned",- CascadeWinnerGroupsInterned => "cascadeWinnerGroupsInterned",- CascadeWinnerEntriesInterned => "cascadeWinnerEntriesInterned",- CascadeWinnerDeltaProperties => "cascadeWinnerDeltaProperties",- CascadeWinnerDeltaStops => "cascadeWinnerDeltaStops",- ComputedWinnerDeltaPropertiesConsumed => "computedWinnerDeltaPropertiesConsumed",- ComputedOutputGroupsCanonicalized => "computedOutputGroupsCanonicalized",- ComputedWinnerPropagationStops => "computedWinnerPropagationStops",+ // Computation and publication.SpecifiedValuesReused => "specifiedValuesReused",- ComputedGroupNodeHandlesPublished => "computedGroupNodeHandlesPublished",- ComputedGroupsReused => "computedGroupsReused",- // The identities each catalog mints. Unlike the reuse counters above, which credit the- // publication that happened to intern an identity first, these count the identities a- // run creates, which is a property of the content and not of the execution order.- ComputedGroupIdentitiesMinted => "computedGroupIdentitiesMinted",- ComputedGroupSetIdentitiesMinted => "computedGroupSetIdentitiesMinted",- InheritedGroupSetIdentitiesMinted => "inheritedGroupSetIdentitiesMinted",- StyleRecordIdentitiesMinted => "styleRecordIdentitiesMinted",- ComputedGroupsRetained => "computedGroupsRetained",- ComputedGroupsReachable => "computedGroupsReachable",- ComputedGroupSetsReused => "computedGroupSetsReused",- InheritedGroupNodeHandlesPublished => "inheritedGroupNodeHandlesPublished",- InheritedGroupSetsReused => "inheritedGroupSetsReused",- InheritedGroupSwapComputations => "inheritedGroupSwapComputations",- InheritedGroupSwapReuses => "inheritedGroupSwapReuses",- CustomPropertyEnvironmentNodeHandlesPublished => "customPropertyEnvironmentNodeHandlesPublished",- CustomPropertyEnvironmentsReused => "customPropertyEnvironmentsReused",- ComputedFixedMetadataNodeHandlesPublished => "computedFixedMetadataNodeHandlesPublished",- ComputedFixedMetadataInterned => "computedFixedMetadataInterned",- ComputedFixedMetadataReused => "computedFixedMetadataReused",+ // The user agent declaration blocks the document's rules declare: those the process interned+ // for this document, which no document of the process interned before, and those it shared.+ // The declaration blocks of the document's own sheets its rules declare, which the process+ // interns as it does the user agent's: those it interned for this document, and those it+ // shared with a document reaching the same blocks before.+ SheetDeclarationsInterned => "sheetDeclarationsInterned",+ SheetDeclarationsShared => "sheetDeclarationsShared",StyleRecordNodeHandlesPublished => "styleRecordNodeHandlesPublished",- StyleRecordsInterned => "styleRecordsInterned",- StyleRecordsReused => "styleRecordsReused",- StyleRecordsReaffirmed => "styleRecordsReaffirmed",AnimationOverlaySlotsAllocated => "animationOverlaySlotsAllocated",AnimationOverlaySlotsReleased => "animationOverlaySlotsReleased",AnimationOverlayRecordsUpdated => "animationOverlayRecordsUpdated",LiveAnimationOverlayRecords => "liveAnimationOverlayRecords",// Read when counters are read: the reclaimed overlay records a published frame's lease still keeps.RetiredAnimationOverlayRecords => "retiredAnimationOverlayRecords",- ComputedPseudoAssignmentsPublished => "computedPseudoAssignmentsPublished",ComputedPseudoAssignmentsRemoved => "computedPseudoAssignmentsRemoved",- ProgramCandidatesRejectedByCascade => "programCandidatesRejectedByCascade",- SelectorRoutesRejectedByCascade => "selectorRoutesRejectedByCascade",- CascadeCandidatesRejectedByWinner => "cascadeCandidatesRejectedByWinner",- // Impact regions and plan selection.- RemainingPostingBuilds => "remainingPostingBuilds",- RemainingPostingReuses => "remainingPostingReuses",- RemainingPostingRowsCopied => "remainingPostingRowsCopied",- RemainingPostingRowsInspected => "remainingPostingRowsInspected",- // How much logical membership the compiled exact-region representation covers, and how much- // interval storage it needs to do so.- ExactRegionBatchIntervals => "exactRegionBatchIntervals",- ExactRegionBatchNodes => "exactRegionBatchNodes",- RoutedEntryPoints => "routedEntryPoints",- OriginTruthRoutesFired => "originTruthRoutesFired",- OriginTruthRoutesSkipped => "originTruthRoutesSkipped",- ScopeConfinedRoutesSkipped => "scopeConfinedRoutesSkipped",+ // Input intake.ArrivingNodeFactsFolded => "arrivingNodeFactsFolded",- SheetChangeCandidatesRejected => "sheetChangeCandidatesRejected",- RelationalAnchorsConsidered => "relationalAnchorsConsidered",- RelationalAnchorsSkippedByWitness => "relationalAnchorsSkippedByWitness",- InvalidatedStyleNodes => "invalidatedStyleNodes",- PlannedNodesWithDirectAction => "plannedNodesWithDirectAction",- PlannedNodesWithSignedDelta => "plannedNodesWithSignedDelta",- PlannedNodesWithOutputChange => "plannedNodesWithOutputChange",- PlannedNodesWithUpquery => "plannedNodesWithUpquery",- PlannedNodesUnattributed => "plannedNodesUnattributed",// Style node identity lifecycle.StyleNodesAllocated => "styleNodesAllocated",- DocumentWidenings => "documentWidenings",- TransitionProofConfirmed => "transitionProofConfirmed",- TransitionProofNoPreviousState => "transitionProofNoPreviousState",- TransitionProofGenerationGap => "transitionProofGenerationGap",- TransitionProofMissingAnswer => "transitionProofMissingAnswer",- TransitionProofElementDeclarations => "transitionProofElementDeclarations",- TransitionProofRemoval => "transitionProofRemoval",- TransitionProofUnsafeRule => "transitionProofUnsafeRule",- TransitionProofPseudoOrScope => "transitionProofPseudoOrScope",- TransitionProofElementWinnerGap => "transitionProofElementWinnerGap",- TransitionProofOperatorOrContinuation => "transitionProofOperatorOrContinuation",- TransitionProofWinnerGap => "transitionProofWinnerGap",- TransitionProofPriorityWin => "transitionProofPriorityWin",}/// The counter set for one document.diff --git a/Libraries/LibWeb/Rust/src/css/style/memory_report.rs b/Libraries/LibWeb/Rust/src/css/style/memory_report.rsnew file mode 100644index 00000000000..543522b6e6f--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/memory_report.rs@@ -0,0 +1,199 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What a document's style engine holds on the heap, by owner.+//!+//! Each owner is a store of the engine, or one kind of thing several stores share: the records,+//! their group payloads and chunks, and the style values. A shared allocation is counted once, by+//! the first owner the report reaches it from, so the owners the report walks first are the ones+//! that hold the most of what others share: the initial style before the records sharing its+//! chunks, the records before the slots holding them. See [`crate::heap_size`] for what a count+//! is.++use crate::heap_size::{HeapSize, HeapSizer};+use std::sync::Arc;++macro_rules! memory_owners {+ ($($owner:ident => $name:literal,)*) => {+ /// An owner of style memory.+ #[derive(Clone, Copy, Debug, PartialEq, Eq)]+ #[repr(u8)]+ pub(crate) enum MemoryOwner {+ $($owner,)*+ }++ impl MemoryOwner {+ pub(crate) const ALL: &[MemoryOwner] = &[$(MemoryOwner::$owner,)*];+ pub(crate) const COUNT: usize = Self::ALL.len();++ pub(crate) fn name(self) -> &'static str {+ match self {+ $(MemoryOwner::$owner => $name,)*+ }+ }+ }+ };+}++memory_owners! {+ Initial => "initial",+ RuleStore => "ruleStore",+ RuleIndex => "ruleIndex",+ UserAgentIndex => "userAgentIndex",+ SheetSegments => "sheetSegments",+ SharedDeclarations => "sharedDeclarations",+ Invalidation => "invalidation",+ SpecifiedValues => "specifiedValues",+ Records => "records",+ Payloads => "payloads",+ GroupValueFacts => "groupValueFacts",+ CustomProperties => "customProperties",+ RetainedSlots => "retainedSlots",+ RecordCells => "recordCells",+ Installed => "installed",+ Projection => "projection",+ ProjectionGenerations => "projectionGenerations",+ HostTree => "hostTree",+ ElementDeclarations => "elementDeclarations",+ HeldRecordMaps => "heldRecordMaps",+ LayoutStyleColumns => "layoutStyleColumns",+ OtherMaps => "otherMaps",+ WorkerCaches => "workerCaches",+ StyleValues => "styleValues",+ AnimationEffects => "animationEffects",+ FontResolutions => "fontResolutions",+ LiveScratch => "liveScratch",+ CssAnimations => "cssAnimations",+ HostMemo => "hostMemo",+}++/// A memory report under way, and then its result.+#[derive(Default)]+pub(crate) struct MemoryReport {+ pub(crate) sizer: HeapSizer,+ bytes: [usize; MemoryOwner::COUNT],+ /// The elements the document holds.+ pub(crate) elements: usize,+ /// The elements that hold a style record.+ pub(crate) styled_elements: usize,+}++impl MemoryReport {+ /// A report of what `sizer` has not counted.+ pub(crate) fn past(sizer: HeapSizer) -> Self {+ Self {+ sizer,+ ..Self::default()+ }+ }++ pub(crate) fn add(&mut self, owner: MemoryOwner, bytes: usize) {+ self.bytes[owner as usize] += bytes;+ }++ /// Counts `value`'s heap toward `owner`.+ pub(crate) fn count<T: HeapSize + ?Sized>(&mut self, owner: MemoryOwner, value: &T) {+ let bytes = value.heap_size(&mut self.sizer);+ self.add(owner, bytes);+ }++ pub(crate) fn bytes(&self, owner: MemoryOwner) -> usize {+ self.bytes[owner as usize]+ }++ /// Ends the report, moving the style values counted aside to their owner.+ pub(crate) fn finish(mut self) -> Self {+ let style_value_bytes = std::mem::take(&mut self.sizer.style_value_bytes);+ self.add(MemoryOwner::StyleValues, style_value_bytes);+ self+ }+}++impl super::StyleEngine {+ /// What the engine holds on the heap, by owner, with the layout arena's style columns.+ pub(crate) fn memory_report(&self, arena: &crate::layout::LayoutNodeArena) -> MemoryReport {+ self.memory_report_into(MemoryReport::default(), arena)+ }++ /// [`Self::memory_report`], past what `report` has counted already.+ pub(crate) fn memory_report_into(+ &self,+ mut report: MemoryReport,+ arena: &crate::layout::LayoutNodeArena,+ ) -> MemoryReport {+ use crate::heap_size::{map_bytes, set_bytes, vec_bytes};+ let state = &self.retained;+ let bytes = state.rules.heap_size(&mut report.sizer);+ report.add(MemoryOwner::RuleStore, bytes);+ // NB: The values the declarations were written with are the blocks' own, rather than+ // counted aside.+ let style_value_bytes = report.sizer.style_value_bytes;+ let mut bytes = state.rules.declarations_heap_size(&mut report.sizer);+ if let Some(rules) = state.rules.user_agent_rules() {+ bytes += rules.declarations_heap_size(&mut report.sizer);+ }+ bytes += std::mem::replace(&mut report.sizer.style_value_bytes, style_value_bytes) - style_value_bytes;+ report.add(MemoryOwner::SharedDeclarations, bytes);+ if let Some(rules) = state.rules.user_agent_rules()+ && report.sizer.first_sight(Arc::as_ptr(rules))+ {+ let bytes = crate::heap_size::ARC_HEADER_BYTES + size_of_val(&**rules) + rules.heap_size(&mut report.sizer);+ report.add(MemoryOwner::UserAgentIndex, bytes);+ }+ if let Some(live) = &state.live_style {+ live.report_memory(&mut report);+ }+ state.computed_group_sets.report_memory(&mut report);+ let bytes = state.canonical_values.heap_size(&mut report.sizer);+ report.add(MemoryOwner::SpecifiedValues, bytes);+ let bytes = state.custom_property_environments.heap_size(&mut report.sizer);+ report.add(MemoryOwner::CustomProperties, bytes);+ report.add(+ MemoryOwner::CustomProperties,+ map_bytes(&state.element_custom_property_data)+ + map_bytes(&state.pseudo_element_custom_property_data)+ + state+ .pseudo_element_custom_property_data+ .values()+ .map(vec_bytes)+ .sum::<usize>(),+ );+ state.projection.report_memory(&mut report);+ let bytes = state.tree.heap_size(&mut report.sizer);+ report.add(MemoryOwner::HostTree, bytes);+ let bytes = state.element_declarations.heap_size(&mut report.sizer);+ report.add(MemoryOwner::ElementDeclarations, bytes);+ let held_style_records = state.held_style_records.heap_size(&mut report.sizer);+ report.add(+ MemoryOwner::HeldRecordMaps,+ held_style_records+ + map_bytes(&state.held_pseudo_style_records)+ + state.held_pseudo_style_records.values().map(vec_bytes).sum::<usize>(),+ );+ report.add(MemoryOwner::LayoutStyleColumns, arena.style_column_heap_size());+ if let Some(font_resolution) = &state.font_resolution {+ report.add(MemoryOwner::FontResolutions, font_resolution.heap_size());+ }+ let bytes = state.css_defined_animations.heap_size(&mut report.sizer);+ report.add(MemoryOwner::CssAnimations, bytes);+ let bytes = state.animation_effect_descriptions.heap_size(&mut report.sizer);+ report.add(MemoryOwner::AnimationEffects, bytes);+ report.add(+ MemoryOwner::OtherMaps,+ set_bytes(&state.keyframes_reading_parent_reset_values)+ + map_bytes(&state.layout_style_snapshots)+ + map_bytes(&state.counter_style_environment_identities)+ + map_bytes(&state.backing_elements)+ + map_bytes(&state.replaced_content_inputs)+ + map_bytes(&state.demand_records)+ + state.transition_baselines.heap_size()+ + state.scope_roots.heap_size()+ + state.scope_by_root.heap_size()+ + set_bytes(&state.unresolved_relational_arrival_keys),+ );+ report.finish()+ }+}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/allocation_count.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/allocation_count.rsnew file mode 100644index 00000000000..d185d4dd58c--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/allocation_count.rs@@ -0,0 +1,143 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The global allocator of this crate's unit test binary: the system allocator, counting what a+//! thread allocates while it runs `count_allocations`, and which of that the engine allocates itself,+//! inside a `StyleSection`. Only the test binary has it; the crate as the browser links it never+//! does.+//!+//! With LIBWEB_TEST_ALLOCATION_BACKTRACES set, each allocation counted prints a backtrace to+//! stderr, for a test that fails to name where its allocations come from.++use std::alloc::{GlobalAlloc, Layout, System};+use std::cell::Cell;+use std::sync::OnceLock;++struct CountingAllocator;++#[global_allocator]+static COUNTING_ALLOCATOR: CountingAllocator = CountingAllocator;++thread_local! {+ static COUNTING: Cell<bool> = const { Cell::new(false) };+ static PRINTS_BACKTRACES: Cell<bool> = const { Cell::new(false) };+ static ALLOCATIONS: Cell<u64> = const { Cell::new(0) };+ static STYLE_ALLOCATIONS: Cell<u64> = const { Cell::new(0) };+ static STYLE_SECTION_DEPTH: Cell<u32> = const { Cell::new(0) };+ static LIVE_BYTES: Cell<i64> = const { Cell::new(0) };+}++/// How many times a thread allocated or reallocated.+#[derive(Clone, Copy, Debug)]+pub(super) struct Allocations {+ pub everywhere: u64,+ /// Those inside a `StyleSection`: invalidating, restyling and installing.+ pub in_style: u64,+}++/// Marks the allocations of the calling thread, until it drops, as the engine's own.+pub(super) struct StyleSection;++impl StyleSection {+ pub(super) fn enter() -> Self {+ STYLE_SECTION_DEPTH.with(|depth| depth.set(depth.get() + 1));+ Self+ }+}++impl Drop for StyleSection {+ fn drop(&mut self) {+ STYLE_SECTION_DEPTH.with(|depth| depth.set(depth.get() - 1));+ }+}++/// Notes that the calling thread's live heap grew by `bytes`, or shrank where negative, while it counts.+fn note_live_bytes(bytes: i64) {+ let Ok(true) = COUNTING.try_with(Cell::get) else {+ return;+ };+ LIVE_BYTES.with(|live| live.set(live.get() + bytes));+}++fn note_allocation() {+ // NB: The thread-local keys have no destructors, so they stay readable while a thread exits.+ let Ok(true) = COUNTING.try_with(Cell::get) else {+ return;+ };+ ALLOCATIONS.with(|allocations| allocations.set(allocations.get() + 1));+ if STYLE_SECTION_DEPTH.with(Cell::get) != 0 {+ STYLE_ALLOCATIONS.with(|allocations| allocations.set(allocations.get() + 1));+ }+ if PRINTS_BACKTRACES.with(Cell::get) {+ // NB: Printing a backtrace allocates, so stop counting while it prints.+ COUNTING.with(|counting| counting.set(false));+ eprintln!("allocation:\n{}", std::backtrace::Backtrace::force_capture());+ COUNTING.with(|counting| counting.set(true));+ }+}++// SAFETY: Every call goes to the system allocator as it is.+unsafe impl GlobalAlloc for CountingAllocator {+ unsafe fn alloc(&self, layout: Layout) -> *mut u8 {+ note_allocation();+ note_live_bytes(layout.size() as i64);+ // SAFETY: Guaranteed by the caller.+ unsafe { System.alloc(layout) }+ }++ unsafe fn alloc_zeroed(&self, layout: Layout) -> *mut u8 {+ note_allocation();+ note_live_bytes(layout.size() as i64);+ // SAFETY: Guaranteed by the caller.+ unsafe { System.alloc_zeroed(layout) }+ }++ unsafe fn dealloc(&self, pointer: *mut u8, layout: Layout) {+ note_live_bytes(-(layout.size() as i64));+ // SAFETY: Guaranteed by the caller.+ unsafe { System.dealloc(pointer, layout) }+ }++ unsafe fn realloc(&self, pointer: *mut u8, layout: Layout, new_size: usize) -> *mut u8 {+ note_allocation();+ note_live_bytes(new_size as i64 - layout.size() as i64);+ // SAFETY: Guaranteed by the caller.+ unsafe { System.realloc(pointer, layout, new_size) }+ }+}++/// Runs `body`, answering what it answers and how many times the calling thread allocated or+/// reallocated meanwhile. What other threads allocate is not counted.+pub(super) fn count_allocations<T>(body: impl FnOnce() -> T) -> (T, Allocations) {+ static PRINTS_BACKTRACES_CACHE: OnceLock<bool> = OnceLock::new();+ let prints_backtraces =+ *PRINTS_BACKTRACES_CACHE.get_or_init(|| std::env::var_os("LIBWEB_TEST_ALLOCATION_BACKTRACES").is_some());+ assert!(!COUNTING.with(Cell::get), "allocations are counted once at a time");+ PRINTS_BACKTRACES.with(|prints| prints.set(prints_backtraces));+ ALLOCATIONS.with(|allocations| allocations.set(0));+ STYLE_ALLOCATIONS.with(|allocations| allocations.set(0));+ COUNTING.with(|counting| counting.set(true));+ let answer = body();+ COUNTING.with(|counting| counting.set(false));+ let allocations = Allocations {+ everywhere: ALLOCATIONS.with(Cell::get),+ in_style: STYLE_ALLOCATIONS.with(Cell::get),+ };+ (answer, allocations)+}++/// Runs `body`, answering what it answers and the bytes the calling thread allocated meanwhile+/// that are still allocated when it returns: what the answer holds, and what `body` left+/// elsewhere, as in a cache. What other threads allocate is not counted.+pub(crate) fn count_live_bytes<T>(body: impl FnOnce() -> T) -> (T, i64) {+ assert!(!COUNTING.with(Cell::get), "allocations are counted once at a time");+ PRINTS_BACKTRACES.with(|prints| prints.set(false));+ LIVE_BYTES.with(|live| live.set(0));+ COUNTING.with(|counting| counting.set(true));+ let answer = body();+ COUNTING.with(|counting| counting.set(false));+ (answer, LIVE_BYTES.with(Cell::get))+}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/allocation_tests.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/allocation_tests.rsnew file mode 100644index 00000000000..1ea8ba5939e--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/allocation_tests.rs@@ -0,0 +1,143 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! How many times a style update allocates once the engine owns a document and has seen+//! the same transactions before. A transaction that changes no style should allocate nothing, in+//! the engine (invalidating, restyling and installing) or anywhere else.+//!+//! The engine runs on the calling thread here, where every allocation is counted. Run with+//! LIBWEB_TEST_ALLOCATION_BACKTRACES set to see where a test's allocations come from.++use super::super::*;+use super::allocation_count::{Allocations, count_allocations};+use super::test_support::*;++/// How many times each transaction a test measures is taken before, for every buffer it grows+/// to reach its size.+const WARMUP_ROUNDS: usize = 4;++/// How many times a test measures each transaction.+const MEASURED_ROUNDS: usize = 3;++/// How many times std's `Mutex` allocates in a transaction that restyles one element. On Apple+/// platforms it wraps a pthread mutex, which it boxes the first time it is locked: here the+/// scratch slot of the calling thread, made for each pass, and the longhand table recipe of the+/// element's new record. Elsewhere it is a futex, which allocates nothing.+const MUTEX_ALLOCATIONS_RESTYLING_ONE_ELEMENT: u64 = if cfg!(target_vendor = "apple") { 2 } else { 0 };++struct Document {+ engine: StyleEngine,+ root: StyleNodeID,+ leaf: StyleNodeID,+ /// A class one selector names.+ target: StyleAtomID,+ /// A class no selector names.+ unnamed: StyleAtomID,+}++impl Document {+ /// Builds `root -> [a, b, c]` with one rule for the class `target`, owned by the engine,+ /// and takes every transaction the tests measure `WARMUP_ROUNDS` times.+ fn warm() -> Self {+ let (mut engine, nodes) = linear_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, sheet, ".target { color: rgb(0, 128, 0); }");+ let target = atom(&mut engine, "target");+ let unnamed = atom(&mut engine, "unnamed");+ start_live(&mut engine, nodes[0]);+ let mut document = Self {+ engine,+ root: nodes[0],+ leaf: nodes[3],+ target,+ unnamed,+ };+ for _ in 0..WARMUP_ROUNDS {+ document.toggle(target);+ document.toggle(unnamed);+ document.take_transaction();+ }+ document+ }++ fn take_transaction(&mut self) -> Allocations {+ let (engine, root) = (&mut self.engine, self.root);+ count_allocations(|| run_style_update(engine, root)).1+ }++ /// Adds `class` to the leaf in one transaction and removes it in another, and answers what+ /// each transaction allocated.+ fn toggle(&mut self, class: StyleAtomID) -> [Allocations; 2] {+ add_feature(&mut self.engine, self.leaf, LocalFeatureKey::Class(class));+ let added = self.take_transaction();+ remove_feature(&mut self.engine, self.leaf, LocalFeatureKey::Class(class));+ let removed = self.take_transaction();+ [added, removed]+ }++ /// What each of `MEASURED_ROUNDS` rounds of `transactions` allocated.+ fn measure(&mut self, mut transactions: impl FnMut(&mut Self) -> Vec<Allocations>) -> Vec<Allocations> {+ (0..MEASURED_ROUNDS).flat_map(|_| transactions(self)).collect()+ }++ fn empty_transactions(&mut self) -> Vec<Allocations> {+ self.measure(|document| vec![document.take_transaction()])+ }++ fn unnamed_class_toggles(&mut self) -> Vec<Allocations> {+ let unnamed = self.unnamed;+ self.measure(|document| document.toggle(unnamed).to_vec())+ }++ fn target_class_toggles(&mut self) -> Vec<Allocations> {+ let target = self.target;+ self.measure(|document| document.toggle(target).to_vec())+ }+}++fn in_style(allocations: &[Allocations]) -> Vec<u64> {+ allocations.iter().map(|allocations| allocations.in_style).collect()+}++fn everywhere(allocations: &[Allocations]) -> Vec<u64> {+ allocations.iter().map(|allocations| allocations.everywhere).collect()+}++fn assert_at_most(counts: Vec<u64>, bound: u64, what: &str) {+ assert!(+ counts.iter().all(|&count| count <= bound),+ "{what} allocate {counts:?} times, more than {bound}"+ );+}++#[test]+fn an_empty_transaction_allocates_nothing_in_style() {+ let allocations = Document::warm().empty_transactions();+ assert_at_most(in_style(&allocations), 0, "empty transactions");+}++#[test]+fn a_class_no_selector_names_allocates_nothing_in_style() {+ let allocations = Document::warm().unnamed_class_toggles();+ assert_at_most(in_style(&allocations), 0, "toggles of a class no selector names");+}++#[test]+fn a_class_one_selector_names_on_a_leaf_allocates_at_most_as_today() {+ let allocations = Document::warm().target_class_toggles();+ assert_at_most(+ in_style(&allocations),+ 91 + MUTEX_ALLOCATIONS_RESTYLING_ONE_ELEMENT,+ "toggles of a class one selector names",+ );+ // FIXME: Lower this as the allocations an empty transaction makes outside+ // the engine go away.+ assert_at_most(+ everywhere(&allocations),+ 114 + MUTEX_ALLOCATIONS_RESTYLING_ONE_ELEMENT,+ "toggles of a class one selector names",+ );+}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/counters.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/counters.rsnew file mode 100644index 00000000000..f287db14625--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/counters.rs@@ -0,0 +1,331 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What the engine did over the life of a document's render state, counted for tests to bound,+//! and what its last pass styled.+//!+//! A pass counts what it does in counts of its own, kept with the engine between the+//! transactions it restyles after, which the state takes into its counters once the pass kept the+//! records it computed. Unlike the live report, which a fork of the state starts anew, the counters+//! are the state's: a fork copies them as they are and counts its own passes in its copy, which+//! the state never sees, as the host never installs what a fork computes.++use super::super::tree::StyleNodeID;+use super::live::LiveField;+use super::projection::Projection;+use super::rules::RuleIndex;+use super::traversal::{Outcome, Statistics};++/// One of the counters of [`Counters`], in the order the host names them.+#[derive(Clone, Copy)]+#[repr(u32)]+pub(in super::super) enum StyleCounter {+ /// The passes of the engine: each restyle, of everything, of what transactions changed, or+ /// of the elements a pass before left waiting on fonts. A transaction that hints no element+ /// runs none.+ Passes,+ /// The passes that restyled every element: the one the engine starts from, and one after an+ /// input that can restyle any element, such as a stylesheet change.+ FullPasses,+ /// The elements passes styled: each once per pass that styled it.+ StyledElements,+ /// The elements passes styled differently than before in what their children compute from.+ ChangedElements,+ /// The elements whose hints asked a pass restyling what changed to restyle them, or their+ /// pseudo-elements, counted as the pass starts.+ HintedElements,+ /// The elements whose hints asked a pass restyling what changed to restyle their descendants,+ /// counted as the pass starts.+ HintedSubtrees,+ /// The elements the invalidation of transactions visited, following the selectors of the+ /// inputs they changed: each once per visit.+ InvalidationVisits,+ /// The compounds the invalidation of transactions tested against an element.+ InvalidationTests,+ /// The cold passes the engine started from: one each time it started.+ ColdPasses,+ /// The elements passes gave the record of an element they styled before with the same parent,+ /// the same inputs and the same revalidation answers, without matching them.+ SharedElements,+ /// The elements passes gave the record of an element whose cascade picked the same+ /// declarations, which they matched and cascaded but did not compute.+ ReusedElements,+ /// The rule indexes the engine built: one as it started, and one for each pass after a rule+ /// change.+ IndexBuilds,+ /// The entries of those indexes, summed.+ IndexedEntries,+ /// The selector entries those indexes, and the ones cold passes built, compiled: those of the+ /// programs no rule index build of the process compiled before.+ CompiledSelectors,+ /// The user agent indexes those indexes built, which no document of the process had built+ /// before: a document whose user agent rules decide as another's did shares its index.+ UserAgentIndexBuilds,+ /// The elements passes matched against the whole rule index, not only against the entries+ /// they were restyled for.+ MatchedElements,+ /// The walks of the argument of a `:has()` that passes took to answer it for an anchor.+ RelativeWalks,+}++impl StyleCounter {+ pub(in super::super) const COUNT: usize = Self::RelativeWalks as usize + 1;+}++/// What a pass counts until the state takes it, and what it styled.+#[derive(Clone, Default)]+pub(super) struct PassCounts {+ counts: [u64; StyleCounter::COUNT],+ last_pass: Option<LastPass>,+}++impl PassCounts {+ /// Note `value` of `field` of the live report, where it is one of the counters.+ pub(super) fn note(&mut self, field: LiveField, value: u64) {+ let counter = match field {+ LiveField::Passes => StyleCounter::Passes,+ LiveField::FullPasses => StyleCounter::FullPasses,+ LiveField::StyledElements => StyleCounter::StyledElements,+ LiveField::ChangedElements => StyleCounter::ChangedElements,+ LiveField::HintedElements => StyleCounter::HintedElements,+ LiveField::HintedSubtrees => StyleCounter::HintedSubtrees,+ LiveField::InvalidationVisits => StyleCounter::InvalidationVisits,+ LiveField::InvalidationTests => StyleCounter::InvalidationTests,+ _ => return,+ };+ self.counts[counter as usize] += value;+ }++ /// Note that the engine updated `index`, indexing `arrived` entries.+ pub(super) fn note_index_update(&mut self, index: &RuleIndex, arrived: usize) {+ self.counts[StyleCounter::IndexedEntries as usize] += arrived as u64;+ self.counts[StyleCounter::CompiledSelectors as usize] += index.compiled_selectors;+ self.counts[StyleCounter::UserAgentIndexBuilds as usize] += u64::from(index.built_user_agent_index);+ }++ /// Note that the engine built `index`.+ pub(super) fn note_index_build(&mut self, index: &RuleIndex) {+ self.counts[StyleCounter::IndexBuilds as usize] += 1;+ self.counts[StyleCounter::IndexedEntries as usize] += index.indexed_entries;+ self.counts[StyleCounter::CompiledSelectors as usize] += index.compiled_selectors;+ self.counts[StyleCounter::UserAgentIndexBuilds as usize] += u64::from(index.built_user_agent_index);+ }++ /// Note that a transaction took inputs, which the passes after it restyle: one that no pass+ /// follows styled nothing.+ pub(super) fn note_transaction(&mut self) {+ self.last_pass.get_or_insert_with(LastPass::default);+ }++ /// Note what a pass styled, everything where `full` is, and `changed`, the elements whose+ /// records, or pseudo-element records, are not the ones they held. A pass restyling what the+ /// one before it left waiting on fonts goes on with what that one styled.+ pub(super) fn note_pass(&mut self, full: bool, statistics: &Statistics, changed: &[StyleNodeID]) {+ self.counts[StyleCounter::SharedElements as usize] += statistics.outcomes.shared;+ self.counts[StyleCounter::ReusedElements as usize] += statistics.outcomes.reused;+ self.counts[StyleCounter::MatchedElements as usize] += statistics.outcomes.matched;+ self.counts[StyleCounter::RelativeWalks as usize] += statistics.match_counters.relative_walks;+ let last_pass = self.last_pass.get_or_insert_with(LastPass::default);+ last_pass.full |= full;+ last_pass.styled.extend_from_slice(&statistics.styled);+ last_pass.changed.extend_from_slice(changed);+ }+}++/// How many elements of a pass took the record of another, by how they found it.+#[derive(Clone, Copy, Default)]+pub(super) struct OutcomeCounts {+ /// The elements a pass reached.+ elements: u64,+ shared: u64,+ reused: u64,+ computed: u64,+ computed_directly: u64,+ /// The elements matched against the whole rule index.+ matched: u64,+}++impl OutcomeCounts {+ pub(super) fn note(&mut self, outcome: &Outcome) {+ self.elements += 1;+ match outcome {+ Outcome::Shared => self.shared += 1,+ Outcome::Reused => self.reused += 1,+ Outcome::Computed { directly } => {+ self.computed += 1;+ self.computed_directly += u64::from(*directly);+ }+ Outcome::CascadeDeclined | Outcome::ComputeDeclined => {}+ }+ }++ pub(super) fn elements(&self) -> u64 {+ self.elements+ }++ /// The elements the pass holds a record of.+ pub(super) fn styled(&self) -> u64 {+ self.shared + self.reused + self.computed+ }++ pub(super) fn shared(&self) -> u64 {+ self.shared+ }++ pub(super) fn reused(&self) -> u64 {+ self.reused+ }++ pub(super) fn computed_directly(&self) -> u64 {+ self.computed_directly+ }++ /// Note an element matched against the whole rule index.+ pub(super) fn note_matched(&mut self) {+ self.matched += 1;+ }++ pub(super) fn add(&mut self, other: &Self) {+ self.elements += other.elements;+ self.computed += other.computed;+ self.computed_directly += other.computed_directly;+ self.shared += other.shared;+ self.reused += other.reused;+ self.matched += other.matched;+ }+}++/// What the last pass of the engine styled, with the passes after it that restyled what it left+/// waiting on fonts.+#[derive(Clone, Default)]+struct LastPass {+ /// Whether it restyled every element.+ full: bool,+ /// The elements it styled.+ styled: Vec<StyleNodeID>,+ /// The elements it left holding records, or pseudo-element records, other than the ones they+ /// held before.+ changed: Vec<StyleNodeID>,+ /// Whether `styled` and `changed` are in tree order, without repeats or departed elements.+ in_tree_order: bool,+}++impl LastPass {+ /// Put the elements in the order a style traversal from `root` reaches them, leaving out the+ /// ones it does not reach any more.+ fn put_in_tree_order(&mut self, tree: &Projection, root: StyleNodeID) {+ if self.in_tree_order {+ return;+ }+ self.in_tree_order = true;+ if !tree.is_live(root) {+ self.styled.clear();+ self.changed.clear();+ return;+ }+ let order: std::collections::HashMap<StyleNodeID, usize> = tree+ .style_preorder(root)+ .enumerate()+ .map(|(position, node)| (node, position))+ .collect();+ for nodes in [&mut self.styled, &mut self.changed] {+ nodes.retain(|node| order.contains_key(node));+ nodes.sort_unstable_by_key(|node| order[node]);+ nodes.dedup();+ }+ }+}++/// What the engine did on a document's render state since the counters were last reset, what+/// its last pass styled, and how often the host composed animations over records.+#[derive(Clone, Default)]+pub(in super::super) struct Counters {+ counts: [u64; StyleCounter::COUNT],+ /// Shared with a fork until either side writes it: a fork restyles nothing until the host+ /// moves on under it.+ last_pass: crate::fork::ForkShared<LastPass>,+ /// The animation samples the host composed over the record an element installed, by whether+ /// composing them rebuilt every group of the record or only the ones they write. These are+ /// reset with the host's style invalidation counters, not with the others.+ animated_samples: [u64; 2],+}++impl Counters {+ /// Take what a pass counted, once it kept the records it computed.+ pub(super) fn take_pass(&mut self, pass: &mut PassCounts) {+ let PassCounts { counts, last_pass } = std::mem::take(pass);+ for (total, count) in self.counts.iter_mut().zip(counts) {+ *total += count;+ }+ if let Some(last_pass) = last_pass {+ self.last_pass.assign(last_pass);+ }+ }++ /// Note that the engine started from a cold pass, with `index`, the rule index it built.+ pub(super) fn note_live_start(&mut self, index: &RuleIndex) {+ self.counts[StyleCounter::ColdPasses as usize] += 1;+ self.counts[StyleCounter::IndexBuilds as usize] += 1;+ self.counts[StyleCounter::IndexedEntries as usize] += index.indexed_entries;+ self.counts[StyleCounter::CompiledSelectors as usize] += index.compiled_selectors;+ self.counts[StyleCounter::UserAgentIndexBuilds as usize] += u64::from(index.built_user_agent_index);+ }++ /// Note that a cold pass built `index`, which counts the selectors it compiled.+ pub(super) fn note_cold_pass_index(&mut self, index: &RuleIndex) {+ self.counts[StyleCounter::CompiledSelectors as usize] += index.compiled_selectors;+ }++ /// The counter of index `index` of [`StyleCounter`], or zero for none.+ pub(in super::super) fn get(&self, index: u32) -> u64 {+ self.counts.get(index as usize).copied().unwrap_or(0)+ }++ /// Zero the counters and forget the last pass.+ pub(in super::super) fn reset(&mut self) {+ self.counts = [0; StyleCounter::COUNT];+ self.last_pass.assign(LastPass::default());+ }++ /// Whether the last pass restyled every element.+ pub(in super::super) fn last_pass_is_full(&self) -> bool {+ self.last_pass.full+ }++ /// The elements the last pass styled, or the ones whose records it changed where `changed` is,+ /// in the order a style traversal from `root` reaches them.+ pub(in super::super) fn last_pass_elements(+ &mut self,+ tree: &Projection,+ root: StyleNodeID,+ changed: bool,+ ) -> &[StyleNodeID] {+ if !self.last_pass.in_tree_order {+ self.last_pass.put_in_tree_order(tree, root);+ }+ match changed {+ true => &self.last_pass.changed,+ false => &self.last_pass.styled,+ }+ }++ /// Note that the host composed an animation sample over the record an element installed,+ /// rebuilding every group of it where `rebuilt_every_group` is.+ pub(in super::super) fn note_animated_sample(&mut self, rebuilt_every_group: bool) {+ self.animated_samples[usize::from(rebuilt_every_group)] += 1;+ }++ /// How many animation samples the host composed, of those that rebuilt every group where+ /// `rebuilt_every_group` is, zeroing the count where `reset` is.+ pub(in super::super) fn animated_samples(&mut self, rebuilt_every_group: bool, reset: bool) -> u64 {+ let count = &mut self.animated_samples[usize::from(rebuilt_every_group)];+ let answer = *count;+ if reset {+ *count = 0;+ }+ answer+ }+}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/differential_tests.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/differential_tests.rsnew file mode 100644index 00000000000..cdb15242ff8--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/differential_tests.rs@@ -0,0 +1,1670 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! Seeded mutation batches over a generated document, each checked by restyling it with live style+//! the engine and comparing every record against a cold pass over the same document, and what that pass+//! matched against the reference matcher.++use super::super::bridge::element_adjustment_fact;+use super::super::*;+use super::counters::StyleCounter;+use super::test_support::{+ add_class, add_feature, add_rules, add_sheet, add_user_agent_sheet, allocate_nodes, assert_live_matches_cold, atom,+ attach_shadow_tree, describe, document_with_children, hosted_engine, linear_document, nested_document, relations,+ remove_class, remove_feature, run_style_update, set_atom_feature, set_tag, start_live, start_live_on,+};++// Cover hundreds of committed mutation batches while staying cheap enough for every Rust run.+const CONTAINERS: usize = 6;+const CHILDREN: usize = 8;+const CLASSES: usize = 8;+const RULES: usize = 16;+const SEEDS: u64 = 12;++/// How many seeds the seeded workloads run, which `LIBWEB_STYLE_FUZZ_SEEDS` raises for a long run.+fn seeds() -> u64 {+ std::env::var("LIBWEB_STYLE_FUZZ_SEEDS")+ .ok()+ .and_then(|seeds| seeds.parse().ok())+ .unwrap_or(SEEDS)+}+const STEPS: usize = 48;++struct Lcg(u64);++impl Lcg {+ fn next(&mut self) -> u64 {+ self.0 = self+ .0+ .wrapping_mul(6364136223846793005)+ .wrapping_add(1442695040888963407);+ self.0 >> 33+ }++ fn under(&mut self, bound: usize) -> usize {+ (self.next() % bound as u64) as usize+ }+}++fn class_name(index: usize) -> String {+ format!("class{index}")+}++fn tag_name(node: StyleNodeID) -> &'static str {+ ["div", "span", "p"][node.raw() as usize % 3]+}++/// The style rule of `index`: one of eight selector shapes over three of the classes.+fn rule_source(index: usize) -> String {+ let a = class_name(index % CLASSES);+ let b = class_name((index + 3) % CLASSES);+ let c = class_name((index + 5) % CLASSES);+ let selector = match index % 8 {+ 0 => format!(".{a}"),+ 1 => format!(".{a} .{b}"),+ 2 => format!(".{a} > .{b}"),+ 3 => format!(".{a} ~ .{b}"),+ 4 => format!(".{a} + .{b}"),+ 5 => format!(".{a} ~ .{b} .{c}"),+ 6 => format!(".{a} .{b} ~ .{c}"),+ _ => format!(".{a} + .{b} + .{c}"),+ };+ format!("{selector} {{ {}; }}", declaration_of(index))+}++/// The declaration of the rule of `index`: one of five properties, important for every seventh+/// rule.+fn declaration_of(index: usize) -> String {+ // NB: Inherited and font-relative properties make a match reach the matched element's+ // descendants and the other properties of the element.+ let declaration = match index % 5 {+ 0 => format!("color: rgb({}, 0, 0)", 16 * index),+ 1 => format!("width: {}px", 1 + index),+ 2 => format!("font-size: {}em", 1 + index % 3),+ 3 => format!("margin-left: {}em", 1 + index),+ _ => format!("padding-top: {}px", 1 + index),+ };+ let important = if index % 7 == 0 { " !important" } else { "" };+ format!("{declaration}{important}")+}++/// The style rule of `index` for the `:has()` workload: one of twelve shapes of `:has()` over+/// three of the classes, whose arguments go down, to a child, or sideways from the anchor, as a+/// subject or a non-subject compound, nested in `:is()` and `:not()`.+fn has_rule_source(index: usize) -> String {+ let a = class_name(index % CLASSES);+ let b = class_name((index + 3) % CLASSES);+ let c = class_name((index + 5) % CLASSES);+ let selector = match index % 12 {+ 0 => format!(".{a}:has(.{b})"),+ 1 => format!(".{a}:has(> .{b}) .{c}"),+ 2 => format!(".{a}:has(+ .{b})"),+ 3 => format!(".{a}:has(~ .{b}) > .{c}"),+ 4 => format!(":has(.{a} .{b}) .{c}"),+ 5 => format!(".{a}:has(+ .{b} .{c})"),+ 6 => format!(".{c}:not(:has(.{a} + .{b}))"),+ 7 => format!(".{a}:has(> .{b}:first-child)"),+ 8 => format!(":is(.{a}:has(~ .{b} > .{c}), .{c}:has(.{a})) ~ *"),+ 9 => format!(".{a}:has(.{b} ~ .{c}) > *"),+ 10 => format!(":has(> :not(.{a})) > .{b}"),+ _ => format!(".{a}:has(+ .{b} + .{c})"),+ };+ format!("{selector} {{ {}; }}", declaration_of(index))+}++/// The style rule of `index` for the nested selector workload: one of eight shapes nesting+/// combinators in `:not()` and `:is()`, as the subject compound or left of one.+fn nested_rule_source(index: usize) -> String {+ let a = class_name(index % CLASSES);+ let b = class_name((index + 3) % CLASSES);+ let c = class_name((index + 5) % CLASSES);+ let selector = match index % 8 {+ 0 => format!(":not(.{a} ~ *)"),+ 1 => format!(".{c}:not(.{a} + .{b})"),+ 2 => format!(":not(.{a} ~ .{b}) > .{c}"),+ 3 => format!(":is(.{a} + .{b}, .{c} ~ *)"),+ 4 => format!(".{a} ~ :not(.{b} + *)"),+ 5 => format!(":not(.{a} > *, .{b} ~ .{c})"),+ 6 => format!(".{c}:is(.{a} .{b} ~ *)"),+ _ => format!(":not(.{a} *) + .{b}"),+ };+ format!("{selector} {{ {}; }}", declaration_of(index))+}++/// The style rule of `index` for the workload of compounds no one fact is carried by every element+/// matching: left of a sibling combinator, as an element arriving or leaving reaches them, and of+/// positions, with and without `of S`.+fn keyless_rule_source(index: usize) -> String {+ let a = class_name(index % CLASSES);+ let b = class_name((index + 3) % CLASSES);+ let c = class_name((index + 5) % CLASSES);+ let selector = match index % 16 {+ 0 => format!(":not(.{a}) + .{b}"),+ 1 => format!(":not(.{a}) ~ .{b}"),+ 2 => format!(":not(.{a}) ~ :not(.{b})"),+ 3 => format!(":is(.{a}, *) + .{b}"),+ 4 => format!(":is(.{a}, :not(.{c})) ~ .{b}"),+ 5 => format!(":where(.{a}, :first-child) + .{b}"),+ 6 => format!(":empty + .{b}"),+ 7 => format!(":empty ~ .{b}"),+ 8 => format!(":not(.{a}) ~ .{b} .{c}"),+ 9 => format!(":not(.{a}):not(.{c}) + .{b}"),+ 10 => format!(":first-child + .{b}"),+ 11 => format!(".{a}:nth-child(2) ~ .{b}"),+ 12 => format!(".{a}:nth-child(2 of .{b})"),+ 13 => format!(":nth-last-child(1 of .{b}) .{c}"),+ 14 => format!(".{a}:only-child"),+ _ => format!(".{a}:first-of-type"),+ };+ format!("{selector} {{ {}; }}", declaration_of(index))+}++/// The style rule of `index` for the attribute workload: compounds testing an attribute of the name+/// `attribute_name` gives, as the subject and left of each combinator, in `:has()` and in `of S`.+fn attribute_rule_source(index: usize) -> String {+ let a = attribute_name(index % CLASSES);+ let b = class_name((index + 3) % CLASSES);+ let c = class_name((index + 5) % CLASSES);+ let selector = match index % 12 {+ 0 => format!("[{a}]"),+ 1 => format!("[{a}] + .{b}"),+ 2 => format!(":not([{a}]) ~ .{b}"),+ 3 => format!("[{a}] .{b}"),+ 4 => format!(".{b}[{a}] > .{c}"),+ 5 => format!(":has([{a}]) .{b}"),+ 6 => format!(".{b}:has(+ [{a}])"),+ 7 => format!(":is([{a}], .{b}) ~ .{c}"),+ 8 => format!("[{a}]:nth-child(2) ~ .{b}"),+ 9 => format!(":nth-child(1 of [{a}]) .{b}"),+ 10 => format!(".{b}:nth-last-child(1 of :not([{a}]))"),+ _ => format!(":where([{a}], :first-child) + .{b}"),+ };+ format!("{selector} {{ {}; }}", declaration_of(index))+}++fn attribute_name(index: usize) -> String {+ format!("data-attribute{index}")+}++struct Workload {+ engine: StyleEngine,+ nodes: Vec<StyleNodeID>,+ root: StyleNodeID,+ containers: Vec<StyleNodeID>,+ children: Vec<Vec<StyleNodeID>>,+ classes: Vec<Vec<usize>>,+ class_atoms: Vec<StyleAtomID>,+ attributes: Vec<Vec<usize>>,+ attribute_atoms: Vec<StyleAtomID>,+ rule_source: fn(usize) -> String,+ /// Each rule's sheet, which holds it alone.+ sheets: Vec<SheetID>,+ rules: Vec<RuleID>,+ rule_conditions: Vec<bool>,+ sheet_conditions: Vec<bool>,+ /// The two layers every third rule is in, in the order the document declares them.+ layers: [CascadeLayerID; 2],+}++impl Workload {+ fn new(seed: u64, rule_source: fn(usize) -> String) -> Self {+ Self::with_shape(seed, rule_source, CONTAINERS, CHILDREN)+ }++ /// A workload of `container_count` containers of `child_count` children each.+ fn with_shape(seed: u64, rule_source: fn(usize) -> String, container_count: usize, child_count: usize) -> Self {+ let mut engine = hosted_engine();+ let nodes = allocate_nodes(&mut engine, 1 + container_count + container_count * child_count);+ let root = nodes[0];+ let containers = nodes[1..1 + container_count].to_vec();+ let children: Vec<Vec<_>> = (0..container_count)+ .map(|container| {+ let first = 1 + container_count + container * child_count;+ nodes[first..first + child_count].to_vec()+ })+ .collect();++ engine.record_tree_delta(root, None, Some(relations(None, None, None)));+ for (index, &container) in containers.iter().enumerate() {+ engine.record_tree_delta(+ container,+ None,+ Some(relations(+ Some(root),+ index.checked_sub(1).map(|previous| containers[previous]),+ containers.get(index + 1).copied(),+ )),+ );+ }+ for (container, list) in children.iter().enumerate() {+ for (index, &child) in list.iter().enumerate() {+ engine.record_tree_delta(+ child,+ None,+ Some(relations(+ Some(containers[container]),+ index.checked_sub(1).map(|previous| list[previous]),+ list.get(index + 1).copied(),+ )),+ );+ }+ }+ engine.set_element_adjustment_facts(root, element_adjustment_fact::IS_DOCUMENT_ELEMENT);++ let class_atoms: Vec<_> = (0..CLASSES)+ .map(|class| atom(&mut engine, &class_name(class)))+ .collect();+ let mut rng = Lcg(seed);+ let mut classes = vec![Vec::new(); nodes.len()];+ for (index, &node) in nodes.iter().enumerate() {+ let tag = atom(&mut engine, tag_name(node));+ engine.record_input(+ InputKey::LocalFeature(node, LocalFeatureKey::TagName),+ InputValue::Feature(FeatureValue::Absent),+ InputValue::Feature(FeatureValue::Atom(tag)),+ );+ for _ in 0..rng.under(3) {+ let class = rng.under(CLASSES);+ if classes[index].contains(&class) {+ continue;+ }+ classes[index].push(class);+ engine.record_input(+ InputKey::LocalFeature(node, LocalFeatureKey::Class(class_atoms[class])),+ InputValue::Feature(FeatureValue::Absent),+ InputValue::Feature(FeatureValue::Present),+ );+ }+ }++ let attribute_atoms: Vec<_> = (0..CLASSES)+ .map(|name| atom(&mut engine, &attribute_name(name)))+ .collect();+ let attributes = vec![Vec::new(); nodes.len()];++ let layers = [0, 1].map(|layer| CascadeLayerID(atom(&mut engine, &format!("layer{layer}")).0));+ engine.set_layer_order(TreeScopeID::DOCUMENT, &layers);+ let mut sheets = Vec::new();+ let mut rules = Vec::new();+ for index in 0..RULES {+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ sheets.push(sheet);+ rules.extend(add_rules(&mut engine, sheet, &rule_source(index)));+ if index % 3 == 0 {+ engine.set_rule_layer(rules[index], layers[index % 2]);+ engine.set_rule_in_a_layer(rules[index]);+ }+ }++ Self {+ engine,+ nodes,+ root,+ containers,+ children,+ classes,+ class_atoms,+ attributes,+ attribute_atoms,+ rule_source,+ sheets,+ rules,+ rule_conditions: vec![true; RULES],+ sheet_conditions: vec![true; RULES],+ layers,+ }+ }++ fn node_relations(&self, node: StyleNodeID) -> TreeRelations {+ if node == self.root {+ return relations(None, None, None);+ }+ if let Some(index) = self.containers.iter().position(|&candidate| candidate == node) {+ return relations(+ Some(self.root),+ index.checked_sub(1).map(|previous| self.containers[previous]),+ self.containers.get(index + 1).copied(),+ );+ }+ self.children+ .iter()+ .enumerate()+ .find_map(|(container, children)| {+ let index = children.iter().position(|&candidate| candidate == node)?;+ Some(relations(+ Some(self.containers[container]),+ index.checked_sub(1).map(|previous| children[previous]),+ children.get(index + 1).copied(),+ ))+ })+ .expect("every workload node remains connected")+ }++ fn mutate(&mut self, rng: &mut Lcg) -> String {+ match rng.under(16) {+ 0..=5 => {+ let index = 1 + rng.under(self.nodes.len() - 1);+ let node = self.nodes[index];+ let class = rng.under(CLASSES);+ let (old, new) = if self.classes[index].contains(&class) {+ self.classes[index].retain(|&existing| existing != class);+ (FeatureValue::Present, FeatureValue::Absent)+ } else {+ self.classes[index].push(class);+ (FeatureValue::Absent, FeatureValue::Present)+ };+ self.engine.record_input(+ InputKey::LocalFeature(node, LocalFeatureKey::Class(self.class_atoms[class])),+ InputValue::Feature(old),+ InputValue::Feature(new),+ );+ format!("toggle {node:?} class{class}: {old:?} -> {new:?}")+ }+ 6..=7 => {+ let from = rng.under(self.containers.len());+ if self.children[from].is_empty() {+ return format!("skip empty container {from}");+ }+ let from_index = rng.under(self.children[from].len());+ let node = self.children[from][from_index];+ let old = self.node_relations(node);+ self.children[from].remove(from_index);+ let to = rng.under(self.containers.len());+ let to_index = rng.under(self.children[to].len() + 1);+ self.children[to].insert(to_index, node);+ let new = self.node_relations(node);+ if old == new {+ return format!("skip no-op move of {node:?}");+ }+ self.engine.record_tree_delta(node, Some(old), Some(new));+ format!("move {node:?}: {old:?} -> {new:?}")+ }+ 10 => {+ // A sheet moves before another, which changes the winner where their rules meet.+ let (index, before) = (rng.under(RULES), rng.under(RULES));+ if index == before {+ return format!("skip moving {:?} before itself", self.sheets[index]);+ }+ self.engine.detach_sheet(self.sheets[index], TreeScopeID::DOCUMENT);+ self.engine.attach_sheet_before_sheet(+ self.sheets[index],+ Some(self.sheets[before]),+ TreeScopeID::DOCUMENT,+ );+ format!("move {:?} before {:?}", self.sheets[index], self.sheets[before])+ }+ 11 => {+ // A rule is replaced by another of some shape and declaration.+ let (index, source) = (rng.under(RULES), rng.under(2 * RULES));+ self.engine.remove_style_rule(self.rules[index]);+ let source = (self.rule_source)(source);+ self.rules[index] = add_rules(&mut self.engine, self.sheets[index], &source)[0];+ self.rule_conditions[index] = true;+ format!("replace rule {index} with {:?}: {source}", self.rules[index])+ }+ 12 => {+ let index = rng.under(RULES);+ self.sheet_conditions[index] = !self.sheet_conditions[index];+ self.engine+ .set_sheet_conditions_hold(self.sheets[index], self.sheet_conditions[index]);+ format!(+ "set {:?} conditions_hold={}",+ self.sheets[index], self.sheet_conditions[index]+ )+ }+ 13 => {+ self.layers.reverse();+ self.engine.set_layer_order(TreeScopeID::DOCUMENT, &self.layers);+ format!("declare the layers in the order {:?}", self.layers)+ }+ 14..=15 => {+ let index = 1 + rng.under(self.nodes.len() - 1);+ let node = self.nodes[index];+ let attribute = rng.under(CLASSES);+ let key = LocalFeatureKey::Attribute(self.attribute_atoms[attribute]);+ if self.attributes[index].contains(&attribute) {+ self.attributes[index].retain(|&existing| existing != attribute);+ remove_feature(&mut self.engine, node, key);+ format!("remove {node:?} attribute {attribute}")+ } else {+ self.attributes[index].push(attribute);+ add_feature(&mut self.engine, node, key);+ format!("add {node:?} attribute {attribute}")+ }+ }+ _ => {+ let index = rng.under(self.rules.len());+ self.rule_conditions[index] = !self.rule_conditions[index];+ self.engine+ .set_rule_conditions_hold(self.rules[index], self.rule_conditions[index]);+ format!(+ "set {:?} conditions_hold={}",+ self.rules[index], self.rule_conditions[index]+ )+ }+ }+ }+}++/// The batches a seed applied, printed when a check of them fails.+struct History {+ seed: u64,+ lines: Vec<String>,+}++impl Drop for History {+ fn drop(&mut self) {+ if std::thread::panicking() {+ eprintln!(+ "seed={:#018x}\noperation history:\n{}",+ self.seed,+ self.lines.join("\n")+ );+ }+ }+}++fn run_seed(seed_index: u64, rule_source: fn(usize) -> String) {+ let seed = 0x5EED_5400_0000_0000_u64 | seed_index;+ let mut workload = Workload::new(seed, rule_source);+ let mut rng = Lcg(seed ^ 0xD1FF_E2E1_71A1_0001);+ let mut history = History {+ seed,+ lines: vec!["--- step 0".to_owned()],+ };+ start_live(&mut workload.engine, workload.root);+ assert_eq!(+ assert_live_matches_cold(&mut workload.engine, workload.root),+ workload.nodes.len()+ );++ for step in 1..=STEPS {+ history.lines.push(format!("--- step {step}"));+ for _ in 0..3 {+ history.lines.push(workload.mutate(&mut rng));+ }+ run_style_update(&mut workload.engine, workload.root);+ assert_eq!(+ assert_live_matches_cold(&mut workload.engine, workload.root),+ workload.nodes.len()+ );+ }+}++#[test]+fn seeded_transactions_restyle_live_as_a_cold_pass_does() {+ for seed_index in 0..seeds() {+ run_seed(seed_index, rule_source);+ }+}++#[test]+fn seeded_transactions_restyle_has_anchors_as_a_cold_pass_does() {+ for seed_index in 0..seeds() {+ run_seed(seed_index, has_rule_source);+ }+}++#[test]+fn seeded_transactions_restyle_compounds_testing_attributes_as_a_cold_pass_does() {+ for seed_index in 0..seeds() {+ run_seed(seed_index, attribute_rule_source);+ }+}++#[test]+fn seeded_transactions_restyle_nested_combinators_as_a_cold_pass_does() {+ for seed_index in 0..seeds() {+ run_seed(seed_index, nested_rule_source);+ }+}++// A document wide enough that each pass on several threads hands most of its elements to the pool.+const WIDE_CONTAINERS: usize = 8;+const WIDE_CHILDREN: usize = 24;+const THREAD_SEEDS: u64 = 4;+const THREAD_STEPS: usize = 16;+const OTHER_THREADS: u32 = 4;++/// Run a seed's batches over two copies of a wide workload, one restyled by the engine on one+/// thread and the other on several, and check after each batch that both hold the same records,+/// and that the one on several threads holds what cold passes compute on one thread and on+/// several, with every cache off and with them on.+fn run_seed_on_one_thread_and_on_several(seed_index: u64, rule_source: fn(usize) -> String) {+ let seed = 0x5EED_7400_0000_0000_u64 | seed_index;+ let mut workloads = [1, OTHER_THREADS].map(|threads| {+ let mut workload = Workload::with_shape(seed, rule_source, WIDE_CONTAINERS, WIDE_CHILDREN);+ start_live_on(&mut workload.engine, workload.root, threads);+ workload+ });+ let mut rngs = [0, 1].map(|_| Lcg(seed ^ 0xD1FF_E2E1_71A1_0001));+ let mut history = History {+ seed,+ lines: vec!["--- step 0".to_owned()],+ };+ for step in 0..=THREAD_STEPS {+ if step != 0 {+ history.lines.push(format!("--- step {step}"));+ for _ in 0..3 {+ let [one, several] = &mut workloads;+ let [one_rng, several_rng] = &mut rngs;+ let line = one.mutate(one_rng);+ assert_eq!(several.mutate(several_rng), line, "both workloads mutate alike");+ history.lines.push(line);+ }+ for workload in &mut workloads {+ run_style_update(&mut workload.engine, workload.root);+ }+ }+ for workload in &mut workloads {+ assert_eq!(+ assert_live_matches_cold(&mut workload.engine, workload.root),+ workload.nodes.len()+ );+ }+ let [one, several] = &workloads;+ let failures = several.engine.self_check_failures(several.root, Some(OTHER_THREADS));+ assert!(+ failures.is_empty(),+ "the engine on {OTHER_THREADS} threads is not what cold passes compute:\n{}",+ failures.join("\n")+ );+ let state = &several.engine.retained;+ fn records(workload: &Workload) -> &super::records::RetainedRecords {+ workload+ .engine+ .retained+ .live_style+ .as_ref()+ .expect("the engine is live")+ .records()+ }+ let (failures, compared) =+ super::self_check::differences(state, several.root, records(several), records(one), &|node| {+ describe(state, node)+ });+ assert_eq!(compared, several.nodes.len());+ assert!(+ failures.is_empty(),+ "the engine on {OTHER_THREADS} threads (live) holds other records than on one (cold):\n{}",+ failures.join("\n")+ );+ }+}++#[test]+fn seeded_transactions_restyle_alike_on_one_thread_and_on_several() {+ for seed_index in 0..THREAD_SEEDS {+ run_seed_on_one_thread_and_on_several(seed_index, rule_source);+ }+}++#[test]+fn seeded_transactions_restyle_has_anchors_alike_on_one_thread_and_on_several() {+ for seed_index in 0..THREAD_SEEDS {+ run_seed_on_one_thread_and_on_several(seed_index, has_rule_source);+ }+}++#[test]+fn seeded_transactions_restyle_compounds_with_no_key_as_a_cold_pass_does() {+ for seed_index in 0..seeds() {+ run_seed(seed_index, keyless_rule_source);+ }+}++#[test]+fn seeded_transactions_restyle_nested_combinators_alike_on_one_thread_and_on_several() {+ for seed_index in 0..THREAD_SEEDS {+ run_seed_on_one_thread_and_on_several(seed_index, nested_rule_source);+ }+}++#[test]+fn a_move_within_a_parent_after_a_matching_sibling_restyles_it_as_a_cold_pass_does() {+ let (mut engine, nodes) = linear_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, sheet, ".x ~ .y { width: 10px; }");+ add_class(&mut engine, nodes[1], "y");+ add_class(&mut engine, nodes[2], "x");+ start_live(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ engine.record_tree_delta(+ nodes[1],+ Some(relations(Some(nodes[0]), None, Some(nodes[2]))),+ Some(relations(Some(nodes[0]), Some(nodes[2]), Some(nodes[3]))),+ );+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+}++#[test]+fn a_move_within_a_parent_past_a_later_sibling_restyles_it_as_a_cold_pass_does() {+ let (mut engine, nodes) = linear_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, sheet, ".x ~ .y { width: 10px; }");+ add_class(&mut engine, nodes[1], "x");+ add_class(&mut engine, nodes[3], "y");+ start_live(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ engine.record_tree_delta(+ nodes[1],+ Some(relations(Some(nodes[0]), None, Some(nodes[2]))),+ Some(relations(Some(nodes[0]), Some(nodes[3]), None)),+ );+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+}++#[test]+fn matching_flags_the_parents_whose_children_selectors_read_siblings_positions_or_emptiness_of() {+ use super::projection::StructuralFlags;+ let cases = [+ (+ ".x + .y { width: 10px; }",+ StructuralFlags::CHILDREN_READ_PREVIOUS_SIBLING,+ ),+ (".x ~ .y { width: 10px; }", StructuralFlags::CHILDREN_READ_SIBLINGS),+ (+ ".y:nth-child(2n) { width: 10px; }",+ StructuralFlags::CHILDREN_READ_POSITIONS,+ ),+ ];+ for (rule, flag) in cases {+ for with_subject in [false, true] {+ let (mut engine, nodes) = linear_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, sheet, rule);+ add_class(&mut engine, nodes[1], "x");+ if with_subject {+ add_class(&mut engine, nodes[3], "y");+ }+ start_live(&mut engine, nodes[0]);+ let flags = engine.retained.projection.structural_flags(nodes[0]);+ assert_eq!(flags.contains(flag), with_subject, "{rule}");++ // An element leaving a parent whose children no selector read the siblings of restyles no sibling,+ // and one leaving where they did restyles those it reached.+ engine.record_tree_delta(+ nodes[2],+ Some(relations(Some(nodes[0]), Some(nodes[1]), Some(nodes[3]))),+ None,+ );+ engine.record_tree_delta(+ nodes[3],+ Some(relations(Some(nodes[0]), Some(nodes[2]), None)),+ Some(relations(Some(nodes[0]), Some(nodes[1]), None)),+ );+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ }+ }++ let (mut engine, nodes) = linear_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, sheet, ".x:empty { width: 10px; }");+ add_class(&mut engine, nodes[1], "x");+ start_live(&mut engine, nodes[0]);+ let projection = &engine.retained.projection;+ assert!(+ projection+ .structural_flags(nodes[1])+ .contains(StructuralFlags::READ_EMPTINESS)+ );+ assert!(+ !projection+ .structural_flags(nodes[2])+ .contains(StructuralFlags::READ_EMPTINESS)+ );+}++/// The elements the last pass styled, where it styled only some.+fn styled_by_a_targeted_pass(engine: &mut StyleEngine, root: StyleNodeID) -> Vec<StyleNodeID> {+ let retained = &mut engine.retained;+ let counters = &mut retained.live_counters;+ assert!(!counters.last_pass_is_full(), "the pass styled only some elements");+ counters.last_pass_elements(&retained.projection, root, false).to_vec()+}++#[test]+fn a_change_left_of_a_sibling_combinator_in_not_restyles_the_siblings_it_reaches() {+ for (selector, reached) in [(":not(.b ~ *)", 2..4), (":not(.b + *)", 2..3)] {+ let (mut engine, nodes) = linear_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, sheet, &format!("{selector} {{ color: green; }}"));+ start_live(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ for change in [add_class, remove_class] {+ change(&mut engine, nodes[1], "b");+ run_style_update(&mut engine, nodes[0]);+ let mut styled = styled_by_a_targeted_pass(&mut engine, nodes[0]);+ styled.sort();+ assert_eq!(styled, nodes[reached.clone()], "{selector}");+ assert_live_matches_cold(&mut engine, nodes[0]);+ }+ }+}++#[test]+fn a_change_in_a_has_argument_restyles_only_the_anchors_whose_answer_flips() {+ let (mut engine, nodes) = nested_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(+ &mut engine,+ sheet,+ ".anchor:has(.x) { width: 10px; } .anchor:has(> .x) > * { height: 10px; } .other:has(.y) { width: 5px; }",+ );+ add_class(&mut engine, nodes[1], "anchor");+ add_class(&mut engine, nodes[2], "anchor");+ start_live(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ // The `.x` arriving on the grandchild of the outer anchor flips both anchors for the first rule,+ // and the inner one, its parent, for the second, which reaches its child.+ add_class(&mut engine, nodes[3], "x");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert_eq!(styled_by_a_targeted_pass(&mut engine, nodes[0]), &nodes[1..]);++ // A fact no argument tests restyles nothing, and one only another query's argument tests+ // flips no anchor of it.+ add_class(&mut engine, nodes[3], "unrelated");+ add_class(&mut engine, nodes[3], "y");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert!(styled_by_a_targeted_pass(&mut engine, nodes[0]).is_empty());++ remove_class(&mut engine, nodes[3], "x");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert_eq!(styled_by_a_targeted_pass(&mut engine, nodes[0]), &nodes[1..]);+}++#[test]+fn an_element_arriving_or_leaving_restyles_has_anchors_as_a_cold_pass_does() {+ let (mut engine, nodes) = linear_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(+ &mut engine,+ sheet,+ concat!(+ ".anchor:has(> .x) { width: 10px; } .anchor:has(+ .x) { height: 10px; } ",+ ".anchor:has(~ .x) { margin-left: 10px; } :has(> :first-child.x) > * { padding-top: 1px; } ",+ ".anchor:has(+ *) { color: rgb(0, 0, 255); }",+ ),+ );+ add_class(&mut engine, nodes[0], "anchor");+ add_class(&mut engine, nodes[1], "anchor");+ add_class(&mut engine, nodes[2], "x");+ start_live(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ // `b` leaves from between `a` and `c`, and then a new `.x` arrives first.+ engine.record_tree_delta(+ nodes[2],+ Some(relations(Some(nodes[0]), Some(nodes[1]), Some(nodes[3]))),+ None,+ );+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ let arriving = allocate_nodes(&mut engine, 1)[0];+ engine.record_tree_delta(arriving, None, Some(relations(Some(nodes[0]), None, Some(nodes[1]))));+ set_tag(&mut engine, arriving, "div");+ add_class(&mut engine, arriving, "x");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ // A plain element arrives after `c`, and the first `.x` leaves.+ let later = allocate_nodes(&mut engine, 1)[0];+ engine.record_tree_delta(later, None, Some(relations(Some(nodes[0]), Some(nodes[3]), None)));+ set_tag(&mut engine, later, "div");+ engine.record_tree_delta(arriving, Some(relations(Some(nodes[0]), None, Some(nodes[1]))), None);+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+}++#[test]+fn an_element_moving_into_a_has_anchor_takes_its_subtree_along() {+ let (mut engine, nodes) = nested_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(+ &mut engine,+ sheet,+ ".anchor:has(.x) { width: 10px; } .anchor:has(.y .x) { height: 10px; }",+ );+ add_class(&mut engine, nodes[1], "anchor");+ add_class(&mut engine, nodes[2], "y");+ add_class(&mut engine, nodes[3], "x");+ start_live(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ // `b`, holding the `.x`, moves from under the anchor to beside it.+ engine.record_tree_delta(+ nodes[2],+ Some(relations(Some(nodes[1]), None, None)),+ Some(relations(Some(nodes[0]), Some(nodes[1]), None)),+ );+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ engine.record_tree_delta(+ nodes[2],+ Some(relations(Some(nodes[0]), Some(nodes[1]), None)),+ Some(relations(Some(nodes[1]), None, None)),+ );+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+}++#[test]+fn an_element_arriving_in_an_empty_witness_restyles_its_anchor() {+ let (mut engine, nodes) = nested_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, sheet, ".hollow:has(.box:empty) { width: 10px; }");+ add_class(&mut engine, nodes[1], "hollow");+ add_class(&mut engine, nodes[2], "box");+ engine.record_tree_delta(nodes[3], Some(relations(Some(nodes[2]), None, None)), None);+ start_live(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ let arriving = allocate_nodes(&mut engine, 1)[0];+ engine.record_tree_delta(arriving, None, Some(relations(Some(nodes[2]), None, None)));+ set_tag(&mut engine, arriving, "span");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert!(styled_by_a_targeted_pass(&mut engine, nodes[0]).contains(&nodes[1]));+}++#[test]+fn a_subtree_leaving_with_a_witness_restyles_what_its_anchor_reaches() {+ let (mut engine, nodes) = linear_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(+ &mut engine,+ sheet,+ ".anchor:has(.x) ~ * { width: 10px; } .anchor:has(> .x) + * { height: 10px; }",+ );+ let witness = allocate_nodes(&mut engine, 1)[0];+ engine.record_tree_delta(witness, None, Some(relations(Some(nodes[1]), None, None)));+ set_tag(&mut engine, witness, "div");+ add_class(&mut engine, witness, "x");+ add_class(&mut engine, nodes[1], "anchor");+ start_live(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ // The anchor leaves with its witness, which, as an element below the one leaving, names no+ // parent it left.+ engine.record_tree_delta(nodes[1], Some(relations(Some(nodes[0]), None, Some(nodes[2]))), None);+ engine.record_tree_delta(witness, Some(relations(None, None, None)), None);+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+}++#[test]+fn a_change_to_a_compound_nested_in_a_has_argument_restyles_the_anchors_it_reaches() {+ let (mut engine, nodes) = nested_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(+ &mut engine,+ sheet,+ concat!(+ ".anchor:has(> :is(.active > *)) { width: 10px; } ",+ ".anchor:has(:is(.outer .y)) { height: 10px; } ",+ ".anchor:has(:is(.p + .q)) { margin-left: 10px; }",+ ),+ );+ add_class(&mut engine, nodes[1], "anchor");+ add_class(&mut engine, nodes[2], "anchor");+ add_class(&mut engine, nodes[3], "y");+ add_class(&mut engine, nodes[3], "q");+ start_live(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ // The anchor itself, and an element above it, match the compounds nested in the arguments.+ add_class(&mut engine, nodes[2], "active");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ add_class(&mut engine, nodes[0], "outer");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ // A `.p` arriving before the `.q` makes the nested selector match it.+ let arriving = allocate_nodes(&mut engine, 1)[0];+ engine.record_tree_delta(arriving, None, Some(relations(Some(nodes[2]), None, Some(nodes[3]))));+ set_tag(&mut engine, arriving, "div");+ add_class(&mut engine, arriving, "p");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ remove_class(&mut engine, nodes[2], "active");+ remove_class(&mut engine, nodes[0], "outer");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+}++#[test]+fn a_dying_rule_entry_leaves_the_match_lists_not_naming_it_alone() {+ let (mut engine, nodes) = linear_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ let rules = add_rules(&mut engine, sheet, ".x { width: 10px; } .y { height: 10px; }");+ add_class(&mut engine, nodes[1], "x");+ add_class(&mut engine, nodes[2], "y");+ start_live(&mut engine, nodes[0]);+ let matches_of = |engine: &StyleEngine, node: StyleNodeID| {+ engine+ .retained+ .live_style+ .as_ref()+ .expect("the engine is live")+ .records()+ .matches_of(node)+ .cloned()+ };+ let kept = matches_of(&engine, nodes[2]).expect("the pass kept the matches");++ // The list of the element the dying entry did not match is the one it held, not a copy.+ engine.remove_style_rule(rules[0]);+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ let after = matches_of(&engine, nodes[2]).expect("the element keeps its matches");+ assert!(std::sync::Arc::ptr_eq(&kept, &after));+}++#[test]+fn a_rule_change_restyles_only_the_elements_its_rules_match_or_matched() {+ let (mut engine, nodes) = linear_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ let rules = add_rules(&mut engine, sheet, ".x { width: 10px; } .y ~ .z { height: 10px; }");+ add_class(&mut engine, nodes[1], "x");+ add_class(&mut engine, nodes[1], "y");+ add_class(&mut engine, nodes[3], "z");+ start_live(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ // A rule arriving restyles the element it matches, and one matching nothing nothing.+ let later = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(+ &mut engine,+ later,+ ".z { margin-left: 1px; } .nobody { color: rgb(1, 2, 3); }",+ );+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert_eq!(styled_by_a_targeted_pass(&mut engine, nodes[0]), [nodes[3]]);++ // A rule leaving restyles the elements it matched, as does a change to what it declares.+ engine.remove_style_rule(rules[0]);+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert_eq!(styled_by_a_targeted_pass(&mut engine, nodes[0]), [nodes[1]]);+ engine.set_rule_conditions_hold(rules[1], false);+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert_eq!(styled_by_a_targeted_pass(&mut engine, nodes[0]), [nodes[3]]);++ // An element gaining a class in the same transaction as a rule arriving for it is matched+ // against the rule with it.+ let third = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, third, ".w { padding-top: 2px; }");+ add_class(&mut engine, nodes[2], "w");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert_eq!(styled_by_a_targeted_pass(&mut engine, nodes[0]), [nodes[2]]);++ // A sheet whose rules match nothing arriving and leaving restyles nothing.+ let empty = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, empty, ".nobody { color: rgb(4, 5, 6); }");+ run_style_update(&mut engine, nodes[0]);+ assert!(styled_by_a_targeted_pass(&mut engine, nodes[0]).is_empty());+ engine.detach_sheet(empty, TreeScopeID::DOCUMENT);+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert!(styled_by_a_targeted_pass(&mut engine, nodes[0]).is_empty());+}++#[test]+fn a_cascade_order_change_restyles_only_the_elements_whose_rules_moved() {+ let (mut engine, nodes) = linear_document();+ let layers = ["base", "theme"].map(|name| CascadeLayerID(atom(&mut engine, name).0));+ engine.set_layer_order(TreeScopeID::DOCUMENT, &layers);+ let first = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ let base = add_rules(&mut engine, first, ".x { width: 1px; } .unmoved { height: 1px; }");+ let second = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ let theme = add_rules(&mut engine, second, ".x { width: 2px; }");+ let third = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, third, ".y { width: 3px; }");+ for (rule, layer) in [(base[0], layers[0]), (base[1], layers[0]), (theme[0], layers[1])] {+ engine.set_rule_layer(rule, layer);+ engine.set_rule_in_a_layer(rule);+ }+ add_class(&mut engine, nodes[1], "x");+ add_class(&mut engine, nodes[2], "unmoved");+ add_class(&mut engine, nodes[3], "y");+ start_live(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ // Reversing the layers moves one of the two rules for `.x` against the other, and the+ // unlayered rule for `.y` against neither.+ engine.set_layer_order(TreeScopeID::DOCUMENT, &[layers[1], layers[0]]);+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ let styled = styled_by_a_targeted_pass(&mut engine, nodes[0]);+ assert!(styled.contains(&nodes[1]) && !styled.contains(&nodes[3]), "{styled:?}");++ // Moving the last sheet to the front moves no rule against another it meets.+ engine.detach_sheet(third, TreeScopeID::DOCUMENT);+ engine.attach_sheet_before_sheet(third, Some(first), TreeScopeID::DOCUMENT);+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ let styled = styled_by_a_targeted_pass(&mut engine, nodes[0]);+ assert!(!styled.contains(&nodes[1]) && !styled.contains(&nodes[2]), "{styled:?}");++ // Moving the theme sheet before the base one in the same layer order changes nothing either,+ // as layers decide before sheets do.+ engine.detach_sheet(second, TreeScopeID::DOCUMENT);+ engine.attach_sheet_before_sheet(second, Some(first), TreeScopeID::DOCUMENT);+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert!(styled_by_a_targeted_pass(&mut engine, nodes[0]).is_empty());++ // Taking the rules out of their layers makes sheet order decide.+ for rule in [base[0], base[1], theme[0]] {+ engine.set_rule_layer(rule, CascadeLayerID::UNLAYERED);+ }+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+}++#[test]+fn elements_declaring_one_viewport_relative_value_all_depend_on_the_viewport() {+ // root -> [a, b, c], all declaring one viewport-relative width, which each absolutizes, as+ // their colors make their winners differ.+ let (mut engine, nodes) = document_with_children(3);+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(+ &mut engine,+ sheet,+ ".sized { width: 10vw; } .green { color: rgb(0, 128, 0); } .blue { color: rgb(0, 0, 255); }",+ );+ for (&node, class) in nodes[1..].iter().zip(["sized", "green", "blue"]) {+ add_class(&mut engine, node, "sized");+ add_class(&mut engine, node, class);+ }+ start_live(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+}++#[test]+fn list_items_of_tree_scopes_with_their_own_counter_styles_name_their_own_registry() {+ // root -> [a -> item, b], with b hosting a shadow tree whose style scope has its own registry,+ // holding an item too. Both scopes adopt one sheet, so the items of both have the same winners+ // under alike parents, and so do their markers, but each names the registry of its own scope.+ let (mut engine, nodes) = document_with_children(3);+ let item = allocate_nodes(&mut engine, 1)[0];+ engine.record_tree_delta(item, None, Some(relations(Some(nodes[1]), None, None)));+ set_tag(&mut engine, item, "div");+ let scope = TreeScopeID(1);+ let shadow = attach_shadow_tree(&mut engine, nodes[2], scope, 1);+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(+ &mut engine,+ sheet,+ ".item { display: list-item; list-style-type: lower-roman; } .item::marker { color: rgb(0, 0, 255); }",+ );+ engine.attach_sheet_before_sheet(sheet, None, scope);+ add_class(&mut engine, item, "item");+ add_class(&mut engine, shadow[1], "item");+ engine+ .retained+ .set_counter_style_environment_identity(TreeScopeID::DOCUMENT, 1);+ engine.retained.set_counter_style_environment_identity(scope, 2);+ start_live(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+}++#[test]+fn a_new_counter_style_registry_restyles_the_elements_naming_the_old_one() {+ // root -> [a -> [item, plain], b], with b hosting a shadow tree whose style scope has its own+ // registry, holding an item too. The items' own styles name a counter style the scope's+ // registry decides; of the plain list items, whose decimal no registry overrides, only the+ // markers do.+ let (mut engine, nodes) = document_with_children(3);+ let children = allocate_nodes(&mut engine, 2);+ engine.record_tree_delta(children[0], None, Some(relations(Some(nodes[1]), None, None)));+ engine.record_tree_delta(+ children[1],+ None,+ Some(relations(Some(nodes[1]), Some(children[0]), None)),+ );+ for &child in &children {+ set_tag(&mut engine, child, "div");+ }+ let scope = TreeScopeID(1);+ let shadow = attach_shadow_tree(&mut engine, nodes[2], scope, 2);+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(+ &mut engine,+ sheet,+ ".item { display: list-item; list-style-type: lower-roman; } .plain { display: list-item; list-style-type: decimal; }",+ );+ engine.attach_sheet_before_sheet(sheet, None, scope);+ add_class(&mut engine, children[0], "item");+ add_class(&mut engine, children[1], "plain");+ add_class(&mut engine, shadow[1], "item");+ add_class(&mut engine, shadow[2], "plain");+ engine+ .retained+ .set_counter_style_environment_identity(TreeScopeID::DOCUMENT, 1);+ engine.retained.set_counter_style_environment_identity(scope, 2);+ start_live(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ // The host minting a registry for a scope is no input of the elements reading it.+ engine.retained.set_counter_style_environment_identity(scope, 3);+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ engine+ .retained+ .set_counter_style_environment_identity(TreeScopeID::DOCUMENT, 4);+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+}++#[test]+fn highlight_pseudo_elements_are_styled_where_the_host_shows_the_highlight() {+ use super::super::publication::pseudo_kind::SELECTION;+ let holds_selection = |engine: &StyleEngine, node: StyleNodeID| {+ let live = engine.retained.live_style.as_ref().expect("the engine is live");+ live.records()+ .pseudo_element_records(node)+ .iter()+ .any(|(kind, _)| *kind == SELECTION)+ };+ let (mut engine, nodes) = linear_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, sheet, ".moved { width: 1px; }");+ start_live(&mut engine, nodes[0]);++ // A highlight rule arriving while no element shows the highlight reaches the matches the+ // elements keep, which their highlight pseudo-elements cascade once they show it.+ add_rules(&mut engine, sheet, "*::selection { color: rgb(1, 2, 3); }");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert!(!holds_selection(&engine, nodes[1]));++ // Only the elements the host shows the highlight in style it, whatever else a pass restyles.+ engine.set_highlight_observing_elements(SELECTION, &[nodes[0], nodes[1]]);+ add_class(&mut engine, nodes[2], "moved");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert!(holds_selection(&engine, nodes[1]) && !holds_selection(&engine, nodes[2]));++ // A highlight rule changing restyles the highlight pseudo-elements of the elements showing it.+ let rules = add_rules(&mut engine, sheet, "div::selection { color: rgb(4, 5, 6); }");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ engine.remove_style_rule(rules[0]);+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ engine.set_highlight_observing_elements(SELECTION, &[nodes[0], nodes[2]]);+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert!(!holds_selection(&engine, nodes[1]) && holds_selection(&engine, nodes[2]));++ engine.set_highlight_observing_elements(SELECTION, &[]);+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert!(nodes.iter().all(|&node| !holds_selection(&engine, node)));+}++#[test]+fn a_shadow_tree_rule_change_restyles_only_what_its_rules_reach() {+ let (mut engine, nodes) = linear_document();+ let scope = TreeScopeID(1);+ let shadow = attach_shadow_tree(&mut engine, nodes[1], scope, 2);+ add_class(&mut engine, nodes[2], "item");+ add_class(&mut engine, shadow[2], "item");+ start_live(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ // The shadow tree's rules reach its own elements and its host, and no element of the document+ // that would match them there.+ let sheet = add_sheet(&mut engine, scope);+ let rules = add_rules(&mut engine, sheet, ".item { width: 1px; } :host { height: 1px; }");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert_eq!(styled_by_a_targeted_pass(&mut engine, nodes[0]), [nodes[1], shadow[2]]);++ // NB: A host whose matches lost an entry holds none, and the elements of its shadow tree+ // standing for its pseudo-elements are restyled with it.+ engine.remove_style_rule(rules[1]);+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ let styled = styled_by_a_targeted_pass(&mut engine, nodes[0]);+ assert!(styled.contains(&nodes[1]) && !styled.contains(&nodes[2]), "{styled:?}");++ engine.detach_sheet(sheet, scope);+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert_eq!(styled_by_a_targeted_pass(&mut engine, nodes[0]), [shadow[2]]);+}++#[test]+fn a_keyframes_rule_restyles_no_element() {+ let (mut engine, nodes) = linear_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, sheet, ".x { width: 1px; }");+ add_class(&mut engine, nodes[1], "x");+ start_live(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ let name = atom(&mut engine, "slide");+ let keyframes = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ engine.add_keyframes_rule(keyframes, None, name);+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert!(styled_by_a_targeted_pass(&mut engine, nodes[0]).is_empty());+}++#[test]+fn sibling_positions_measured_before_a_move_are_measured_again_after_it() {+ let (mut engine, nodes) = linear_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, sheet, ".x:nth-child(2n) ~ * { width: 10px; }");+ start_live(&mut engine, nodes[0]);++ // The first child is measured where it stands, first, for each change to its classes.+ for change in [add_class, remove_class] {+ change(&mut engine, nodes[1], "x");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ }++ engine.record_tree_delta(+ nodes[1],+ Some(relations(Some(nodes[0]), None, Some(nodes[2]))),+ Some(relations(Some(nodes[0]), Some(nodes[2]), Some(nodes[3]))),+ );+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ // It is second now, which gives its later sibling the width.+ add_class(&mut engine, nodes[1], "x");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+}++#[test]+fn an_input_no_rule_tests_restyles_nothing_and_one_a_rule_tests_restyles() {+ let (mut engine, nodes) = linear_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(+ &mut engine,+ sheet,+ "#named { width: 1px; } :has(> .inner) { width: 2px; }",+ );+ start_live(&mut engine, nodes[0]);+ let named = atom(&mut engine, "named");+ let unnamed = atom(&mut engine, "unnamed");+ let styled = |engine: &mut StyleEngine, node| styled_by_a_targeted_pass(engine, nodes[0]).contains(&node);++ set_atom_feature(&mut engine, nodes[1], LocalFeatureKey::Id, unnamed);+ add_class(&mut engine, nodes[2], "unnamed");+ run_style_update(&mut engine, nodes[0]);+ assert!(styled_by_a_targeted_pass(&mut engine, nodes[0]).is_empty());+ assert_live_matches_cold(&mut engine, nodes[0]);++ // An id is tested as the value it had and the value it has.+ engine.record_input(+ InputKey::LocalFeature(nodes[1], LocalFeatureKey::Id),+ InputValue::Feature(FeatureValue::Atom(unnamed)),+ InputValue::Feature(FeatureValue::Atom(named)),+ );+ run_style_update(&mut engine, nodes[0]);+ assert!(styled(&mut engine, nodes[1]));+ assert_live_matches_cold(&mut engine, nodes[0]);++ // A class only a `:has()` argument tests restyles the anchor.+ add_class(&mut engine, nodes[2], "inner");+ run_style_update(&mut engine, nodes[0]);+ assert!(styled(&mut engine, nodes[0]));+ assert_live_matches_cold(&mut engine, nodes[0]);+}++#[test]+fn only_a_transaction_that_hints_an_element_runs_a_pass() {+ let (mut engine, nodes) = linear_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, sheet, ".x { width: 1px; }");+ start_live(&mut engine, nodes[0]);+ let counter = |engine: &StyleEngine, counter: StyleCounter| engine.retained.live_counters.get(counter as u32);+ let passes = counter(&engine, StyleCounter::Passes);++ for change in [add_class, remove_class] {+ change(&mut engine, nodes[1], "unnamed");+ run_style_update(&mut engine, nodes[0]);+ assert_eq!(counter(&engine, StyleCounter::Passes), passes);+ assert!(styled_by_a_targeted_pass(&mut engine, nodes[0]).is_empty());+ assert_live_matches_cold(&mut engine, nodes[0]);+ }++ run_style_update(&mut engine, nodes[0]);+ assert_eq!(counter(&engine, StyleCounter::Passes), passes);++ add_class(&mut engine, nodes[1], "x");+ run_style_update(&mut engine, nodes[0]);+ assert_eq!(counter(&engine, StyleCounter::Passes), passes + 1);+ assert_eq!(styled_by_a_targeted_pass(&mut engine, nodes[0]), &nodes[1..2]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ // A rule no element matches is indexed alone, without building the rule index again, and+ // restyles nothing.+ let index_builds = counter(&engine, StyleCounter::IndexBuilds);+ let indexed_entries = counter(&engine, StyleCounter::IndexedEntries);+ add_rules(&mut engine, sheet, ".y { width: 2px; }");+ run_style_update(&mut engine, nodes[0]);+ assert_eq!(counter(&engine, StyleCounter::Passes), passes + 1);+ assert_eq!(counter(&engine, StyleCounter::IndexBuilds), index_builds);+ assert_eq!(counter(&engine, StyleCounter::IndexedEntries), indexed_entries + 1);+ assert_live_matches_cold(&mut engine, nodes[0]);+}++#[test]+fn a_user_agent_sheet_arriving_shares_another_user_agent_index_without_building_the_rule_index() {+ let (mut engine, nodes) = linear_document();+ add_user_agent_sheet(&mut engine, "div { width: 1px; } .x { height: 1px; }");+ let author = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, author, ".y { width: 2px; }");+ add_class(&mut engine, nodes[1], "x");+ add_class(&mut engine, nodes[2], "z");+ add_class(&mut engine, nodes[3], "y");+ start_live(&mut engine, nodes[0]);+ let counter = |engine: &StyleEngine, counter: StyleCounter| engine.retained.live_counters.get(counter as u32);+ let index_builds = counter(&engine, StyleCounter::IndexBuilds);+ let user_agent_index_builds = counter(&engine, StyleCounter::UserAgentIndexBuilds);++ // A user agent sheet arriving, as the first SVG element of a document brings one, has the+ // document decide with the user agent index of all its user agent sheets, whose rules the+ // first one has keep their numbers: only the element the arriving rule matches is restyled.+ add_user_agent_sheet(&mut engine, ".z { height: 3px; }");+ run_style_update(&mut engine, nodes[0]);+ assert_eq!(counter(&engine, StyleCounter::IndexBuilds), index_builds);+ assert_eq!(+ counter(&engine, StyleCounter::UserAgentIndexBuilds),+ user_agent_index_builds + 1+ );+ assert_live_matches_cold(&mut engine, nodes[0]);++ // An author rule arriving after it is numbered where the document's own entries are.+ add_rules(&mut engine, author, ".x { width: 4px; }");+ run_style_update(&mut engine, nodes[0]);+ assert_eq!(counter(&engine, StyleCounter::IndexBuilds), index_builds);+ assert_live_matches_cold(&mut engine, nodes[0]);+}++#[test]+fn a_document_whose_media_leave_a_user_agent_rule_out_decides_without_it() {+ let (mut engine, nodes) = linear_document();+ let (_, rules) = add_user_agent_sheet(&mut engine, ".x { width: 1px; } .y { height: 1px; }");+ add_class(&mut engine, nodes[1], "x");+ add_class(&mut engine, nodes[2], "y");+ start_live(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ // The rule's conditions stop holding in this document alone, and hold again.+ for holds in [false, true] {+ engine.set_rule_conditions_hold(rules[0], holds);+ run_style_update(&mut engine, nodes[0]);+ assert_eq!(engine.rules.rule_can_decide(rules[0]), holds);+ assert!(engine.rules.rule_can_decide(rules[1]));+ assert_live_matches_cold(&mut engine, nodes[0]);+ }+}++#[test]+fn a_document_finds_the_user_agent_index_the_process_built_ahead() {+ use super::rules::RuleIndex;+ use std::sync::Arc;+ // NB: The process's atoms are the ones the selectors name.+ let process = Arc::new(ProcessStyle::with_atoms(Arc::clone(+ crate::render_state::process_style().atoms(),+ )));+ let source = 1;+ process.publish_user_agent_sheet(source, |engine, sheet| {+ add_rules(engine, sheet, ".x { width: 1px; }");+ });+ process+ .index_user_agent_sheet_ahead(source, &[])+ .expect("the sheet is published")+ .join()+ .expect("the index builds");+ let (mut engine, _) = linear_document();+ engine.share_process_style(Arc::clone(&process));+ let sheet = engine.add_user_agent_sheet(source);+ engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);+ engine.commit_staged_program();+ let index = RuleIndex::build(&engine.rules, Some(&process.rule_indexes));+ assert!(index.user_agent_index().is_some());+ assert!(!index.built_user_agent_index);+}++#[test]+fn documents_read_the_user_agent_rules_the_process_keeps() {+ use std::sync::Arc;+ // NB: The process's atoms are the ones the selectors name.+ let process = Arc::new(ProcessStyle::with_atoms(Arc::clone(+ crate::render_state::process_style().atoms(),+ )));+ let mut declarations: Vec<Vec<_>> = Vec::new();+ for _ in 0..2 {+ let (mut engine, nodes) = linear_document();+ engine.share_process_style(Arc::clone(&process));+ let (_, published) = add_user_agent_sheet(+ &mut engine,+ "div { width: 1px; display: block; } .x { height: 1px; display: block; }",+ );+ let author = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, author, ".y { width: 2px; display: block; }");+ add_class(&mut engine, nodes[1], "x");+ add_class(&mut engine, nodes[2], "y");+ start_live(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ // The document's own rules are its author sheet's alone.+ assert_eq!(engine.rules.rule_count(), 1);+ assert_eq!(published.len(), 2);+ declarations.push(+ published+ .iter()+ .map(|&rule| engine.rules.written_values_of(rule).as_ptr())+ .collect::<Vec<_>>(),+ );+ }+ // Both documents read the declarations of the same blocks.+ assert_eq!(declarations[0], declarations[1]);+}++#[test]+fn rules_leaving_take_their_selectors_out_of_the_invalidation_map_in_place() {+ use super::invalidation::{InvalidationMap, Trigger};+ let (mut engine, nodes) = nested_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ let rules = add_rules(+ &mut engine,+ sheet,+ ".x .y { width: 1px; } .z { height: 1px; } :nth-child(1 of .w) { width: 2px; } \+ .v:has(.u) { width: 3px; } .y ~ .t { width: 4px; } .x { height: 2px; }",+ );+ add_class(&mut engine, nodes[3], "y");+ start_live(&mut engine, nodes[0]);+ let counter = |engine: &StyleEngine, counter: StyleCounter| engine.retained.live_counters.get(counter as u32);+ let index_builds = counter(&engine, StyleCounter::IndexBuilds);++ // Every rule testing `.w`, `.u` or `.t`, and the one testing `.y` below `.x`, leaves.+ for rule in [rules[0], rules[2], rules[3], rules[4]] {+ engine.remove_style_rule(rule);+ }+ run_style_update(&mut engine, nodes[0]);+ assert_eq!(counter(&engine, StyleCounter::IndexBuilds), index_builds);+ assert_live_matches_cold(&mut engine, nodes[0]);++ // The map the rules left is the one built from the rules that stayed.+ let triggers: Vec<Trigger> = ["x", "y", "z", "w", "v", "u", "t"]+ .into_iter()+ .map(|name| Trigger::Class(atom(&mut engine, name)))+ .collect();+ let live = engine+ .retained+ .live_style+ .as_deref()+ .expect("the engine owns the document");+ let map = live.current_invalidation().expect("the map describes the rules");+ let built = InvalidationMap::build(live.index());+ for trigger in &triggers {+ assert_eq!(map.tests(trigger), built.tests(trigger));+ }+ assert!(!map.has_relative_arguments());++ // A change to a class only a rule that left tested restyles nothing.+ let hinted = counter(&engine, StyleCounter::HintedElements);+ for name in ["w", "u", "t"] {+ add_class(&mut engine, nodes[2], name);+ run_style_update(&mut engine, nodes[0]);+ }+ assert_eq!(counter(&engine, StyleCounter::HintedElements), hinted);+ assert_live_matches_cold(&mut engine, nodes[0]);+}++#[test]+fn a_pass_styles_nested_restyled_elements_once_from_the_topmost() {+ let (mut engine, nodes) = nested_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, sheet, ".x { width: 1px; } .y .z { width: 2px; }");+ add_class(&mut engine, nodes[3], "z");+ start_live(&mut engine, nodes[0]);+ let counter = |engine: &StyleEngine, counter: StyleCounter| engine.retained.live_counters.get(counter as u32);++ // Each element restyled below the next, then each above the next: the ones below go with+ // the topmost, and each one is styled once.+ for (change, order) in [+ (add_class as fn(&mut StyleEngine, StyleNodeID, &str), [3, 2, 1]),+ (remove_class, [1, 2, 3]),+ ] {+ for index in order {+ change(&mut engine, nodes[index], "x");+ }+ let styled_before = counter(&engine, StyleCounter::StyledElements);+ run_style_update(&mut engine, nodes[0]);+ assert_eq!(styled_by_a_targeted_pass(&mut engine, nodes[0]), &nodes[1..4]);+ assert_eq!(counter(&engine, StyleCounter::StyledElements), styled_before + 3);+ assert_live_matches_cold(&mut engine, nodes[0]);+ }++ // An element restyled below one whose descendants restyle, with one between them that is not.+ add_class(&mut engine, nodes[3], "x");+ add_class(&mut engine, nodes[1], "y");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ remove_class(&mut engine, nodes[1], "y");+ remove_class(&mut engine, nodes[3], "x");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+}++#[test]+fn invalidation_after_a_wide_transaction_measures_positions_anew() {+ // More children than the invalidation keeps room for between transactions.+ let (mut engine, nodes) = document_with_children(1201);+ let (root, children) = (nodes[0], &nodes[1..]);+ for &child in children.iter().skip(1).step_by(2) {+ set_tag(&mut engine, child, "span");+ }+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(+ &mut engine,+ sheet,+ ".x:nth-of-type(3n) { width: 10px; } .x:nth-last-child(2n) { height: 10px; } .y + .x { color: rgb(0, 128, 0); }",+ );+ start_live(&mut engine, root);++ for &child in children {+ add_class(&mut engine, child, "x");+ }+ run_style_update(&mut engine, root);+ assert_live_matches_cold(&mut engine, root);++ // The first child leaves, which moves every later sibling, among all of them and among+ // those of its type.+ engine.record_tree_delta(children[0], Some(relations(Some(root), None, Some(children[1]))), None);+ run_style_update(&mut engine, root);+ assert_live_matches_cold(&mut engine, root);++ // A `span` arrives between two of them, and one of them gains a class.+ let arriving = allocate_nodes(&mut engine, 1)[0];+ engine.record_tree_delta(+ arriving,+ None,+ Some(relations(Some(root), Some(children[4]), Some(children[5]))),+ );+ set_tag(&mut engine, arriving, "span");+ add_class(&mut engine, children[7], "y");+ run_style_update(&mut engine, root);+ assert_live_matches_cold(&mut engine, root);++ for &child in &children[1..] {+ remove_class(&mut engine, child, "x");+ }+ run_style_update(&mut engine, root);+ assert_live_matches_cold(&mut engine, root);+}++#[test]+fn a_pass_restyling_what_waited_reads_containers_an_earlier_pass_computed() {+ let (mut engine, nodes) = nested_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(+ &mut engine,+ sheet,+ ".c { container-type: inline-size; } .w { width: calc(10cqw + random(1px, 2px)); }",+ );+ start_live(&mut engine, nodes[0]);++ // The element becomes a container in the pass that finds its child waiting on a random base+ // value, and the pass after it restyles only the child, before the host installs either.+ add_class(&mut engine, nodes[1], "c");+ add_class(&mut engine, nodes[2], "w");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+}++#[test]+fn an_inherited_text_fill_color_reaches_an_element_with_a_color_of_its_own() {+ use crate::css::computed_value_views::ComputedValuesView;++ let (mut engine, nodes) = nested_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(+ &mut engine,+ sheet,+ ".parent { color: rgb(16, 30, 30); } .on .parent { -webkit-text-fill-color: transparent; } .own { color: rgb(111, 119, 134); }",+ );+ add_class(&mut engine, nodes[1], "parent");+ add_class(&mut engine, nodes[2], "own");+ start_live(&mut engine, nodes[0]);+ add_class(&mut engine, nodes[0], "on");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ for &node in &nodes[1..] {+ let record = super::test_support::live_record(&engine, node);+ let text = ComputedValuesView::of(&record.payloads).inherited_text();+ assert_eq!(text.webkit_text_fill_color, 0);+ assert!(!text.webkit_text_fill_color_is_current_color);+ }+}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/fork_tests.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/fork_tests.rsnew file mode 100644index 00000000000..e878497a9a3--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/fork_tests.rs@@ -0,0 +1,139 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What a fork of a styled document's engine allocates. The render clock and the hover lane fork+//! the engine whenever the host moves on under them, so a fork is made per frame while the host is+//! busy: it should copy chunk pointers and reference counts, not tables, and so allocate no more+//! for a document twice as large.++use super::super::*;+use super::allocation_count::count_live_bytes;+use super::test_support::*;+use crate::css::computed_value_types::FontValues;+use crate::css::computed_values::{BoxValues, StyleGroups};+use crate::css::table_group_builder::group_index;++/// How many elements the smaller of the two documents a test forks holds.+const ELEMENTS: usize = 256;++/// Builds a document element with `count - 1` children, owned by the engine, as a document's+/// host leaves it after its first frame: one query container late in tree order, every eighth+/// element with replaced content, and the damage of moving every element between two records+/// compared once.+fn styled_document(count: usize) -> StyleEngine {+ let (mut engine, nodes) = document_with_children(count);+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(+ &mut engine,+ sheet,+ ".c { container-type: inline-size; } .q { color: rgb(0, 128, 0); }",+ );+ for (index, &node) in nodes.iter().enumerate().skip(1) {+ add_class(&mut engine, node, "q");+ if index % 8 == 0 {+ engine.set_element_replaced_content_input(+ node,+ inputs::ReplacedContentInput::Input {+ size: 20,+ is_text_entry: true,+ },+ );+ }+ }+ let container = *nodes.last().unwrap();+ add_class(&mut engine, container, "c");+ start_live(&mut engine, nodes[0]);+ hold_container_record(&mut engine, container);+ // NB: Comparing records reads their font cascade lists, which the default font group holds+ // none of. The test stubs compare lists by address.+ let font_cascade_list: *const std::ffi::c_void = (&raw const *Box::leak(Box::new(0_u8))).cast();+ let mut payloads = engine.default_groups().groups().clone();+ // SAFETY: The font group holds a `FontValues`.+ unsafe {+ payloads.write_group::<FontValues>(group_index::FONT, |font| {+ font.font_cascade_list = libgfx_rust::font::FontCascadeListHandle::retain(font_cascade_list);+ });+ }+ // NB: Records of equal content are one, so each element moves between records of its own.+ for (index, &node) in nodes.iter().enumerate() {+ let opacity = index as f64 / 1024.0;+ let old = install_record(&mut engine, node, &payloads, opacity);+ let new = install_record(&mut engine, node, &payloads, 1.0 - opacity);+ engine.element_record_damage(node, false, old, new);+ }+ engine+}++/// Installs a record of `payloads` for `node` over a longhand table holding `opacity` and the+/// initial value of every other longhand, answering its identity.+fn install_record(engine: &mut StyleEngine, node: StyleNodeID, payloads: &StyleGroups, opacity: f64) -> u64 {+ let value_of = |property| match property {+ crate::css::property_metadata::property_id::OPACITY => {+ RetainedStyleValueData::from_owned(crate::css::style_value::StyleValueData::Number { value: opacity })+ }+ _ => crate::css::style_compute::initial_value_handle(property).clone(),+ };+ engine+ .install_test_record(+ computed::ComputedStyleTarget::new(node, u8::MAX),+ Some(&value_of),+ Some(payloads),+ 0,+ )+ .raw()+}++/// Has the host hold a record for `node` that makes it an inline-size query container.+fn hold_container_record(engine: &mut StyleEngine, node: StyleNodeID) {+ engine.set_element_box_kind(node, bridge::ElementBoxKind::FromDisplay);+ let mut payloads = engine.default_groups().groups().clone();+ // SAFETY: The group at this index holds box values.+ unsafe {+ payloads.write_group::<BoxValues>(group_index::BOX, |box_values| {+ box_values.display = crate::css::display::FfiDisplay::block();+ box_values.is_inline_size_container = true;+ });+ }+ let record = install_record(engine, node, &payloads, 1.0);+ let held = engine.computed_group_sets.host_record(record).cloned();+ engine.set_held_style_record(node, held);+}++/// The bytes a fork of `engine` holds of its own, as `RenderState::fork` makes one.+///+/// NB: The fork does not retain the font cascades its font resolutions name, as a fork of the+/// render state does: the test's font resolver makes none.+fn fork_bytes(engine: &StyleEngine) -> i64 {+ let (fork, bytes) = count_live_bytes(|| {+ let mut fork = engine.clone();+ fork.detach_tree_depth_for_fork();+ fork+ });+ drop(fork);+ bytes+}++/// What a fork of the smaller document allocates, and how much more per element a fork of one+/// twice as large does, at most.+const FORK_BYTES: i64 = 5_000;+const FORK_BYTES_PER_ELEMENT: f64 = 1.5;++#[test]+fn forking_a_styled_document_allocates_at_most_as_today() {+ let small = fork_bytes(&styled_document(ELEMENTS));+ let large = fork_bytes(&styled_document(2 * ELEMENTS));+ let per_element = (large - small) as f64 / ELEMENTS as f64;+ // FIXME: A fork copies chunk pointers and reference counts, not tables: drive both bounds to+ // what the chunks written since the fork hold.+ assert!(+ small <= FORK_BYTES,+ "a fork of {ELEMENTS} elements allocates {small} bytes"+ );+ assert!(+ per_element <= FORK_BYTES_PER_ELEMENT,+ "a fork allocates {per_element:.1} bytes per element"+ );+}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/self_check.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/self_check.rsnew file mode 100644index 00000000000..da9a49157e7--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/self_check.rs@@ -0,0 +1,750 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The check of what the engine holds against a cold reference pass over the same document:+//! one thread, every cache off, on a fork of the engine, so that nothing the reference pass does+//! reaches the document's engine. With `LIBWEB_STYLE_SELFCHECK` set, the document is checked so+//! at the end of each style update that installed styles; `report` prints what differs, any other+//! value but `0` aborts on it. `threads` (or `threads-report`) also checks it against cold passes+//! with their caches on, on one thread and on several: each thread keeps caches and style sharing+//! candidates of its own, so what a pass reuses depends on how its elements spread over threads.+//! The unit tests check the engine with the same comparison.++use super::super::*;+use super::records::{Record, RecordCells, Records, RetainedRecords};+use super::rules::RuleIndex;+use super::traversal;+#[cfg(test)]+use super::write_once::WriteOnce;+use crate::css::custom_properties::CustomPropertyStore;+use crate::css::property_metadata::{FIRST_LONGHAND_PROPERTY_ID, LAST_LONGHAND_PROPERTY_ID, property_name};+use crate::css::style_value::{RetainedStyleValueData, retained_style_values_equal};+use std::sync::Arc;+use std::time::Instant;++/// What `LIBWEB_STYLE_SELFCHECK` asks for.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(super) enum Mode {+ Off,+ /// Print what differs, and abort.+ Abort,+ /// Print what differs only.+ Report,+}++/// What `LIBWEB_STYLE_SELFCHECK` asks for, read once per document host.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(in super::super) struct SelfCheckSettings {+ mode: Mode,+ /// Whether it asks for the check against cold passes on one thread and on several.+ checks_thread_counts: bool,+}++impl SelfCheckSettings {+ pub(in super::super) fn from_environment() -> Self {+ let (mode, checks_thread_counts) = match std::env::var("LIBWEB_STYLE_SELFCHECK").as_deref() {+ Err(_) | Ok("" | "0") => (Mode::Off, false),+ Ok("report") => (Mode::Report, false),+ Ok("threads") => (Mode::Abort, true),+ Ok("threads-report") => (Mode::Report, true),+ Ok(_) => (Mode::Abort, false),+ };+ Self {+ mode,+ checks_thread_counts,+ }+ }++ pub(in super::super) fn is_enabled(self) -> bool {+ self.mode != Mode::Off+ }+}++/// How many threads the self-check's cold passes on several threads run on.+fn reference_thread_count() -> u32 {+ traversal::thread_count().max(4) as u32+}++/// The names of the groups, by `group_index`.+const GROUP_NAMES: [&str; crate::css::table_group_builder::group_index::COUNT] = [+ "inherited list and table",+ "inherited UI",+ "inherited SVG",+ "inherited text",+ "font",+ "animation",+ "SVG reset",+ "grid",+ "anchor",+ "content",+ "alignment",+ "misc layout",+ "misc interaction",+ "effects",+ "mask",+ "text reset",+ "transform",+ "background",+ "border",+ "sizing",+ "surround",+ "box",+];++/// The element, as its tag, ID and classes, with `name_of` naming their atoms.+pub(super) fn describe(state: &RetainedState, node: StyleNodeID, name_of: &dyn Fn(StyleAtomID) -> String) -> String {+ let Some(facts) = state.projection.facts(node) else {+ return format!("node {}", node.raw());+ };+ let mut description = format!("<{}", name_of(facts.tag()));+ let id = facts.id();+ if !id.is_none() {+ description += &format!(" id={}", name_of(id));+ }+ let classes: Vec<_> = facts.classes().iter().map(|&class| name_of(class)).collect();+ if !classes.is_empty() {+ description += &format!(" class=\"{}\"", classes.join(" "));+ }+ description + &format!("> (node {})", node.raw())+}++pub(super) fn pseudo_element_name(kind: u8) -> String {+ use super::super::publication::pseudo_kind::{+ AFTER, BACKDROP, BEFORE, FIRST_LETTER, MARKER, SEARCH_TEXT, SEARCH_TEXT_CURRENT, SELECTION, SPELLING_ERROR,+ };+ match kind {+ BEFORE => "::before".to_owned(),+ AFTER => "::after".to_owned(),+ FIRST_LETTER => "::first-letter".to_owned(),+ SELECTION => "::selection".to_owned(),+ SEARCH_TEXT => "::search-text".to_owned(),+ SEARCH_TEXT_CURRENT => "::search-text:current".to_owned(),+ SPELLING_ERROR => "::spelling-error".to_owned(),+ BACKDROP => "::backdrop".to_owned(),+ MARKER => "::marker".to_owned(),+ kind => format!("pseudo-element {kind}"),+ }+}++fn payloads_equal(+ group: usize,+ first: &crate::css::computed_values::GroupPointer,+ second: &crate::css::computed_values::GroupPointer,+) -> bool {+ let (first, second) = (first.as_ptr(), second.as_ptr());+ // SAFETY: Both are live payloads of the group.+ first == second || unsafe { crate::css::computed_values::style_group_payloads_equal(group, first, second) }+}++fn serialized(value: Option<&RetainedStyleValueData>) -> String {+ value.map_or_else(+ || "(none)".to_owned(),+ |value| String::from_utf16_lossy(&crate::css::serialize::serialize_style_value_to_utf16(value.data())),+ )+}++/// The values of the custom properties whose names resolve to different values in two stores,+/// whichever stores the values are in, as the first's and the second's.+fn custom_property_differences(+ first: Option<&Arc<CustomPropertyStore>>,+ second: Option<&Arc<CustomPropertyStore>>,+) -> Vec<(String, String)> {+ fn append_names(store: &CustomPropertyStore, names: &mut Vec<usize>) {+ names.extend(store.own_values.keys());+ if let Some(parent) = store.parent() {+ append_names(parent, names);+ }+ }+ let (first, second) = (first.map(Arc::as_ref), second.map(Arc::as_ref));+ let mut all = Vec::new();+ for store in [first, second].into_iter().flatten() {+ append_names(store, &mut all);+ }+ all.sort_unstable();+ all.dedup();+ let describe = |entry: Option<&crate::css::custom_properties::CustomPropertyEntry>| {+ entry.map_or_else(+ || "(none)".to_owned(),+ |entry| match entry.important {+ true => format!("{} !important", serialized(Some(&entry.value))),+ false => serialized(Some(&entry.value)),+ },+ )+ };+ all.into_iter()+ .filter_map(|name| {+ let (first, second) = (+ first.and_then(|store| store.get(name)),+ second.and_then(|store| store.get(name)),+ );+ let equal = match (first, second) {+ (None, None) => true,+ (Some(first), Some(second)) => {+ first.important == second.important && retained_style_values_equal(&first.value, &second.value)+ }+ _ => false,+ };+ (!equal).then(|| (describe(first), describe(second)))+ })+ .collect()+}++/// The parts `live` differs from `cold` in, compared by value: the payloads of the groups, the+/// longhands, what their groups are built from and their flags as published, the custom properties by the values their names resolve to, and+/// what the record notes of how it was computed, each with the values that differ where they+/// have a text.+pub(super) fn record_differences(live: &Record, cold: &Record) -> Vec<String> {+ let mut differences = Vec::new();+ let groups: Vec<_> = (0..crate::css::table_group_builder::group_index::COUNT)+ .filter(|&group| !payloads_equal(group, &live.payloads[group], &cold.payloads[group]))+ .map(|group| GROUP_NAMES[group])+ .collect();+ if !groups.is_empty() {+ differences.push(format!("the groups {}", groups.join(", ")));+ }+ let (live_longhands, cold_longhands) = (+ computed::ViewLonghands::of_record(live),+ computed::ViewLonghands::of_record(cold),+ );+ let longhands: Vec<_> = (FIRST_LONGHAND_PROPERTY_ID..=LAST_LONGHAND_PROPERTY_ID)+ .filter_map(|property| {+ let (ours, theirs) = (live_longhands.handle(property), cold_longhands.handle(property));+ let equal = match (ours, theirs) {+ (None, None) => true,+ (Some(ours), Some(theirs)) => retained_style_values_equal(ours, theirs),+ _ => false,+ };+ (!equal).then(|| {+ format!(+ "{}: live {}, cold {}",+ property_name(property),+ serialized(ours),+ serialized(theirs)+ )+ })+ })+ .collect();+ if !longhands.is_empty() {+ differences.push(format!("the longhands {{{}}}", longhands.join("; ")));+ } else if !live.rare().value_facts.publication_equals(&cold.rare().value_facts) {+ differences.push(format!(+ "the groups, in {}",+ live.rare()+ .value_facts+ .difference(&cold.rare().value_facts)+ .unwrap_or_else(|| "what they are built from beside their values".into())+ ));+ }+ let flags = live+ .rare()+ .table_flags+ .publication_differences(&cold.rare().table_flags);+ if !flags.is_empty() {+ differences.push(format!("the longhand table flags {{{}}}", flags.join("; ")));+ }+ if live.facts() != cold.facts() {+ differences.push("the record facts".into());+ }+ if live.payloads.current_color() != cold.payloads.current_color() {+ differences.push(format!(+ "current color {:#010x} != {:#010x}",+ live.payloads.current_color(),+ cold.payloads.current_color()+ ));+ }+ for (name, live, cold) in [+ ("custom properties", live.custom_properties(), cold.custom_properties()),+ (+ "inheritable custom properties",+ live.inheritable_custom_properties(),+ cold.inheritable_custom_properties(),+ ),+ ] {+ let values = custom_property_differences(live, cold);+ if !values.is_empty() {+ let values: Vec<_> = values+ .iter()+ .map(|(live, cold)| format!("live {live}, cold {cold}"))+ .collect();+ differences.push(format!("{name} {{{}}}", values.join("; ")));+ }+ }+ // NB: A cascade decides one declaration per name, so the order of the list says nothing.+ let custom_declarations_equal = match (&live.custom_declarations(), &cold.custom_declarations()) {+ (None, None) => true,+ (Some(first), Some(second)) => {+ let same_declaration =+ |first: &(CustomDeclaration, RetainedStyleValueData),+ second: &(CustomDeclaration, RetainedStyleValueData)| {+ first.0 == second.0 && retained_style_values_equal(&first.1, &second.1)+ };+ first.len() == second.len()+ && (first+ .iter()+ .zip(second.iter())+ .all(|(first, second)| same_declaration(first, second))+ || first+ .iter()+ .all(|declaration| second.iter().any(|other| same_declaration(declaration, other))))+ }+ _ => false,+ };+ if !custom_declarations_equal {+ differences.push("custom declarations".to_owned());+ }+ if live.rare().custom_property_reads != cold.rare().custom_property_reads {+ differences.push("the custom properties the longhands read".to_owned());+ }+ if live.rare().reads.parent_reset_groups != cold.rare().reads.parent_reset_groups {+ differences.push(format!(+ "parent_reset_groups {:#x} != {:#x}",+ live.rare().reads.parent_reset_groups,+ cold.rare().reads.parent_reset_groups+ ));+ }+ for (name, live, cold) in [+ (+ "reads_sibling_position",+ live.rare().reads.reads_sibling_position,+ cold.rare().reads.reads_sibling_position,+ ),+ (+ "reads_attributes",+ live.rare().reads.reads_attributes,+ cold.rare().reads.reads_attributes,+ ),+ ] {+ if live != cold {+ differences.push(format!("{name} {live} != {cold}"));+ }+ }+ if live.rare().reads.container_units != cold.rare().reads.container_units {+ differences.push(format!(+ "container units {:#x} != {:#x}",+ live.rare().reads.container_units,+ cold.rare().reads.container_units+ ));+ }+ if live.rare().counter_style_environment_identity != cold.rare().counter_style_environment_identity {+ differences.push("counter style environment".to_owned());+ }+ if live.rare().animation_name_scope != cold.rare().animation_name_scope {+ differences.push("animation name scope".to_owned());+ }+ differences+}++/// What the records `live` holds for the document under `root`, of each element and of its+/// pseudo-elements, differ in from those `cold` holds, one line per element or pseudo-element,+/// with `describe` naming the elements, and how many elements it compared.+pub(super) fn differences(+ state: &RetainedState,+ root: StyleNodeID,+ live: &RetainedRecords,+ cold: &RetainedRecords,+ describe: &dyn Fn(StyleNodeID) -> String,+) -> (Vec<String>, usize) {+ let (failures, compared) = differences_by_element(state, root, live, cold);+ let failures = failures+ .into_iter()+ .map(|(node, difference)| match difference.strip_prefix("::") {+ Some(of_pseudo_element) => {+ let (name, rest) = of_pseudo_element.split_once(": ").unwrap_or((of_pseudo_element, ""));+ format!("::{name} of {}: {rest}", describe(node))+ }+ None => format!("{}: {difference}", describe(node)),+ })+ .collect();+ (failures, compared)+}++/// What differs between `live` and `cold`, one line per element or pseudo-element beginning with+/// the name of the pseudo-element where it is one, with the element it is about.+pub(super) fn differences_by_element(+ state: &RetainedState,+ root: StyleNodeID,+ live: &RetainedRecords,+ cold: &RetainedRecords,+) -> (Vec<(StyleNodeID, String)>, usize) {+ let mut failures = Vec::new();+ let mut compared = 0;+ // NB: The engine keeps the records of the elements below one that stopped being displayed,+ // which no pass keeps current and the host installs none of.+ let hidden_in_cold = |node| {+ std::iter::successors(state.projection.inheritance_parent(node), |&ancestor| {+ state.projection.inheritance_parent(ancestor)+ })+ .any(|ancestor| cold.get(ancestor).is_none_or(|record| !record.is_displayed()))+ };+ for node in state.projection.style_preorder(root) {+ match (live.get(node), cold.get(node)) {+ (None, None) => continue,+ (Some(_), None) if hidden_in_cold(node) => continue,+ (Some(_), None) => failures.push((node, "live holds a record, cold computed none".to_owned())),+ (None, Some(_)) => failures.push((node, "live holds no record, cold computed one".to_owned())),+ (Some(live), Some(cold)) => {+ let differences = record_differences(live, cold);+ if !differences.is_empty() {+ failures.push((node, format!("live differs from cold in {}", differences.join(", "))));+ }+ }+ }+ compared += 1;+ let (live, cold) = (live.pseudo_element_records(node), cold.pseudo_element_records(node));+ let kinds = |records: &[(u8, Arc<Record>)]| records.iter().map(|(kind, _)| *kind).collect::<Vec<_>>();+ if kinds(live) != kinds(cold) {+ let names = |kinds: Vec<u8>| kinds.into_iter().map(pseudo_element_name).collect::<Vec<_>>();+ failures.push((+ node,+ format!(+ "live holds the pseudo-elements {:?}, cold computed {:?}",+ names(kinds(live)),+ names(kinds(cold))+ ),+ ));+ continue;+ }+ for ((kind, live), (_, cold)) in live.iter().zip(cold) {+ let differences = record_differences(live, cold);+ if !differences.is_empty() {+ failures.push((+ node,+ format!(+ "{}: live differs from cold in {}",+ pseudo_element_name(*kind),+ differences.join(", ")+ ),+ ));+ }+ }+ }+ (failures, compared)+}++/// What the records installed for the elements under `root` and their pseudo-elements, which the host renders, differ+/// in from those `live` holds for them, one line per element or pseudo-element, with `describe` naming the elements.+/// An element's animations compose over its installed record, which is what is compared.+pub(super) fn installed_differences(+ state: &RetainedState,+ root: StyleNodeID,+ live: &RetainedRecords,+ describe: &dyn Fn(StyleNodeID) -> String,+) -> Vec<String> {+ let installed = &state.computed_group_sets;+ let mut failures = Vec::new();+ for node in state.projection.style_preorder(root) {+ // NB: The engine keeps the records of the elements below one that stopped being displayed,+ // which no pass keeps current and the host installs none of.+ let hidden = std::iter::successors(state.projection.inheritance_parent(node), |&ancestor| {+ state.projection.inheritance_parent(ancestor)+ })+ .any(|ancestor| live.get(ancestor).is_none_or(|record| !record.is_displayed()));+ if hidden {+ continue;+ }+ if let Some(held) = live.get(node)+ && let Some(record) = installed+ .assigned_style_record(node)+ .and_then(|record| installed.installed_base_record(record))+ {+ let differences = record_differences(record, held);+ if !differences.is_empty() {+ failures.push(format!(+ "{}: the installed record differs from live in {}",+ describe(node),+ differences.join(", ")+ ));+ }+ }+ for (kind, held) in live.pseudo_element_records(node) {+ let Some(record) = installed+ .pseudo_style_record(node, *kind)+ .and_then(|record| installed.installed_base_record(record))+ else {+ continue;+ };+ let differences = record_differences(record, held);+ if !differences.is_empty() {+ failures.push(format!(+ "{} of {}: the installed record differs from live in {}",+ pseudo_element_name(*kind),+ describe(node),+ differences.join(", ")+ ));+ }+ }+ }+ failures+}++/// What a reference pass computed and measured.+pub(super) struct ReferencePass {+ pub(super) records: RetainedRecords,+ /// What its last round measured.+ pub(super) statistics: traversal::Statistics,+ pub(super) indexed_entries: u64,+ pub(super) index_nanoseconds: u64,+ pub(super) style_nanoseconds: u64,+ pub(super) threads: u64,+ /// What its last round produced for each element.+ #[cfg(test)]+ pub(super) outputs: Vec<WriteOnce<traversal::ElementOutput>>,+}++/// Style the document under `engine`'s `root` from scratch on `threads` threads, against a rule+/// index of its own, and with every cache off unless `uses_caches`, and keep what it computed, or+/// none where it computes no initial style or waits on fonts or random base values for good. It+/// resolves the fonts and draws the random base values it waits on in `engine`.+pub(super) fn reference_pass(+ engine: &mut StyleEngine,+ root: StyleNodeID,+ uses_caches: bool,+ threads: u32,+) -> Option<ReferencePass> {+ let initial = engine.computed_initial(root)?;+ // NB: A pass on one thread leaves the engine's pool as it is.+ let pool = (threads > 1).then(|| engine.style_pool(threads)).flatten();+ let started = Instant::now();+ let index = RuleIndex::build(&engine.retained.rules, engine.retained.process_rule_indexes());+ let index_nanoseconds = started.elapsed().as_nanos() as u64;+ engine.retained.live_counters.note_cold_pass_index(&index);+ // A drive that waits on a font declines its element; the pass styles every element again once+ // the resolver answered.+ engine.until_resolved(root, |engine| {+ let state: &RetainedState = &engine.retained;+ let slot_count = state.projection.element_slot_count();+ let mut cells = RecordCells::default();+ cells.reserve(slot_count);+ #[cfg(test)]+ let outputs: Vec<WriteOnce<traversal::ElementOutput>> = (0..slot_count).map(|_| WriteOnce::default()).collect();+ let started = Instant::now();+ let statistics = {+ let records = Records::new(state, &cells, None)+ .composing_over_equal_records(|first, second| record_differences(first, second).is_empty());+ let context = traversal::PassContext {+ #[cfg(test)]+ outputs: Some(&outputs),+ uses_caches,+ cache_audit: state.cache_audit_mode(),+ ..traversal::PassContext::new(state, &index, &initial, &records, None)+ };+ traversal::style_document(&context, pool.as_deref(), root)+ };+ let style_nanoseconds = started.elapsed().as_nanos() as u64;+ if statistics.font_requests.is_empty() && statistics.random_requests.is_empty() {+ let styled: Vec<_> = state.projection.style_preorder(root).collect();+ let mut records = RetainedRecords::default();+ records.absorb(&mut cells, &styled, None, &mut Default::default());+ return Ok(ReferencePass {+ records,+ statistics,+ indexed_entries: index.entries.count() as u64,+ index_nanoseconds,+ style_nanoseconds,+ threads: pool.as_deref().map_or(0, rayon::ThreadPool::current_num_threads) as u64 + 1,+ #[cfg(test)]+ outputs,+ });+ }+ Err(super::Waits {+ fonts: statistics.font_requests,+ random_bases: statistics.random_requests,+ })+ })+}++impl StyleEngine {+ /// What the records the engine holds for the document under `root` differ in from those of+ /// a reference pass over a fork of the engine, one line per element or pseudo-element, or none+ /// where the engine does not own the document or has restyling left to do. Where+ /// `other_threads` names a number of threads, they are also checked against cold passes with+ /// their caches on, on one thread and on that many, with their lines naming the pass.+ pub(super) fn self_check_failures(&self, root: StyleNodeID, other_threads: Option<u32>) -> Vec<String> {+ let Some(live) = self.retained.live_style.as_deref() else {+ return Vec::new();+ };+ // NB: A pass leaving children for the next one, to inherit the composition of their+ // parents' animations, leaves their records as they were until then.+ if live.has_pending() {+ return Vec::new();+ }+ let mut fork = self.clone();+ fork.detach_host_flags_for_fork();+ fork.detach_tree_depth_for_fork();+ let name_of = |atom: StyleAtomID| self.atoms.name_of(atom).unwrap_or_else(|| format!("atom{}", atom.0));+ let describe = |node| describe(&self.retained, node, &name_of);+ let mut references = vec![(None, false, 1)];+ if let Some(threads) = other_threads {+ references.push((Some("a cold pass on 1 thread with caches".to_owned()), true, 1));+ references.push((+ Some(format!("a cold pass on {threads} threads with caches")),+ true,+ threads,+ ));+ }+ let mut failures = Vec::new();+ for (name, uses_caches, threads) in references {+ let Some(ReferencePass { records: reference, .. }) = reference_pass(&mut fork, root, uses_caches, threads)+ else {+ failures.push(format!(+ "the reference pass computes no style for the document{}",+ name.as_ref().map_or_else(String::new, |name| format!(" on {name}"))+ ));+ continue;+ };+ let (differences, _) = differences(&self.retained, root, &live.records, &reference, &describe);+ failures.extend(differences.into_iter().map(|difference| match &name {+ Some(name) => format!("against {name}: {difference}"),+ None => difference,+ }));+ }+ failures.extend(installed_differences(&self.retained, root, &live.records, &describe));+ failures+ }++ /// Check the records the engine holds for the document under `root` against a reference+ /// pass, as `settings` ask.+ pub(in super::super) fn run_self_check(&self, root: StyleNodeID, settings: SelfCheckSettings) {+ if !settings.is_enabled() {+ return;+ }+ let other_threads = settings.checks_thread_counts.then(reference_thread_count);+ conclude(&self.self_check_failures(root, other_threads), settings.mode);+ }+}++/// Print `failures` to stderr, and abort where `mode` asks to.+pub(super) fn conclude(failures: &[String], mode: Mode) {+ if failures.is_empty() {+ return;+ }+ eprintln!(+ "Style self-check: the engine differs from a cold pass in {} places:",+ failures.len()+ );+ for failure in failures {+ eprintln!(" {failure}");+ }+ assert!(+ mode != Mode::Abort,+ "the engine differs from a cold pass; set LIBWEB_STYLE_SELFCHECK=report to only print the differences"+ );+}++#[cfg(test)]+mod tests {+ use super::super::test_support::*;+ use super::*;++ fn document_with_a_target() -> (StyleEngine, Vec<StyleNodeID>) {+ let (mut engine, nodes) = linear_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(+ &mut engine,+ sheet,+ ".target { color: rgb(0, 128, 0); width: 10px; } .target::before { content: \"x\"; }",+ );+ add_class(&mut engine, nodes[2], "target");+ start_live(&mut engine, nodes[0]);+ (engine, nodes)+ }++ #[test]+ fn live_style_holds_what_a_reference_pass_computes() {+ let (mut engine, nodes) = document_with_a_target();+ assert_eq!(engine.self_check_failures(nodes[0], None), Vec::<String>::new());++ add_class(&mut engine, nodes[1], "target");+ remove_class(&mut engine, nodes[2], "target");+ run_style_update(&mut engine, nodes[0]);+ assert_eq!(engine.self_check_failures(nodes[0], None), Vec::<String>::new());+ }++ #[test]+ fn live_style_holds_what_cold_passes_on_one_thread_and_on_four_compute() {+ let (engine, nodes) = document_with_a_target();+ assert_eq!(engine.self_check_failures(nodes[0], Some(4)), Vec::<String>::new());+ }++ #[test]+ fn a_record_live_style_holds_wrongly_is_reported() {+ let (mut engine, nodes) = document_with_a_target();+ // Seed a mismatch: the element no rule styles holds the record of the one the rule styles.+ let seeded = live_record(&engine, nodes[2]);+ let mut live = engine.retained.live_style.take().expect("the engine is live");+ let mut cells = RecordCells::default();+ cells.reserve(engine.retained.projection.element_slot_count());+ Records::new(&engine.retained, &cells, None).insert(nodes[1], seeded, nodes[1], None);+ live.records+ .absorb(&mut cells, &[nodes[1]], None, &mut Default::default());+ engine.retained.live_style = Some(live);++ let failures = engine.self_check_failures(nodes[0], Some(4));+ assert_eq!(failures.len(), 4, "{failures:?}");+ assert!(+ failures[1].starts_with("against a cold pass on 1 thread with caches: "),+ "{failures:?}"+ );+ assert!(+ failures[2].starts_with("against a cold pass on 4 threads with caches: "),+ "{failures:?}"+ );+ // NB: What it installed is what a pass computed before the seed, which the seeded record differs from too.+ assert!(+ failures[3].contains(&format!(+ "(node {}): the installed record differs from live in ",+ nodes[1].raw()+ )),+ "{failures:?}"+ );+ let failure = &failures[0];+ // NB: The atoms of a test's engine name no strings the self-check could show.+ assert!(+ failure.contains(&format!("(node {}): live differs from cold in ", nodes[1].raw())),+ "{failure}"+ );+ for part in [+ "the groups ",+ "inherited text",+ "color: live ",+ "width: live 10px, cold auto",+ ] {+ assert!(failure.contains(part), "{failure} names {part}");+ }+ }++ #[test]+ fn a_record_installed_for_another_element_is_reported() {+ let (mut engine, nodes) = document_with_a_target();+ // Seed a mismatch: the engine holds the right records, and the element no rule styles is+ // assigned the record installed for the one the rule styles.+ let sets = &mut engine.retained.computed_group_sets;+ let installed = sets.assigned_style_record(nodes[2]).expect("the element is installed");+ sets.assign_installed_record(nodes[1], installed);++ let failures = engine.self_check_failures(nodes[0], None);+ assert_eq!(failures.len(), 1, "{failures:?}");+ assert!(+ failures[0].contains(&format!(+ "(node {}): the installed record differs from live in ",+ nodes[1].raw()+ )),+ "{failures:?}"+ );+ }++ #[test]+ fn a_report_only_prints_the_differences() {+ conclude(&["a difference".to_owned()], Mode::Report);+ conclude(&[], Mode::Abort);+ }++ #[test]+ #[should_panic(expected = "the engine differs from a cold pass")]+ fn a_difference_aborts() {+ conclude(&["a difference".to_owned()], Mode::Abort);+ }+}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/test_support.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/test_support.rsnew file mode 100644index 00000000000..2a469795ec5--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/test_support.rs@@ -0,0 +1,699 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! What the unit tests of the engine build on: a host stand-in that lets an engine compute records,+//! documents and rules built through the inputs the host records, and a check of what live style+//! the engine holds against a cold pass over the same document, and of what that pass matched against the+//! reference matcher.++use super::super::bridge::{+ BoundScopeChain, FfiDocumentStyleComputationInputs, FfiFontResolutionRequest, FfiHostHandle, FfiResolvedFont,+ element_adjustment_fact, publish_rule_declarations, publish_style_rule,+};+use super::super::font_resolution::{FontResolverHost, PublishedFontFaces};+use super::super::*;+use super::records::Record;+use super::write_once::WriteOnce;+use super::{self_check, traversal};+use std::cell::RefCell;+use std::sync::Arc;++/// Every request resolves to one font with these metrics, which nothing follows the handles of.+unsafe extern "C" fn resolve_font(+ _memo: *const std::ffi::c_void,+ _snapshot: *const std::ffi::c_void,+ _request: FfiFontResolutionRequest,+) -> FfiResolvedFont {+ FfiResolvedFont {+ first_available_font: FfiHostHandle::from_pointer(std::ptr::dangling()),+ font_cascade_list: FfiHostHandle::from_pointer(std::ptr::dangling()),+ ascent: 12.0,+ descent: 4.0,+ x_height: 8.0,+ zero_advance: 8.0,+ font_size_adjust_from_font: 0.0,+ }+}++/// An engine hosted as a document's is, as far as computing records goes: it has a font resolver+/// and a font resolution cache, and the document's computation inputs, those of an 800x600+/// viewport with a 16px font.+pub(super) fn hosted_engine() -> StyleEngine {+ let mut engine = StyleEngine::new();+ engine.share_the_process_style_for_test();+ // SAFETY: The test build's host object references and unreferences do nothing.+ let font_faces = unsafe { PublishedFontFaces::adopt(std::ptr::dangling(), std::ptr::dangling()) };+ engine.host.font_resolver = Some(FontResolverHost::with_callbacks(resolve_font, resolve_font, font_faces));+ engine.retained.font_resolution = Some(Default::default());+ // NB: CSS pixels count in 64ths of a pixel raw.+ engine.retained.document_style_computation_inputs = FfiDocumentStyleComputationInputs {+ viewport_width: 800.0,+ viewport_height: 600.0,+ root_font_size: 16.0,+ root_font_x_height: 8.0,+ root_font_cap_height: 11.0,+ root_font_zero_advance: 8.0,+ root_line_height: 18.0,+ root_effective_zoom: 1.0,+ initial_font_size: 16.0,+ initial_font_x_height: 8.0,+ initial_font_cap_height: 11.0,+ initial_font_zero_advance: 8.0,+ initial_font_size_raw: 16 << 6,+ default_font_size_raw: 16 << 6,+ device_pixels_per_css_pixel: 1.0,+ ..Default::default()+ };+ engine+}++/// The names `atom` interned: the strings, kept alive for their identities to stay theirs, and+/// the name of each atom, for a failure to name it by.+#[derive(Default)]+struct Names {+ strings: Vec<ak::Utf16FlyString>,+ by_atom: HashMap<StyleAtomID, String>,+}++thread_local! {+ static NAMES: RefCell<Names> = RefCell::new(Names::default());+}++/// The atom of `name`, as the host interns the names elements carry and selectors test.+pub(super) fn atom(engine: &mut StyleEngine, name: &str) -> StyleAtomID {+ let string = ak::Utf16FlyString::from_utf16(&name.encode_utf16().collect::<Vec<_>>());+ let atom = engine.intern_atom(string.raw_identity());+ // NB: Each engine has atoms of its own, so the name of an atom is the one interned last.+ NAMES.with_borrow_mut(|names| {+ names.strings.push(string);+ names.by_atom.insert(atom, name.to_owned());+ });+ atom+}++fn name_of(atom: StyleAtomID) -> String {+ NAMES.with_borrow(|names| {+ names+ .by_atom+ .get(&atom)+ .cloned()+ .unwrap_or_else(|| format!("atom{}", atom.0))+ })+}++pub(super) fn allocate_nodes(engine: &mut StyleEngine, count: usize) -> Vec<StyleNodeID> {+ let mut raw = vec![0_u32; count];+ engine.allocate_style_nodes(&mut raw);+ raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect()+}++pub(super) fn relations(+ parent: Option<StyleNodeID>,+ previous: Option<StyleNodeID>,+ next: Option<StyleNodeID>,+) -> TreeRelations {+ TreeRelations {+ parent,+ previous_element_sibling: previous,+ next_element_sibling: next,+ ..TreeRelations::detached(TreeScopeID::DOCUMENT)+ }+}++pub(super) fn add_feature(engine: &mut StyleEngine, node: StyleNodeID, feature: LocalFeatureKey) {+ engine.record_input(+ InputKey::LocalFeature(node, feature),+ InputValue::Feature(FeatureValue::Absent),+ InputValue::Feature(FeatureValue::Present),+ );+}++pub(super) fn remove_feature(engine: &mut StyleEngine, node: StyleNodeID, feature: LocalFeatureKey) {+ engine.record_input(+ InputKey::LocalFeature(node, feature),+ InputValue::Feature(FeatureValue::Present),+ InputValue::Feature(FeatureValue::Absent),+ );+}++pub(super) fn set_atom_feature(+ engine: &mut StyleEngine,+ node: StyleNodeID,+ feature: LocalFeatureKey,+ atom: StyleAtomID,+) {+ engine.record_input(+ InputKey::LocalFeature(node, feature),+ InputValue::Feature(FeatureValue::Absent),+ InputValue::Feature(FeatureValue::Atom(atom)),+ );+}++pub(super) fn set_tag(engine: &mut StyleEngine, node: StyleNodeID, tag: &str) {+ let tag = atom(engine, tag);+ set_atom_feature(engine, node, LocalFeatureKey::TagName, tag);+}++pub(super) fn add_class(engine: &mut StyleEngine, node: StyleNodeID, class: &str) {+ let class = atom(engine, class);+ add_feature(engine, node, LocalFeatureKey::Class(class));+}++pub(super) fn remove_class(engine: &mut StyleEngine, node: StyleNodeID, class: &str) {+ let class = atom(engine, class);+ remove_feature(engine, node, LocalFeatureKey::Class(class));+}++/// Builds the document element `root`, a `div`, with `count - 1` `div` children, through the same+/// delta path C++ drives.+pub(super) fn document_with_children(count: usize) -> (StyleEngine, Vec<StyleNodeID>) {+ let mut engine = hosted_engine();+ let nodes = allocate_nodes(&mut engine, count);+ engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));+ for index in 1..count {+ let previous = (index > 1).then(|| nodes[index - 1]);+ engine.record_tree_delta(nodes[index], None, Some(relations(Some(nodes[0]), previous, None)));+ }+ engine.set_element_adjustment_facts(nodes[0], element_adjustment_fact::IS_DOCUMENT_ELEMENT);+ for &node in &nodes {+ set_tag(&mut engine, node, "div");+ }+ (engine, nodes)+}++/// Builds `root -> [a, b, c]`.+pub(super) fn linear_document() -> (StyleEngine, Vec<StyleNodeID>) {+ document_with_children(4)+}++/// Builds `root -> a -> b -> c`.+pub(super) fn nested_document() -> (StyleEngine, Vec<StyleNodeID>) {+ let mut engine = hosted_engine();+ let nodes = allocate_nodes(&mut engine, 4);+ engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));+ for pair in nodes.windows(2) {+ engine.record_tree_delta(pair[1], None, Some(relations(Some(pair[0]), None, None)));+ }+ engine.set_element_adjustment_facts(nodes[0], element_adjustment_fact::IS_DOCUMENT_ELEMENT);+ for &node in &nodes {+ set_tag(&mut engine, node, "div");+ }+ (engine, nodes)+}++/// Attaches the shadow tree `scope` to `host`: a shadow root and a chain of `depth` `div`+/// elements below it, root first.+pub(super) fn attach_shadow_tree(+ engine: &mut StyleEngine,+ host: StyleNodeID,+ scope: TreeScopeID,+ depth: usize,+) -> Vec<StyleNodeID> {+ let nodes = allocate_nodes(engine, depth + 1);+ engine.record_tree_delta(nodes[0], None, Some(TreeRelations::detached(scope)));+ for pair in nodes.windows(2) {+ engine.record_tree_delta(+ pair[1],+ None,+ Some(TreeRelations {+ parent: Some(pair[0]),+ tree_scope: scope,+ ..TreeRelations::detached(scope)+ }),+ );+ set_tag(engine, pair[1], "div");+ }+ engine.set_shadow_root(host, nodes[0]);+ engine.set_tree_scope_root(scope, nodes[0]);+ nodes+}++/// Builds `root -> [a, b, c]` with `.target:nth-of-type(2)`, where `a` and `c` are of one type and+/// `b`, with the same local name in another namespace, of another, and only `c` is a target.+pub(super) fn typed_nth_of_type_document() -> (StyleEngine, Vec<StyleNodeID>) {+ let (mut engine, nodes) = linear_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, sheet, ".target:nth-of-type(2) { color: rgb(0, 128, 0); }");+ let first_namespace = atom(&mut engine, "first-namespace");+ let other_namespace = atom(&mut engine, "other-namespace");+ for (node, namespace) in [+ (nodes[1], first_namespace),+ (nodes[2], other_namespace),+ (nodes[3], first_namespace),+ ] {+ engine.set_element_namespace(node, namespace);+ }+ add_class(&mut engine, nodes[3], "target");+ (engine, nodes)+}++/// Builds `root -> [a, b, c]` with `.target:nth-child(3n)`, where every child is a target.+pub(super) fn nth_target_document() -> (StyleEngine, Vec<StyleNodeID>) {+ let (mut engine, nodes) = linear_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, sheet, ".target:nth-child(3n) { color: rgb(0, 128, 0); }");+ for &node in &nodes[1..] {+ add_class(&mut engine, node, "target");+ }+ (engine, nodes)+}++/// An author sheet attached to `scope`.+pub(super) fn add_sheet(engine: &mut StyleEngine, scope: TreeScopeID) -> SheetID {+ add_sheet_with_origin(engine, scope, CascadeOrigin::Author)+}++pub(super) fn add_sheet_with_origin(engine: &mut StyleEngine, scope: TreeScopeID, origin: CascadeOrigin) -> SheetID {+ let sheet = engine.add_sheet(origin);+ engine.attach_sheet(sheet, scope);+ sheet+}++/// A style rule parsed as the host parses a sheet's: its selectors and its declarations.+pub(super) struct ParsedRule {+ selectors: Arc<crate::css::selector_parser::RustParsedSelectorList>,+ pub(super) declarations: crate::css::declaration_block::SharedDeclarationBlock,+}++/// The style rules of `source`.+pub(super) fn parse_rules(source: &str) -> Vec<ParsedRule> {+ use crate::css::css_tokenizer::TokenizerInput;+ use crate::css::parser::syntax_parser::parse_shared_stylesheet;+ use crate::css::rule::{NativeRuleList, NativeRuleType, rust_rule_list_count, rust_rule_type};+ let units: Vec<_> = source.encode_utf16().collect();+ // NB: A random function parses only where its declaration is numbered, as the host numbers+ // those of a sheet.+ let random_function_index = crate::css::parser::value_parser::RandomFunctionIndex::default();+ let context = crate::css::parser::value_parser::ParseContext {+ random_function_index: Some(&random_function_index),+ ..Default::default()+ };+ let rules = NativeRuleList::from_parsed(parse_shared_stylesheet(TokenizerInput::Utf16(&units), Some(&context)));+ let count = rust_rule_list_count(&rules);+ assert_ne!(count, 0, "no rule parses from {source:?}");+ (0..count)+ .map(|index| {+ let rule = rules.rule_at(index);+ assert!(+ matches!(rust_rule_type(&rule), NativeRuleType::Style),+ "only style rules are published: {source:?}"+ );+ ParsedRule {+ selectors: rule.style_rule().selectors(),+ declarations: rule.cascade_declarations().expect("a style rule declares"),+ }+ })+ .collect()+}++/// Append `rule` to `sheet` with its selectors, answering the rule it is.+fn publish_parsed_rule(engine: &mut StyleEngine, sheet: SheetID, rule: &ParsedRule) -> RuleID {+ let published = publish_style_rule(+ engine,+ sheet.0 + 1,+ 0,+ &rule.selectors.selectors,+ &BoundScopeChain::default(),+ );+ assert_ne!(published, 0, "the rule is published");+ RuleID(published - 1)+}++/// Append the style rules of `source` to `sheet`, as the host publishes a sheet's rules: their+/// selectors, then their declarations.+pub(super) fn add_rules(engine: &mut StyleEngine, sheet: SheetID, source: &str) -> Vec<RuleID> {+ parse_rules(source)+ .iter()+ .map(|parsed| {+ let rule = publish_parsed_rule(engine, sheet, parsed);+ publish_rule_declarations(engine, rule.0 + 1, &parsed.declarations);+ rule+ })+ .collect()+}++/// Attach a user agent sheet of the style rules of `source` to the document, as the host does: the+/// process keeps its rules, which one published sheet holds for every document attaching `source`.+/// Answers the sheet and the rules, as the document names them.+pub(super) fn add_user_agent_sheet(engine: &mut StyleEngine, source: &str) -> (SheetID, Vec<RuleID>) {+ use std::hash::{Hash, Hasher};+ let mut hasher = crate::css::style::fast_hash::fast_hasher();+ source.hash(&mut hasher);+ let source_identity = hasher.finish();+ Arc::clone(&engine.process_style).publish_user_agent_sheet(source_identity, |engine, sheet| {+ add_rules(engine, sheet, source);+ });+ let sheet = engine.add_user_agent_sheet(source_identity);+ engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);+ let rules = engine.rules.rules_in_sheet(sheet);+ (sheet, rules)+}++/// Take a style update and every later wave of its pass, as the host does when it installs+/// each wave; nothing is installed here. The engine, where it owns the document, restyles what+/// the transaction changed as it does.+pub(super) fn run_style_update(engine: &mut StyleEngine, root: StyleNodeID) {+ engine.run_style_update(root, |_, _| {});+}++/// Have the engine own the document under `root`, from a cold pass of it after the inputs+/// recorded so far, with its passes on one thread.+pub(super) fn start_live(engine: &mut StyleEngine, root: StyleNodeID) {+ start_live_on(engine, root, 1);+}++/// Have the engine own the document under `root` as `start_live` does, with its passes on+/// `threads` threads.+pub(super) fn start_live_on(engine: &mut StyleEngine, root: StyleNodeID, threads: u32) {+ run_style_update(engine, root);+ engine.restart_live_style(root, threads);+ // NB: The engine owned the document from its first transaction on, so the restart has the next+ // transaction restyle everything. Take that one here, so the next a test takes restyles+ // only what it changed.+ run_style_update(engine, root);+ assert!(engine.has_live_style(), "the engine owns the document");+}++/// What `node` matches by the reference matcher, one entry per rule and pseudo-element-ness.+type MatchedRule = (RuleID, bool, crate::css::selector::Specificity);++/// One entry per rule and pseudo-element-ness, with the greatest specificity among its matching+/// entries, as the cascade weighs a rule.+fn merged_by_rule(matches: impl Iterator<Item = MatchedRule>) -> Vec<MatchedRule> {+ let mut merged: Vec<MatchedRule> = Vec::new();+ for (rule, pseudo_element, specificity) in matches {+ match merged+ .iter_mut()+ .find(|(existing_rule, existing_pseudo, _)| *existing_rule == rule && *existing_pseudo == pseudo_element)+ {+ Some(existing) => existing.2 = existing.2.max(specificity),+ None => merged.push((rule, pseudo_element, specificity)),+ }+ }+ merged.sort_unstable();+ merged+}++pub(super) fn exact_matches(engine: &StyleEngine, node: StyleNodeID) -> Vec<MatchedRule> {+ let mut exact = Vec::new();+ assert!(+ engine+ .retained+ .append_exact_matches_in_every_scope(node, &mut exact)+ .is_ok(),+ "the reference matcher matches {}",+ describe(&engine.retained, node)+ );+ merged_by_rule(+ exact+ .iter()+ .map(|matched| (matched.rule, matched.pseudo_element.is_some(), matched.specificity)),+ )+}++/// The element, as its tag, ID and classes, for a failure to name.+pub(super) fn describe(state: &RetainedState, node: StyleNodeID) -> String {+ self_check::describe(state, node, &name_of)+}++/// The record the engine holds for `node`.+pub(super) fn live_record(engine: &StyleEngine, node: StyleNodeID) -> Arc<Record> {+ let records = engine+ .retained+ .live_style+ .as_ref()+ .expect("the engine is live")+ .records();+ records+ .get(node)+ .unwrap_or_else(|| panic!("the engine holds a record for {}", describe(&engine.retained, node)))+ .clone()+}++/// Whether two records hold equal values, as `assert_live_matches_cold` compares them.+pub(super) fn records_equal(first: &Record, second: &Record) -> bool {+ self_check::record_differences(first, second).is_empty()+}++/// Whether the records the engine holds for `first` and `second` hold equal values, for a test+/// to tell that a rule reached an element.+pub(super) fn live_records_equal(engine: &StyleEngine, first: StyleNodeID, second: StyleNodeID) -> bool {+ records_equal(&live_record(engine, first), &live_record(engine, second))+}++/// How many passes settling the engine may take, as levels of elements composing animations+/// below one another.+const MAX_SETTLING_PASSES: usize = 1024;++/// Settle the engine, then check every record it holds for the document under `root`, of an+/// element and of its pseudo-elements, against the record a cold pass over the document computes,+/// and what that pass matched for each element against the reference matcher. Answers how many+/// elements it checked.+///+/// The records are compared by value: the payloads of each group and the longhand tables as the+/// host is handed them, and the custom properties by what each name resolves to, since the live+/// records are not the cold pass's, and their custom property stores chain to other parents.+pub(super) fn assert_live_matches_cold(engine: &mut StyleEngine, root: StyleNodeID) -> usize {+ assert!(engine.has_live_style(), "the engine owns the document");+ for _ in 0..MAX_SETTLING_PASSES {+ if !engine+ .retained+ .live_style+ .as_ref()+ .is_some_and(|live| live.has_pending())+ {+ break;+ }+ engine.live_restyle(root);+ }+ assert!(engine.has_live_style(), "the engine kept the document as it settled");+ let self_check::ReferencePass {+ records: cold, outputs, ..+ } = self_check::reference_pass(engine, root, false, 1).expect("the cold pass styles the document");+ let state = &engine.retained;+ let live = state.live_style.as_ref().expect("the engine is live").records();+ let describe = |node| describe(state, node);+ let (mut failures, checked) = self_check::differences(state, root, live, &cold, &describe);+ for node in state.projection.style_preorder(root) {+ let Some(output) = outputs.get(node.element_slot()).and_then(WriteOnce::get) else {+ continue;+ };+ match output.outcome {+ traversal::Outcome::CascadeDeclined | traversal::Outcome::ComputeDeclined => {+ failures.push(format!("{}: the cold pass declined to style it", describe(node)));+ }+ _ => {}+ }+ if let Some(matches) = &output.matches {+ let ours = merged_by_rule(+ matches+ .iter()+ .map(|matched| (matched.rule, matched.pseudo_element(), matched.specificity)),+ );+ let reference = exact_matches(engine, node);+ if ours != reference {+ failures.push(format!(+ "{}: the cold pass matched {ours:?}, the reference matcher {reference:?}",+ describe(node)+ ));+ }+ }+ }+ assert!(+ failures.is_empty(),+ "the engine is not what a cold pass computes:\n{}",+ failures.join("\n")+ );+ checked+}++mod tests {+ use super::*;++ #[test]+ fn an_element_holding_a_record_only_as_installed_hands_down_its_custom_properties() {+ let (mut engine, nodes) = nested_document();+ start_live(&mut engine, nodes[0]);+ engine.install_test_record(computed::ComputedStyleTarget::new(nodes[1], u8::MAX), None, None, 0);+ let cells = crate::css::style::pipeline::records::RecordCells::default();+ let records = crate::css::style::pipeline::records::Records::new(&engine.retained, &cells, None);+ assert!(records.custom_stores_of(nodes[1]).is_some());+ }++ #[test]+ fn a_class_change_restyles_a_plain_document_as_a_cold_pass_does() {+ let (mut engine, nodes) = linear_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(+ &mut engine,+ sheet,+ ".target { color: rgb(0, 128, 0); width: 10px; } .target::before { content: \"x\"; }",+ );+ add_class(&mut engine, nodes[2], "target");+ start_live(&mut engine, nodes[0]);+ assert_eq!(assert_live_matches_cold(&mut engine, nodes[0]), nodes.len());+ assert!(!live_records_equal(&engine, nodes[1], nodes[2]));++ add_class(&mut engine, nodes[1], "target");+ remove_class(&mut engine, nodes[2], "target");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert!(live_records_equal(&engine, nodes[2], nodes[3]));+ assert!(!live_records_equal(&engine, nodes[1], nodes[2]));+ }++ #[test]+ fn a_guard_change_restyles_a_nested_document_as_a_cold_pass_does() {+ let (mut engine, nodes) = nested_document();+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(+ &mut engine,+ sheet,+ ".guard { color: rgb(0, 0, 255); --size: 4px; } .guard .target { width: var(--size); }",+ );+ add_class(&mut engine, nodes[1], "guard");+ add_class(&mut engine, nodes[3], "target");+ start_live(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);++ remove_class(&mut engine, nodes[1], "guard");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert!(live_records_equal(&engine, nodes[1], nodes[2]));++ add_class(&mut engine, nodes[2], "guard");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert!(!live_records_equal(&engine, nodes[1], nodes[2]));+ }++ #[test]+ fn a_class_change_in_a_shadow_tree_restyles_it_as_a_cold_pass_does() {+ let (mut engine, nodes) = linear_document();+ let scope = TreeScopeID(1);+ let shadow = attach_shadow_tree(&mut engine, nodes[1], scope, 3);+ let document_sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, document_sheet, ".target { color: rgb(255, 0, 0); }");+ let shadow_sheet = add_sheet(&mut engine, scope);+ add_rules(+ &mut engine,+ shadow_sheet,+ ":host { width: 20px; } .target { color: rgb(0, 128, 0); }",+ );+ add_class(&mut engine, shadow[2], "target");+ start_live(&mut engine, nodes[0]);+ let checked = assert_live_matches_cold(&mut engine, nodes[0]);+ assert_eq!(checked, nodes.len() + shadow.len() - 1);++ remove_class(&mut engine, shadow[2], "target");+ add_class(&mut engine, shadow[3], "target");+ add_class(&mut engine, nodes[3], "target");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert!(!live_records_equal(&engine, shadow[3], nodes[3]));+ }++ #[test]+ fn a_shadow_root_matches_no_compound_left_of_a_combinator() {+ let (mut engine, nodes) = linear_document();+ let scope = TreeScopeID(1);+ let shadow = attach_shadow_tree(&mut engine, nodes[1], scope, 2);+ let shadow_sheet = add_sheet(&mut engine, scope);+ add_rules(+ &mut engine,+ shadow_sheet,+ "* > .child { color: rgb(0, 128, 0); } * .descendant { width: 20px; } \+ :not(.absent) > .child { height: 20px; }",+ );+ add_class(&mut engine, shadow[2], "child");+ start_live(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert!(!live_records_equal(&engine, shadow[2], nodes[2]));++ // The top-level element of the shadow tree has the shadow root for its parent and only+ // ancestor, which is not an element and matches nothing.+ remove_class(&mut engine, shadow[2], "child");+ add_class(&mut engine, shadow[1], "child");+ add_class(&mut engine, shadow[1], "descendant");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert!(exact_matches(&engine, shadow[1]).is_empty());+ assert!(live_records_equal(&engine, shadow[1], shadow[2]));++ remove_class(&mut engine, shadow[1], "child");+ add_class(&mut engine, shadow[2], "descendant");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert!(!live_records_equal(&engine, shadow[1], shadow[2]));+ }++ #[test]+ fn a_departure_restyles_an_nth_of_type_document_as_a_cold_pass_does() {+ let (mut engine, nodes) = typed_nth_of_type_document();+ start_live(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert!(!live_records_equal(&engine, nodes[2], nodes[3]));+ let untargeted = live_record(&engine, nodes[1]);++ // Another type leaving moves no position of the target's type.+ engine.record_tree_delta(+ nodes[2],+ Some(relations(Some(nodes[0]), Some(nodes[1]), Some(nodes[3]))),+ None,+ );+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert!(!live_records_equal(&engine, nodes[1], nodes[3]));++ // The same type leaving makes the target the first of its type.+ engine.record_tree_delta(nodes[1], Some(relations(Some(nodes[0]), None, Some(nodes[3]))), None);+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert!(records_equal(&live_record(&engine, nodes[3]), &untargeted));+ }++ #[test]+ fn arrivals_and_departures_restyle_an_nth_child_document_as_a_cold_pass_does() {+ let (mut engine, nodes) = nth_target_document();+ start_live(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert!(!live_records_equal(&engine, nodes[2], nodes[3]));++ // A departure makes the third child the second.+ engine.record_tree_delta(nodes[1], Some(relations(Some(nodes[0]), None, Some(nodes[2]))), None);+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert!(live_records_equal(&engine, nodes[2], nodes[3]));++ // An arrival before both makes the second child the third.+ let inserted = allocate_nodes(&mut engine, 1)[0];+ engine.record_tree_delta(inserted, None, Some(relations(Some(nodes[0]), None, Some(nodes[2]))));+ set_tag(&mut engine, inserted, "div");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ assert!(!live_records_equal(&engine, nodes[2], nodes[3]));+ }+}++/// A declaration block declaring each `(property, important, value)` of `declarations`.+pub(crate) fn declaration_block(+ declarations: &[(u16, bool, crate::css::style_value::StyleValueData)],+) -> crate::css::declaration_block::SharedDeclarationBlock {+ crate::css::declaration_block::DeclarationBlockBuilder {+ properties: declarations+ .iter()+ .map(+ |(property, important, value)| crate::css::declaration_block::DeclaredProperty {+ property_id: *property,+ important: *important,+ value: crate::css::style_value_arc::StyleValueArc::new(value.clone()),+ },+ )+ .collect(),+ custom_properties: Vec::new(),+ }+ .finish()+}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal/cache_audit.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal/cache_audit.rsnew file mode 100644index 00000000000..6e1e845c325--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal/cache_audit.rs@@ -0,0 +1,411 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The audit of what a pass reuses. With `LIBWEB_STYLE_AUDIT_CACHES` set, every element a pass+//! with its caches on gives a record, whether through style sharing, the result cache, a move of+//! its custom properties or a computation reading the group, absolutized value, custom property+//! store and substitution caches of its thread, is styled again from nothing: on a scratch of its+//! own, with every cache off, over the records the pass holds for the elements before it. The+//! element's record and its pseudo-elements' records, the ones from the pseudo-element record cache+//! included, must be the ones that recomputation gives, and the rules it matched the ones that+//! recomputation matches. `report` prints what differs at the end of the pass, and any other value+//! but `0` aborts there.++use super::super::super::*;+use super::super::records::{PseudoElementRecords, Record};+use super::super::self_check::{Mode, describe, pseudo_element_name, record_differences};+use super::{PassContext, Scratch, is_document_element};+use std::sync::Arc;++/// What `LIBWEB_STYLE_AUDIT_CACHES` asks for, which the engine reads once as it starts.+pub(in super::super) fn mode_from_environment() -> Mode {+ match std::env::var("LIBWEB_STYLE_AUDIT_CACHES").as_deref() {+ Err(_) | Ok("" | "0") => Mode::Off,+ Ok("report") => Mode::Report,+ Ok(_) => Mode::Abort,+ }+}++/// What gave an element the record the audit checks.+#[derive(Clone, Copy, Debug, PartialEq, Eq)]+pub(super) enum Reuse {+ SharedStyle,+ ReusedResult,+ MovedCustomProperties,+ /// A computation, reading the caches its thread kept of the computations before it.+ ComputationCaches,+ /// The pseudo-element record cache, for a pseudo-element.+ PseudoElementRecord,+}++impl Reuse {+ const COUNT: usize = 5;++ fn name(self) -> &'static str {+ match self {+ Self::SharedStyle => "style sharing",+ Self::ReusedResult => "the result cache",+ Self::MovedCustomProperties => "a move of its custom properties",+ Self::ComputationCaches => "a computation with the caches of its thread",+ Self::PseudoElementRecord => "the pseudo-element record cache",+ }+ }+}++#[derive(Clone, Default)]+pub(in super::super) struct CacheAudit {+ /// How many records the audit checked, by what gave them.+ checked: [u64; Reuse::COUNT],+ /// How many elements the audit checked nothing of, or nothing of the pseudo-elements of, as+ /// recomputation declined to style them or waited on a font or a random base value.+ declined: u64,+ failures: Vec<String>,+}++impl CacheAudit {+ /// The audit of a thread of a pass over `context`, where the context asks for one and the pass+ /// has caches to audit.+ pub(super) fn for_pass(context: &PassContext<'_>) -> Option<Box<Self>> {+ (context.uses_caches && context.cache_audit != Mode::Off).then(Box::default)+ }++ pub(in super::super) fn add(&mut self, other: Self) {+ for (checked, other) in self.checked.iter_mut().zip(other.checked) {+ *checked += other;+ }+ self.declined += other.declined;+ self.failures.extend(other.failures);+ }++ /// Print what differs from its recomputation to stderr, and abort where `mode` asks to.+ pub(super) fn conclude(&self, mode: Mode) {+ if self.failures.is_empty() {+ return;+ }+ eprintln!(+ "Style cache audit: what a pass reused differs from recomputing it without caches in {} places (live is what the pass holds, cold the recomputation):",+ self.failures.len()+ );+ for failure in &self.failures {+ eprintln!(" {failure}");+ }+ assert!(+ mode != Mode::Abort,+ "a cache gave a record recomputation does not; set LIBWEB_STYLE_AUDIT_CACHES=report to only print the differences"+ );+ }+}++impl Scratch<'_> {+ /// Check the record `context` holds for `node`, which `reuse` gave it, and the records of its+ /// pseudo-elements, against styling it again with every cache off, where the audit is on.+ pub(super) fn audit_caches(&mut self, context: &PassContext<'_>, node: StyleNodeID, reuse: Reuse) {+ let Some(audit) = self.cache_audit.as_deref_mut() else {+ return;+ };+ let Some(live) = context.records.get_shared(node) else {+ return;+ };+ let Some(recomputed) = recompute(context, node) else {+ audit.declined += 1;+ return;+ };+ let cold = &recomputed.record;+ let state = context.state;+ let name_of = |atom: StyleAtomID| state.atoms.name_of(atom).unwrap_or_else(|| format!("atom{}", atom.0));+ let element = || describe(state, node, &name_of);+ audit.checked[reuse as usize] += 1;+ // NB: What an element matched decides its style, so a record differing for other matches+ // than recomputation finds differs for those, whatever the caches gave.+ if let Some(live_matches) = context.records.matches_of(node).filter(|_| context.keeps_matches)+ && live_matches[..] != recomputed.matches[..]+ {+ let only_in = |first: &[u32], second: &[u32]| {+ first+ .iter()+ .filter(|entry| !second.contains(entry))+ .map(|&entry| match context.index.entries.entry(entry as usize).pseudo_kind {+ u8::MAX => entry.to_string(),+ kind => format!("{entry} ({})", pseudo_element_name(kind)),+ })+ .collect::<Vec<_>>()+ .join(", ")+ };+ audit.failures.push(format!(+ "{}, from {}: live matched other rule entries than cold, live alone [{}], cold alone [{}]",+ element(),+ reuse.name(),+ only_in(live_matches, &recomputed.matches),+ only_in(&recomputed.matches, live_matches)+ ));+ }+ let differences = record_differences(live, cold);+ if !differences.is_empty() {+ audit.failures.push(format!(+ "{}, from {}: live differs from cold in {}",+ element(),+ reuse.name(),+ differences.join(", ")+ ));+ }+ // NB: An element whose pseudo-element waits on a font waits in the pass too, which styles+ // it again once the font resolved.+ let Some(cold_pseudo_elements) = &recomputed.pseudo_elements else {+ audit.declined += 1;+ return;+ };+ let live_pseudo_elements = context.records.pseudo_element_records(node);+ let kinds = |records: &[(u8, Arc<Record>)]| records.iter().map(|(kind, _)| *kind).collect::<Vec<_>>();+ if kinds(live_pseudo_elements) != kinds(cold_pseudo_elements) {+ let names = |kinds: Vec<u8>| kinds.into_iter().map(pseudo_element_name).collect::<Vec<_>>();+ audit.failures.push(format!(+ "{}, from {}: live holds the pseudo-elements {:?}, cold computes {:?}",+ element(),+ reuse.name(),+ names(kinds(live_pseudo_elements)),+ names(kinds(cold_pseudo_elements))+ ));+ return;+ }+ for ((kind, live), (_, cold)) in live_pseudo_elements.iter().zip(cold_pseudo_elements) {+ let reuse = match self.pseudo_element_cache_hits.contains(kind) {+ true => Reuse::PseudoElementRecord,+ false => reuse,+ };+ audit.checked[reuse as usize] += u64::from(reuse == Reuse::PseudoElementRecord);+ let differences = record_differences(live, cold);+ if !differences.is_empty() {+ audit.failures.push(format!(+ "{} of {}, from {}: live differs from cold in {}",+ pseudo_element_name(*kind),+ element(),+ reuse.name(),+ differences.join(", ")+ ));+ }+ }+ }+}++/// What an element styled from nothing comes to.+struct Recomputed {+ record: Arc<Record>,+ /// None where one of them waits on a font or a random base value.+ pseudo_elements: Option<PseudoElementRecords>,+ /// The entries of the rule index the element matched.+ matches: Vec<u32>,+}++/// The record of `node` and those of its pseudo-elements, styled from nothing on a scratch of+/// their own with every cache off, over the records `context` holds for the elements before it,+/// the pseudo-elements over the one it holds for `node`. None where that declines to style the+/// element, or waits on a font or a random base value.+fn recompute(context: &PassContext<'_>, node: StyleNodeID) -> Option<Recomputed> {+ let state = context.state;+ // NB: The pass computes the document element against the root font it held before, and its+ // pseudo-elements and every element after it against the one it computes.+ let is_document_element = is_document_element(state, node);+ let reference = PassContext {+ uses_caches: false,+ ..PassContext::new(+ state,+ context.index,+ context.initial,+ context.records,+ context.held_root_font,+ )+ };+ let note_root_font = || {+ if let Some(&root_font) = context.root_font.get() {+ let _ = reference.root_font.set(root_font);+ }+ };+ if !is_document_element {+ note_root_font();+ }+ let mut scratch = Scratch::new(&reference);+ let facts = state.projection.facts(node)?;+ scratch.enter_parent(&reference, state.projection.parent(node));+ scratch+ .matcher+ .match_element(node, facts, &scratch.filter, &mut scratch.matches)+ .ok()?;+ scratch.apply_container_gates(&reference, node, false);+ if !scratch.cascade_element(&reference, node, state.backed_host_pseudo_element(node)) {+ return None;+ }+ let (record, _) = scratch.compute(&reference, node).ok()?;+ if is_document_element {+ note_root_font();+ }+ let pseudo_elements = scratch+ .styled_pseudo_elements(&reference, node)+ .map(|(pseudo_elements, _)| pseudo_elements);+ Some(Recomputed {+ record,+ pseudo_elements: pseudo_elements.filter(|_| scratch.requested() == (0, 0)),+ matches: scratch.matches.iter().map(|matched| matched.entry).collect(),+ })+}++#[cfg(test)]+pub(super) mod tests {+ use super::super::super::test_support::*;+ use super::*;++ /// `root -> [a, b, c, d -> e -> f -> g]`, every element but the root an `.item`, whose style+ /// and `::before` every one shares or reuses from another but the first.+ fn document_of_items() -> (StyleEngine, Vec<StyleNodeID>) {+ let mut engine = hosted_engine();+ let nodes = allocate_nodes(&mut engine, 8);+ engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));+ for index in 1..5 {+ let previous = (index > 1).then(|| nodes[index - 1]);+ engine.record_tree_delta(nodes[index], None, Some(relations(Some(nodes[0]), previous, None)));+ }+ for index in 5..8 {+ engine.record_tree_delta(nodes[index], None, Some(relations(Some(nodes[index - 1]), None, None)));+ }+ engine.set_element_adjustment_facts(nodes[0], bridge::element_adjustment_fact::IS_DOCUMENT_ELEMENT);+ for &node in &nodes {+ set_tag(&mut engine, node, "div");+ }+ for &node in &nodes[1..] {+ add_class(&mut engine, node, "item");+ }+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(+ &mut engine,+ sheet,+ ".item { color: rgb(0, 128, 0); width: 10px; --name: 1; } .item::before { content: \"x\"; }",+ );+ (engine, nodes)+ }++ #[test]+ fn what_live_style_reuses_is_what_it_recomputes() {+ let (mut engine, nodes) = document_of_items();+ start_live(&mut engine, nodes[0]);+ // NB: The engine starting again keeps the audit it started with, here one reporting+ // what differs.+ engine+ .retained+ .live_style+ .as_mut()+ .expect("the engine runs")+ .cache_audit = Mode::Report;+ start_live(&mut engine, nodes[0]);+ add_class(&mut engine, nodes[2], "other");+ remove_class(&mut engine, nodes[6], "item");+ run_style_update(&mut engine, nodes[0]);+ let audit = &engine+ .retained+ .live_style+ .as_ref()+ .expect("the engine runs")+ .cache_audits;+ assert_eq!(audit.failures, Vec::<String>::new());+ for reuse in [+ Reuse::SharedStyle,+ Reuse::ReusedResult,+ Reuse::ComputationCaches,+ Reuse::PseudoElementRecord,+ ] {+ assert_ne!(+ audit.checked[reuse as usize],+ 0,+ "the audit checks records from {}",+ reuse.name()+ );+ }+ }++ /// Style `nodes` in turn on one scratch with its caches on, having `poison` seed its caches+ /// before the last one, and answer what the audit found.+ fn poisoned_pass(+ engine: &mut StyleEngine,+ nodes: &[StyleNodeID],+ poison: impl FnOnce(&mut Scratch<'_>, &PassContext<'_>),+ ) -> CacheAudit {+ let initial = engine+ .computed_initial(nodes[0])+ .expect("the document has initial values");+ let state = &engine.retained;+ let index = super::super::super::rules::RuleIndex::build(&state.rules, state.process_rule_indexes());+ let mut cells = super::super::super::records::RecordCells::default();+ cells.reserve(state.projection.element_slot_count());+ let records = super::super::super::records::Records::new(state, &cells, None);+ let context = PassContext {+ cache_audit: Mode::Report,+ ..PassContext::new(state, &index, &initial, &records, None)+ };+ let mut scratch = Scratch::new(&context);+ let (last, first) = nodes.split_last().expect("there are elements to style");+ for &node in first {+ scratch.style_element(&context, node, None, super::super::PARENT_CHANGED);+ }+ poison(&mut scratch, &context);+ scratch.style_element(&context, *last, None, super::super::PARENT_CHANGED);+ *scratch.cache_audit.take().expect("the scratch audits")+ }++ #[test]+ fn a_shared_style_that_differs_from_recomputation_is_reported() {+ let (mut engine, nodes) = document_of_items();+ start_live(&mut engine, nodes[0]);+ let audit = poisoned_pass(&mut engine, &nodes[..3], |scratch, context| {+ // Seed a candidate the second item agrees with, holding the root's record.+ let state = context.state;+ let facts = state.projection.facts(nodes[2]).unwrap();+ let key = super::super::super::sharing::key_of(state, context.index, context.records, nodes[2], facts)+ .expect("the item can share");+ let wrong = context.records.get_shared(nodes[0]).unwrap().clone();+ scratch.sharing = Default::default();+ scratch.sharing.insert(key, wrong, nodes[1], Default::default());+ });+ assert_eq!(audit.checked[Reuse::SharedStyle as usize], 1);+ // NB: The `::before` the item shares recomputes over the record the item holds.+ assert_eq!(audit.failures.len(), 2, "{:?}", audit.failures);+ assert!(audit.failures[1].starts_with("::before of "), "{:?}", audit.failures);+ let failure = &audit.failures[0];+ for part in [+ &format!(+ "(node {}), from style sharing: live differs from cold in ",+ nodes[2].raw()+ )[..],+ "width: live auto, cold 10px",+ "custom properties",+ ] {+ assert!(failure.contains(part), "{failure} names {part}");+ }+ }++ #[test]+ fn a_pseudo_element_record_that_differs_from_recomputation_is_reported() {+ let (mut engine, nodes) = document_of_items();+ start_live(&mut engine, nodes[0]);+ let audit = poisoned_pass(&mut engine, &nodes[..3], |scratch, context| {+ // Have every pseudo-element record the scratch keeps be the root's record.+ let wrong = context.records.get_shared(nodes[0]).unwrap().clone();+ for record in scratch.pseudo_elements.values_mut() {+ *record = wrong.clone();+ }+ scratch.sharing = Default::default();+ });+ assert_eq!(audit.checked[Reuse::PseudoElementRecord as usize], 1);+ assert_eq!(audit.failures.len(), 1, "{:?}", audit.failures);+ let failure = &audit.failures[0];+ // NB: The atoms of a test's engine name no strings the audit could show.+ assert!(failure.starts_with("::before of <"), "{failure}");+ assert!(+ failure.contains(&format!(+ "(node {}), from the pseudo-element record cache: live differs from cold in ",+ nodes[2].raw()+ )),+ "{failure}"+ );+ }+}diff --git a/Libraries/LibWeb/Rust/src/css/style/tests.rs b/Libraries/LibWeb/Rust/src/css/style/tests.rsindex 9c5769cae44..e877ef22551 100644--- a/Libraries/LibWeb/Rust/src/css/style/tests.rs+++ b/Libraries/LibWeb/Rust/src/css/style/tests.rs@@ -4,22 +4,9 @@* SPDX-License-Identifier: BSD-2-Clause*/-use super::batch_matcher::insert_scope_rule;-use super::container_queries::PublishedContainerVerdict;-use super::index::CandidateEntries;-use super::index::ParentDispatchFacts;-use super::index::SelectorPostingKey;-use super::index::StateSet;-use super::index::unwritten_declarations;use super::instrumentation::Counter;-use super::program::DeclarationBlockID;-use super::program::SelectorProgramID;-use super::transaction::InputKind;-use super::tree::PseudoElementKind;-use super::tree::PseudoElementTarget;+use super::pipeline::rule_store::{DeclarationBlockID, SheetListStart};use super::*;-use crate::css::property_metadata::property_id;-use crate::css::style_value::{RetainedStyleValueData, StyleValueData};fn native_rules(source: &str) -> std::rc::Rc<crate::css::rule::NativeRuleList> {use crate::css::css_tokenizer::TokenizerInput;@@ -32,138 +19,7 @@ fn native_rules(source: &str) -> std::rc::Rc<crate::css::rule::NativeRuleList> {))}-impl StyleEngine {- /// Read one answer the preceding style transaction published, as a cascade over it would.- pub(super) fn consume_published_match_answer(&mut self, node: StyleNodeID) -> Option<Vec<RuleMatch>> {- let retained = &mut self.retained;- let mut traversal = retained.batch_matching_traversal.take();- let effects = match traversal.as_mut() {- Some(traversal) => &mut traversal.answer_effects,- None => &mut retained.published_match_answers.answer_effects,- };- let mut effects = std::mem::take(effects);- let result = retained.consume_published_match_answer_in_traversal(&mut effects, node, traversal.as_deref());- match traversal.as_mut() {- Some(traversal) => traversal.answer_effects = effects,- None => retained.published_match_answers.answer_effects = effects,- }- retained.batch_matching_traversal = traversal;- result- }-}--#[test]-fn native_selector_publication_and_replacement_outlive_the_source() {- use super::bridge::{BoundScopeChain, publish_style_rule, publish_style_rule_selectors};- let (mut engine, nodes) = linear_document();- let name = ak::Utf16FlyString::from_utf16(&"色".encode_utf16().collect::<Vec<_>>());- let name = engine.intern_atom(name.raw_identity());- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(name));- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let mut published = 0;- for (text, matches) in [(".別, .色 {}", true), (".別 {}", false), (".色 {}", true)] {- let rules = native_rules(text);- let rule = rules.rule_at(0);- let bound = rule.matching_selectors();- let selectors: Vec<_> = bound.selectors.iter().map(|selector| selector.as_ref()).collect();- if published == 0 {- published = publish_style_rule(- &mut engine,- sheet.0 + 1,- 0,- &selectors,- NamespaceScope::default(),- &BoundScopeChain::default(),- );- } else {- publish_style_rule_selectors(- &mut engine,- published,- &selectors,- NamespaceScope::default(),- &BoundScopeChain::default(),- );- }- drop(bound);- drop(rule);- drop(rules);- discard_transaction(&mut engine);- let answer = engine.match_element(nodes[1]).unwrap();- assert_eq!(!answer.is_empty(), matches, "{text}");- if matches {- assert_eq!(answer.len(), 1);- }- }-}--#[test]-fn native_scope_publication_outlives_the_rule_graph() {- use super::bridge::{BoundScopeChain, publish_style_rule, publish_style_rule_selectors};- use crate::css::rule::{NativeRuleType, rust_rule_list_count};- for (source, matches) in [- ("@scope (.根) {}", true),- ("@scope (.別) {}", false),- ("@scope {}", true),- ("@scope (.根) to (.限) {}", false),- ("@scope (.根) { @scope (.別) {} }", false),- (":has(.根) { @scope (:has(&)) {} }", false),- ("@import 'sheet.css' scope((.根));", true),- ("@import 'sheet.css' scope((.根) to (.限));", false),- ] {- let (mut engine, nodes) = linear_document();- for (node, text) in [(nodes[0], "根"), (nodes[1], "限")] {- let name = ak::Utf16FlyString::from_utf16(&text.encode_utf16().collect::<Vec<_>>());- let name = engine.intern_atom(name.raw_identity());- add_feature(&mut engine, node, LocalFeatureKey::Class(name));- }- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let mut published = 0;- for _ in 0..2 {- let rules = native_rules(source);- let mut rule = rules.rule_at(0);- let mut scope = BoundScopeChain::default();- loop {- if matches!(- crate::css::rule::rust_rule_type(&rule),- NativeRuleType::Scope | NativeRuleType::Import- ) {- let start = rule.scope_start_selectors();- let end = rule.scope_end_selectors();- scope.push(start.as_deref(), end.as_deref(), nodes[0].raw());- }- let children = rule.child_rules().map(|children| &**children);- let Some(children) = children.filter(|children| rust_rule_list_count(children) > 0) else {- break;- };- rule = children.rule_at(0);- }- let universal = native_rules("* {}");- let bound = universal.rule_at(0).matching_selectors();- let selectors: Vec<_> = bound.selectors.iter().map(|selector| selector.as_ref()).collect();- if published == 0 {- published = publish_style_rule(- &mut engine,- sheet.0 + 1,- 0,- &selectors,- NamespaceScope::default(),- &scope,- );- } else {- publish_style_rule_selectors(&mut engine, published, &selectors, NamespaceScope::default(), &scope);- }- drop(bound);- drop(universal);- drop(scope);- drop(rule);- drop(rules);- discard_transaction(&mut engine);- assert_eq!(!engine.match_element(nodes[1]).unwrap().is_empty(), matches, "{source}");- }- }-}+impl StyleEngine {}#[test]fn native_declaration_publication_reuses_values_and_observes_live_mutation() {@@ -172,17 +28,15 @@ fn native_declaration_publication_reuses_values_and_observes_live_mutation() {DeclarationBlock, rust_declaration_block_replace, rust_declaration_block_retain,};let (mut engine, _) = linear_document();- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);+ let sheet = engine.add_sheet(CascadeOrigin::Author);engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);let first = native_rules("* { color: #14181c; }");- let bound = first.rule_at(0).matching_selectors();- let selectors: Vec<_> = bound.selectors.iter().map(|selector| selector.as_ref()).collect();+ let bound = first.rule_at(0).style_rule().selectors();let rule = publish_style_rule(&mut engine,sheet.0 + 1,0,- &selectors,- NamespaceScope::default(),+ &bound.selectors,&BoundScopeChain::default(),);let mut first = DeclarationBlock::new(first.rule_at(0).cascade_declarations().unwrap());@@ -199,348 +53,12 @@ fn native_declaration_publication_reuses_values_and_observes_live_mutation() {);let callbacks = crate::css::ffi_stats::CPP_CALLBACK_COUNT.get();assert!(!publish_rule_declarations(&mut engine, rule, &first.data()));- let reused = engine.counters().get(Counter::SpecifiedValuesReused);assert!(!publish_rule_declarations(&mut engine, rule, &second));- assert_eq!(engine.counters().get(Counter::SpecifiedValuesReused), reused + 1);rust_declaration_block_replace(&mut first, &transitions);assert!(publish_rule_declarations(&mut engine, rule, &retained.data()));assert_eq!(crate::css::ffi_stats::CPP_CALLBACK_COUNT.get(), callbacks);}-#[test]-fn environment_memo_retains_its_written_value_keys() {- let mut environments = custom_property_environments::CustomPropertyEnvironments::default();- let written = RetainedStyleValueData::from_owned(StyleValueData::Number { value: 1.25 });- let written_pointer = written.pointer();- let inputs = custom_property_environments::EnvironmentInputs {- parent: 0,- registration_generation: 0,- cascaded: Box::new([custom_property_environments::CascadedCustomProperty {- name: StyleAtomID(1),- important: false,- written_value: written_pointer as usize,- }]),- };- environments.remember(inputs, 1, vec![written.clone_retained()]);-- // SAFETY: `written` and the memo both retain the value while this temporary Arc observes its- // strong count.- unsafe { std::sync::Arc::increment_strong_count(written_pointer) };- let observer = unsafe { std::sync::Arc::from_raw(written_pointer) };- assert_eq!(std::sync::Arc::strong_count(&observer), 3);-}--#[test]-fn substitution_memo_retains_its_written_value_key() {- let mut environments = custom_property_environments::CustomPropertyEnvironments::default();- let written = RetainedStyleValueData::from_owned(StyleValueData::Number { value: 1.25 });- let written_pointer = written.pointer();- let value = RetainedStyleValueData::from_owned(StyleValueData::Keyword { keyword: 2 });- environments.remember_substitution(written.clone_retained(), 1, 0, value);-- // SAFETY: `written` and the memo both retain the value while this temporary Arc observes its- // strong count.- unsafe { std::sync::Arc::increment_strong_count(written_pointer) };- let observer = unsafe { std::sync::Arc::from_raw(written_pointer) };- assert_eq!(std::sync::Arc::strong_count(&observer), 3);-}--#[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());-}--#[test]-fn pending_paint_only_local_inputs_preserve_layout_geometry() {- let (mut engine, nodes) = linear_document();- let paint_only = StyleAtomID(200);- let rule = add_target_rule(&mut engine, StyleSheetObjectID(1), paint_only);- engine.set_rule_declared_properties(rule, &[(property_id::BACKGROUND_COLOR, false)]);- discard_transaction(&mut engine);-- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(paint_only));- assert!(!engine.pending_transaction_may_affect_layout_geometry());- assert!(engine.has_pending_transaction());-}--#[test]-fn pending_geometry_inputs_see_custom_declaration_changes() {- let (mut engine, nodes) = linear_document();- let target = StyleAtomID(200);- let rule = add_target_rule(&mut engine, StyleSheetObjectID(1), target);- engine.set_rule_declared_properties(rule, &[(property_id::BACKGROUND_COLOR, false)]);- discard_transaction(&mut engine);- prepare_route_liveness(&mut engine);-- set_rule_declared_properties_beside_a_custom_property(&mut engine, rule, &[(property_id::BACKGROUND_COLOR, false)]);- discard_transaction(&mut engine);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(target));- assert!(engine.pending_transaction_may_affect_layout_geometry());- discard_transaction(&mut engine);- prepare_route_liveness(&mut engine);-- engine.set_rule_declared_properties(rule, &[(property_id::BACKGROUND_COLOR, false)]);- discard_transaction(&mut engine);- add_feature(&mut engine, nodes[2], LocalFeatureKey::Class(target));- assert!(!engine.pending_transaction_may_affect_layout_geometry());-}--#[test]-fn pending_inputs_see_a_rule_whose_declarations_came_to_move_geometry() {- let (mut engine, nodes) = linear_document();- let target = StyleAtomID(200);- let rule = add_target_rule(&mut engine, StyleSheetObjectID(1), target);- engine.set_rule_declared_properties(rule, &[(property_id::BACKGROUND_COLOR, false)]);- discard_transaction(&mut engine);- prepare_route_liveness(&mut engine);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(target));- assert!(!engine.pending_transaction_may_affect_layout_geometry());- discard_transaction(&mut engine);-- // The view prepared for the paint-only rule does not answer for the rule it became.- engine.set_rule_declared_properties(rule, &[(property_id::WIDTH, false)]);- discard_transaction(&mut engine);- add_feature(&mut engine, nodes[2], LocalFeatureKey::Class(target));- assert!(engine.pending_transaction_may_affect_layout_geometry());-}--#[test]-fn pending_layout_local_inputs_may_change_geometry() {- for property in [property_id::WIDTH, property_id::TRANSFORM, property_id::COLOR] {- let (mut engine, nodes) = linear_document();- let target = StyleAtomID(200);- let rule = add_target_rule(&mut engine, StyleSheetObjectID(1), target);- engine.set_rule_declared_properties(rule, &[(property, false)]);- discard_transaction(&mut engine);-- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(target));- assert!(engine.pending_transaction_may_affect_layout_geometry());- }-}--fn test_nth_position(argument: &str, of_type: bool) -> selector::NthPosition {- let (step, offset) = match argument.split_once('n') {- Some((step, offset)) => {- let step = step- .parse()- .unwrap_or_else(|_| panic!("invalid test an+b step: {argument}"));- let offset = offset.strip_prefix('+').unwrap_or(offset);- let offset = if offset.is_empty() {- 0- } else {- offset- .parse()- .unwrap_or_else(|_| panic!("invalid test an+b offset: {argument}"))- };- (step, offset)- }- None => (- 0,- argument- .parse()- .unwrap_or_else(|_| panic!("invalid test an+b position: {argument}")),- ),- };- selector::NthPosition {- step,- offset,- from_end: false,- of_selector: None,- of_type,- }-}--fn test_selector_program_with_metadata(- selector_text: &str,- atoms: &[(&str, StyleAtomID)],- specificity: Option<Specificity>,- pseudo_element: Option<PseudoElementTarget>,-) -> selector::SelectorProgram {- let mut builder = selector::SelectorProgramBuilder::new();- for complex_selector_text in selector_text.split(',') {- let mut complex_selector = None;- let mut combinator = None;- for compound_text in complex_selector_text.trim().split_ascii_whitespace() {- if matches!(compound_text, ">" | "+" | "~") {- assert!(- complex_selector.is_some(),- "test selector starts with a combinator: {selector_text}"- );- assert!(- combinator.replace(compound_text).is_none(),- "test selector has adjacent combinators: {selector_text}"- );- continue;- }- let mut operands = Vec::new();- let relation = complex_selector.map(|left| match combinator.take() {- None => builder.push_ancestor(left),- Some(">") => builder.push(selector::SelectorOp::Parent(left)),- Some("+") => builder.push(selector::SelectorOp::PreviousSibling(left)),- Some("~") => builder.push(selector::SelectorOp::PrecedingSibling(left)),- Some(_) => unreachable!(),- });- let mut remaining = compound_text;- if let Some(rest) = remaining.strip_prefix('*') {- operands.push(builder.push_feature(selector::FeatureTest::AnyElement));- remaining = rest;- }- while let Some(rest) = remaining.strip_prefix('.') {- let name_length = rest- .find(|character: char| !character.is_ascii_alphanumeric() && character != '-' && character != '_')- .unwrap_or(rest.len());- assert!(- name_length != 0,- "test selector has an empty class name: {selector_text}"- );- let (name, rest) = rest.split_at(name_length);- let atom = atoms- .iter()- .find_map(|&(candidate, atom)| (candidate == name).then_some(atom))- .unwrap_or_else(|| panic!("test selector names an unbound class: {name}"));- operands.push(builder.push_feature(selector::FeatureTest::Class(atom)));- remaining = rest;- }- let pseudo_class = remaining;- if let Some(argument) = pseudo_class- .strip_prefix(":nth-child(")- .and_then(|argument| argument.strip_suffix(')'))- {- operands.push(builder.push(selector::SelectorOp::NthPosition(test_nth_position(argument, false))));- remaining = "";- } else if let Some(argument) = pseudo_class- .strip_prefix(":nth-of-type(")- .and_then(|argument| argument.strip_suffix(')'))- {- operands.push(builder.push(selector::SelectorOp::NthPosition(test_nth_position(argument, true))));- remaining = "";- } else if let Some(name) = pseudo_class- .strip_prefix(":state(")- .and_then(|name| name.strip_suffix(')'))- {- let state = atoms- .iter()- .find_map(|&(candidate, atom)| (candidate == name).then_some(atom))- .unwrap_or_else(|| panic!("test selector names an unbound state: {name}"));- operands.push(builder.push(selector::SelectorOp::ValueState {- kind: selector::ValueStateTestKind::CustomState,- value: state,- }));- remaining = "";- } else if let Some(name) = pseudo_class- .strip_prefix(":not(:state(")- .and_then(|name| name.strip_suffix("))"))- {- let state = atoms- .iter()- .find_map(|&(candidate, atom)| (candidate == name).then_some(atom))- .unwrap_or_else(|| panic!("test selector names an unbound state: {name}"));- let state = builder.push(selector::SelectorOp::ValueState {- kind: selector::ValueStateTestKind::CustomState,- value: state,- });- operands.push(builder.push(selector::SelectorOp::Not(state)));- remaining = "";- }- assert!(- remaining.is_empty(),- "unsupported test selector syntax: {selector_text}"- );- assert!(- !operands.is_empty(),- "test selector has an empty compound: {selector_text}"- );- if let Some(relation) = relation {- operands.push(relation);- }- complex_selector = Some(builder.push_compound(&operands));- }-- assert!(- combinator.is_none(),- "test selector ends with a combinator: {selector_text}"- );- let root = complex_selector.unwrap_or_else(|| panic!("test selector is empty"));- let entry = builder.push_entry_for_pseudo(root, pseudo_element);- if let Some(specificity) = specificity {- builder.set_entry_specificity(entry, specificity);- }- }- builder.finish()-}--fn test_selector_program(selector_text: &str, atoms: &[(&str, StyleAtomID)]) -> selector::SelectorProgram {- test_selector_program_with_metadata(selector_text, atoms, None, None)-}--fn test_class_selector_program(- selector_text: &str,- atoms: &[(&str, StyleAtomID)],- pseudo_element: Option<PseudoElementTarget>,-) -> selector::SelectorProgram {- test_selector_program_with_metadata(- selector_text,- atoms,- Some(Specificity {- classes: 1,- ..Specificity::default()- }),- pseudo_element,- )-}--#[test]-fn test_selector_parser_builds_class_descendant_selectors() {- let guard = StyleAtomID(1);- let also = StyleAtomID(2);- let target_atom = StyleAtomID(3);- let parsed = test_selector_program(- ".guard.also .target, .target",- &[("guard", guard), ("also", also), ("target", target_atom)],- );-- let mut builder = selector::SelectorProgramBuilder::new();- let guard = builder.push_feature(selector::FeatureTest::Class(guard));- let also = builder.push_feature(selector::FeatureTest::Class(also));- let ancestor = builder.push_compound(&[guard, also]);- let ancestor = builder.push_ancestor(ancestor);- let target = builder.push_feature(selector::FeatureTest::Class(target_atom));- let root = builder.push_compound(&[target, ancestor]);- builder.push_entry(root);- let target = builder.push_feature(selector::FeatureTest::Class(target_atom));- builder.push_entry(target);-- assert!(parsed == builder.finish());-}--fn prepare_empty_transaction_fact_view(engine: &mut StyleEngine, root: StyleNodeID) {- let mut transaction = engine.take_transaction();- assert!(transaction.is_empty(), "test setup left a transaction pending");- let view = engine.transaction_fact_view_for(&mut transaction, root, &ImpactRegions::new());- engine.release_transaction(transaction);- engine.transaction_fact_view = Some(view);-}-fn add_feature(engine: &mut StyleEngine, node: StyleNodeID, feature: LocalFeatureKey) {engine.record_input(InputKey::LocalFeature(node, feature),@@ -549,14 +67,6 @@ fn add_feature(engine: &mut StyleEngine, node: StyleNodeID, feature: LocalFeatur);}-fn remove_feature(engine: &mut StyleEngine, node: StyleNodeID, feature: LocalFeatureKey) {- engine.record_input(- InputKey::LocalFeature(node, feature),- InputValue::Feature(FeatureValue::Present),- InputValue::Feature(FeatureValue::Absent),- );-}-fn set_atom_feature(engine: &mut StyleEngine, node: StyleNodeID, feature: LocalFeatureKey, atom: StyleAtomID) {engine.record_input(InputKey::LocalFeature(node, feature),@@ -565,278 +75,11 @@ fn set_atom_feature(engine: &mut StyleEngine, node: StyleNodeID, feature: LocalF);}-fn prepare_route_liveness(engine: &mut StyleEngine) {- let retained = &mut engine.retained;- std::sync::Arc::get_mut(&mut retained.routing)- .expect("routing is not shared outside a planning epoch")- .prepare_route_liveness(&retained.program, &retained.programs);-}--/// Take a style transaction and every later wave of its pass, as the host does when it installs-/// each wave; nothing is installed here.-fn take_every_wave(- engine: &mut StyleEngine,- root: StyleNodeID,- mut emit: impl FnMut(StyleTransactionVersion, ProgramVersion, &[PublishedStyleDeltaRecord]),-) -> bool {- let scoped = engine.take_style_transaction(root, &mut emit);- while engine.host.suspended_style_pass.is_some() {- engine.take_style_transaction(root, &mut emit);- }- scoped-}-pub(super) fn discard_transaction(engine: &mut StyleEngine) {let transaction = engine.take_transaction();engine.release_transaction(transaction);}-#[test]-fn attribute_changes_publish_one_name_route() {- let node = StyleNodeID::element(1);- let name = StyleAtomID(10);- let old_value = StyleAtomID(20);- let new_value = StyleAtomID(21);- let changed = NormalizedInput {- key: InputKey::LocalFeature(node, LocalFeatureKey::Attribute(name)),- old: InputValue::Feature(FeatureValue::Atom(old_value)),- new: InputValue::Feature(FeatureValue::Atom(new_value)),- };-- assert_eq!(- routing_keys_for_input(&changed).as_slice(),- [RoutingKey::AttributeName(name)]- );-- let added = NormalizedInput {- old: InputValue::Feature(FeatureValue::Absent),- new: InputValue::Feature(FeatureValue::Atom(new_value)),- ..changed- };- assert_eq!(- routing_keys_for_input(&added).as_slice(),- [RoutingKey::AttributeName(name)]- );-}--#[test]-fn unchanged_attribute_value_truth_skips_descendant_routing() {- let (mut engine, nodes) = nested_document();- let attribute_name = StyleAtomID(200);- let old_value = StyleAtomID(201);- let target = StyleAtomID(202);- let new_value = StyleAtomID(203);-- let mut builder = selector::SelectorProgramBuilder::new();- let (value_offset, value_length) = builder.push_literal(&[u16::from(b'a')]);- let attribute = builder.push_feature(selector::FeatureTest::Attribute(selector::AttributeTest {- name: attribute_name,- any_namespace: false,- folded: attribute_name,- fold_in_namespace: StyleAtomID::NONE,- operator: selector::AttributeOperator::Prefix,- value_atom: StyleAtomID::NONE,- value_offset,- value_length,- case: selector::AttributeCase::Sensitive,- }));- let ancestor = builder.push_ancestor(attribute);- let target_test = builder.push_feature(selector::FeatureTest::Class(target));- let subject = builder.push_compound(&[target_test, ancestor]);- builder.push_entry(subject);- let program = engine.programs.add(builder.finish());- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);-- engine.set_attribute_value_text(old_value, &[u16::from(b'a'), u16::from(b'b')]);- engine.set_attribute_value_text(new_value, &[u16::from(b'a'), u16::from(b'c')]);- engine.record_input(- InputKey::LocalFeature(nodes[1], LocalFeatureKey::Attribute(attribute_name)),- InputValue::Feature(FeatureValue::Absent),- InputValue::Feature(FeatureValue::Atom(old_value)),- );- add_feature(&mut engine, nodes[3], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- engine.record_input(- InputKey::LocalFeature(nodes[1], LocalFeatureKey::Attribute(attribute_name)),- InputValue::Feature(FeatureValue::Atom(old_value)),- InputValue::Feature(FeatureValue::Atom(new_value)),- );- let skipped_before = engine.counters().get(Counter::OriginTruthRoutesSkipped);- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert!(planned.is_empty());- assert_eq!(- engine.counters().get(Counter::OriginTruthRoutesSkipped) - skipped_before,- 1- );-}--fn assert_attribute_origin_route_fires(- operator: selector::AttributeOperator,- value_atom: StyleAtomID,- literal: &[u16],- old: FeatureValue,- new: FeatureValue,- old_text: Option<&[u16]>,- new_text: Option<&[u16]>,-) {- let (mut engine, nodes) = nested_document();- let attribute_name = StyleAtomID(200);- let target = StyleAtomID(201);- let mut builder = selector::SelectorProgramBuilder::new();- let (value_offset, value_length) = builder.push_literal(literal);- let attribute = builder.push_feature(selector::FeatureTest::Attribute(selector::AttributeTest {- name: attribute_name,- any_namespace: false,- folded: attribute_name,- fold_in_namespace: StyleAtomID::NONE,- operator,- value_atom,- value_offset,- value_length,- case: selector::AttributeCase::Sensitive,- }));- let ancestor = builder.push_ancestor(attribute);- let target_test = builder.push_feature(selector::FeatureTest::Class(target));- let subject = builder.push_compound(&[target_test, ancestor]);- builder.push_entry(subject);- let program = engine.programs.add(builder.finish());- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);-- if let (FeatureValue::Atom(atom), Some(text)) = (old, old_text) {- engine.set_attribute_value_text(atom, text);- }- if let (FeatureValue::Atom(atom), Some(text)) = (new, new_text) {- engine.set_attribute_value_text(atom, text);- }- if old != FeatureValue::Absent {- engine.record_input(- InputKey::LocalFeature(nodes[1], LocalFeatureKey::Attribute(attribute_name)),- InputValue::Feature(FeatureValue::Absent),- InputValue::Feature(old),- );- }- add_feature(&mut engine, nodes[3], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- engine.record_input(- InputKey::LocalFeature(nodes[1], LocalFeatureKey::Attribute(attribute_name)),- InputValue::Feature(old),- InputValue::Feature(new),- );- let fired_before = engine.counters().get(Counter::OriginTruthRoutesFired);- let skipped_before = engine.counters().get(Counter::OriginTruthRoutesSkipped);- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert!(planned.contains(&nodes[3].raw()));- assert_eq!(engine.counters().get(Counter::OriginTruthRoutesFired) - fired_before, 1);- assert_eq!(- engine.counters().get(Counter::OriginTruthRoutesSkipped) - skipped_before,- 0- );-}--#[test]-fn attribute_presence_truth_flip_fires_descendant_routing() {- assert_attribute_origin_route_fires(- selector::AttributeOperator::Presence,- StyleAtomID::NONE,- &[],- FeatureValue::Absent,- FeatureValue::Atom(StyleAtomID(202)),- None,- None,- );-}--#[test]-fn attribute_exact_value_truth_flip_fires_descendant_routing() {- assert_attribute_origin_route_fires(- selector::AttributeOperator::Exact,- StyleAtomID(203),- &[],- FeatureValue::Atom(StyleAtomID(202)),- FeatureValue::Atom(StyleAtomID(203)),- None,- None,- );-}--#[test]-fn attribute_text_truth_flip_fires_descendant_routing() {- assert_attribute_origin_route_fires(- selector::AttributeOperator::Prefix,- StyleAtomID::NONE,- &[u16::from(b'x')],- FeatureValue::Atom(StyleAtomID(202)),- FeatureValue::Atom(StyleAtomID(203)),- Some(&[u16::from(b'a'), u16::from(b'b')]),- Some(&[u16::from(b'x'), u16::from(b'c')]),- );-}--fn published_match_answer(node: u32, cascade_input: Option<u32>, match_count: usize) -> PublishedMatchAnswer {- let rule_match = RuleMatch {- node: StyleNodeID::element(node),- pseudo_element: None,- rule: RuleID(1),- program: SelectorProgramID(1),- entry: 0,- cascade_order: 0,- specificity: Specificity::default(),- tree_scope: TreeScopeID::DOCUMENT,- scope_proximity: u32::MAX,- };- PublishedMatchAnswer {- node: StyleNodeID::element(node),- cascade_input: cascade_input.map(MatchAnswerID),- matches: Some(vec![rule_match; match_count].into_boxed_slice()),- cascade_winners_are_complete: true,- }-}--#[test]-fn retained_winners_construct_a_source_free_cascade_store() {- let (mut engine, nodes) = linear_document();- let target = StyleAtomID(200);- let rule = add_target_rule(&mut engine, StyleSheetObjectID(1), target);- let value = RetainedStyleValueData::from_owned(StyleValueData::Keyword { keyword: 1 });- let value_id = engine.intern_specified_value(&value.clone().into_arc());- engine.set_rule_declared_properties_with_values(rule, &[(property_id::BACKGROUND_COLOR, true, value_id)]);- commit_test_setup(&mut engine);- let matches = vec![concrete_rule_match(&engine, nodes[1], rule, 0, None)];- engine.matches_for_cascade(matches, false, Some(nodes[1]));- engine.retained.published_match_answers.push(- published_match_answer(nodes[1].raw(), None, 1),- &engine.retained.counters,- );- engine.published_match_answers.sort();-- let store = engine- .engine_constructed_cascade_store(computed::ComputedStyleTarget::new(nodes[1], u8::MAX))- .unwrap();- let (stored, important, _, has_style_sheet_context, _) =- store.winning_declaration(property_id::BACKGROUND_COLOR).unwrap();- assert_eq!(stored.pointer(), value.pointer());- assert!(important);- assert!(!has_style_sheet_context);-}-#[test]fn retained_stores_reject_every_logically_mapped_property() {let (_, nodes) = linear_document();@@ -856,9956 +99,687 @@ fn retained_stores_reject_every_logically_mapped_property() {}#[test]-fn repaired_selector_truth_deltas_do_not_depend_on_retained_order() {- let node = StyleNodeID::element(1);- let mut programs = SelectorPrograms::new();- let program = programs.add(test_selector_program("*", &[]));- let retained = [3, 1, 2, 5, 4].map(|rule| RetainedRuleMatch {- rule: RuleID(rule),- program,- entry: 0,- tree_scope: TreeScopeID::DOCUMENT,- scope_proximity: u32::MAX,- });- let mut current = [1, 2, 3, 4, 5].map(|rule| RuleMatch {- node,- pseudo_element: None,- rule: RuleID(rule),- program,- entry: 0,- cascade_order: rule,- specificity: Specificity::default(),- tree_scope: TreeScopeID::DOCUMENT,- scope_proximity: u32::MAX,- });+fn part_names_are_derived_from_their_host_pairs() {+ let mut engine = StyleEngine::new();+ let mut raw_nodes = [0; 3];+ engine.allocate_style_nodes(&mut raw_nodes);+ let element = StyleNodeID::from_raw(raw_nodes[0]).unwrap();+ let inner_host = StyleNodeID::from_raw(raw_nodes[1]).unwrap();+ let outer_host = StyleNodeID::from_raw(raw_nodes[2]).unwrap();+ let inner_name = StyleAtomID(1);+ let outer_name = StyleAtomID(2);+ let pairs = [+ (inner_name, inner_host),+ (outer_name, outer_host),+ (outer_name, inner_host),+ ];++ engine.set_element_parts(element, &pairs);assert_eq!(- planning::repaired_selector_truth_deltas(node, &retained, &mut current, &programs),- Some(Vec::new())+ engine.projection.written_facts(element).unwrap().parts(),+ &[inner_name, outer_name]);+ assert_eq!(engine.projection.part_hosts_of(element), &pairs);}-#[test]-fn verification_gates_only_execute_checks() {- let mut engine = StyleEngine::new();- let _: () = verify_style_answer_patch(&mut engine.retained, |_| {});- let _: () = verify_cascade_winners(&engine, |_| {});- let _: () = verify_style_plan_provenance(&engine, |_| {});- let _: () = verify_published_style_transaction(&engine, |_| {});-}--fn publish_current_cascade_as_computed(engine: &mut StyleEngine, node: StyleNodeID) {- let cascade_state = engine- .winner_groups- .token_for(WinnerGroupKey::current(node, engine.program.version()))- .sparse()- .unwrap_or_else(|gap| panic!("the test style has no current cascade state: {gap:?}"));- let target = computed::ComputedStyleTarget::new(node, u8::MAX);- engine.publish_computed_groups(- target,- &[],- 0,- 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(),- },- );- assert_eq!(- engine.computed_group_sets.bind_cascade_state(target, cascade_state),- None- );+fn relations(parent: Option<u32>, previous: Option<u32>, next: Option<u32>) -> TreeRelations {+ TreeRelations {+ parent: parent.map(StyleNodeID::element),+ previous_element_sibling: previous.map(StyleNodeID::element),+ next_element_sibling: next.map(StyleNodeID::element),+ ..TreeRelations::detached(TreeScopeID::DOCUMENT)+ }}#[test]-fn flat_tree_descendant_collection_follows_shadow_and_slot_relations() {+fn a_sibling_only_link_write_does_not_recompute_the_sibling_subtree_depth() {let mut engine = StyleEngine::new();- let mut raw = [0_u32; 7];+ let mut raw = [0_u32; 4];engine.allocate_style_nodes(&mut raw);- let nodes: Vec<_> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let [host, assigned, unassigned, shadow_root, wrapper, slot, assigned_child] = nodes.as_slice() else {- unreachable!()- };+ let nodes: Vec<_> = raw.into_iter().map(|raw| StyleNodeID::from_raw(raw).unwrap()).collect();+ engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));+ engine.record_tree_delta(nodes[1], None, Some(relations(Some(raw[0]), None, None)));+ engine.record_tree_delta(nodes[2], None, Some(relations(Some(raw[1]), None, None)));+ engine.record_tree_delta(nodes[3], None, Some(relations(Some(raw[2]), None, None)));+ discard_transaction(&mut engine);+ engine.tree.take_depth_recompute_visits();++ let mut inserted_raw = [0_u32; 1];+ engine.allocate_style_nodes(&mut inserted_raw);+ let inserted = StyleNodeID::from_raw(inserted_raw[0]).unwrap();+ engine.record_tree_delta(inserted, None, Some(relations(Some(raw[0]), None, Some(raw[1]))));+ engine.settle_tree_at_barrier();- engine.tree.set_first_element_child(*host, Some(*assigned));- engine.tree.set_parent(*assigned, Some(*host));- engine.tree.set_next_element_sibling(*assigned, Some(*unassigned));- engine.tree.set_previous_element_sibling(*unassigned, Some(*assigned));- engine.tree.set_parent(*unassigned, Some(*host));- engine.tree.set_first_element_child(*shadow_root, Some(*wrapper));- engine.tree.set_parent(*wrapper, Some(*shadow_root));- engine.tree.set_first_element_child(*wrapper, Some(*slot));- engine.tree.set_parent(*slot, Some(*wrapper));- engine.tree.set_first_element_child(*assigned, Some(*assigned_child));- engine.tree.set_parent(*assigned_child, Some(*assigned));- engine.retained.tree.set_shadow_root(*host, *shadow_root);- engine.retained.tree.set_assigned_slot(*assigned, Some(*slot));- engine.retained.tree.set_assigned_nodes(*slot, &[*assigned]);-- let mut descendants = Vec::new();- engine.for_each_flat_tree_descendant(*host, |node| descendants.push(node));-- assert_eq!(descendants, vec![*wrapper, *slot, *assigned, *assigned_child]);+ assert_eq!(engine.tree.take_depth_recompute_visits(), 1);+ assert_eq!(engine.element_depth(nodes[3]), 3);}#[test]-fn size_container_dependents_are_found_along_the_flat_tree() {+fn wrapping_existing_children_recomputes_depth_from_the_arriving_parent() {let mut engine = StyleEngine::new();- let mut raw = [0_u32; 7];+ let mut raw = [0_u32; 4];engine.allocate_style_nodes(&mut raw);- let nodes: Vec<_> = raw.iter().filter_map(|&raw| StyleNodeID::from_raw(raw)).collect();- let [host, assigned, unassigned, shadow_root, wrapper, slot, assigned_child]: [StyleNodeID; 7] =- std::array::from_fn(|index| nodes[index]);-- engine.tree.set_first_element_child(host, Some(assigned));- engine.tree.set_parent(assigned, Some(host));- engine.tree.set_next_element_sibling(assigned, Some(unassigned));- engine.tree.set_previous_element_sibling(unassigned, Some(assigned));- engine.tree.set_parent(unassigned, Some(host));- engine.tree.set_first_element_child(shadow_root, Some(wrapper));- engine.tree.set_parent(wrapper, Some(shadow_root));- engine.tree.set_first_element_child(wrapper, Some(slot));- engine.tree.set_parent(slot, Some(wrapper));- engine.tree.set_first_element_child(assigned, Some(assigned_child));- engine.tree.set_parent(assigned_child, Some(assigned));- let retained = &mut engine.retained;- retained.tree.set_shadow_root(host, shadow_root);- retained.tree.set_assigned_slot(assigned, Some(slot));- retained.tree.set_assigned_nodes(slot, &[assigned]);-- // The host is the container: its shadow tree, and the light child its slot renders, are what- // the container's box decides. Its light child no slot takes is in no box below it.- engine.set_element_size_container_query_facts(host, true, false);- for dependent in [slot, assigned_child, unassigned] {- engine.set_element_size_container_query_facts(dependent, false, true);- }- engine.record_size_container_query_dependents(host);-- assert_eq!(engine.size_query_container_scan_visits(true), 4);- let recorded = &engine.retained.row_inputs_moved;- assert!(recorded.containers_moved(slot));- assert!(recorded.containers_moved(assigned_child));- assert!(!recorded.containers_moved(unassigned));- assert!(!recorded.containers_moved(wrapper));-- // A container nothing asked about has no dependents to find.- engine.set_element_size_container_query_facts(host, false, false);- engine.record_size_container_query_dependents(host);- assert_eq!(engine.size_query_container_scan_visits(true), 0);-}+ let nodes: Vec<_> = raw.into_iter().map(|raw| StyleNodeID::from_raw(raw).unwrap()).collect();+ engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));+ engine.record_tree_delta(nodes[1], None, Some(relations(Some(raw[0]), None, Some(raw[2]))));+ engine.record_tree_delta(nodes[2], None, Some(relations(Some(raw[0]), Some(raw[1]), None)));+ engine.record_tree_delta(nodes[3], None, Some(relations(Some(raw[1]), None, None)));+ discard_transaction(&mut engine);-#[test]-fn delta_batch_keeps_singletons_inline_and_consolidates_larger_batches() {- let mut batch = DeltaBatch::default();- batch.push(2_u32);- assert_eq!(batch.as_slice(), &[2]);-- batch.consolidate();- assert_eq!(batch.as_slice(), &[2]);-- batch.push(1);- batch.push(2);- batch.consolidate();- assert_eq!(batch.as_slice(), &[1, 2]);+ let mut wrapper_raw = [0_u32; 1];+ engine.allocate_style_nodes(&mut wrapper_raw);+ let wrapper = StyleNodeID::from_raw(wrapper_raw[0]).unwrap();+ engine.record_tree_delta(+ nodes[1],+ Some(relations(Some(raw[0]), None, Some(raw[2]))),+ Some(relations(Some(wrapper.raw()), None, Some(raw[2]))),+ );+ engine.record_tree_delta(+ nodes[2],+ Some(relations(Some(raw[0]), Some(raw[1]), None)),+ Some(relations(Some(wrapper.raw()), Some(raw[1]), None)),+ );+ engine.record_tree_delta(wrapper, None, Some(relations(Some(raw[0]), None, None)));+ engine.settle_tree_at_barrier();++ assert_eq!(engine.element_depth(wrapper), 1);+ assert_eq!(engine.element_depth(nodes[1]), 2);+ assert_eq!(engine.element_depth(nodes[2]), 2);+ assert_eq!(engine.element_depth(nodes[3]), 3);}#[test]-fn selector_truth_changes_consolidate_by_semantic_key() {- let node = StyleNodeID::element(1);- let rule = RuleID(2);- let entry = EntryID(3);- let delta = |entry, change| SelectorTruthDelta {- node,- rule,- entry: EntryID(entry),- change,- selector_truth_changed: true,- };- let mut changes = SelectorTruthChanges::default();- changes.deltas.push(delta(0, SetChange::Added));- changes.deltas.push(delta(0, SetChange::Added));- changes.deltas.push(delta(0, SetChange::Removed));- changes.deltas.push(delta(1, SetChange::Added));- changes.deltas.push(delta(1, SetChange::Added));- changes.deltas.push(delta(2, SetChange::Removed));- changes.deltas.push(delta(2, SetChange::Removed));- changes.refreshes.push(SelectorTruthRefresh {- node,- rule: Some((rule, entry)),- });- changes.refreshes.push(SelectorTruthRefresh {- node,- rule: Some((rule, entry)),- });- let counters = Counters::new();-- changes.consolidate(&counters);-- assert_eq!(- changes.deltas.as_slice(),- &[delta(1, SetChange::Added), delta(2, SetChange::Removed)]- );- assert_eq!(changes.refreshes.as_slice().len(), 1);- assert_eq!(counters.get(Counter::SelectorTruthAdditions), 1);- assert_eq!(counters.get(Counter::SelectorTruthRemovals), 1);- assert_eq!(counters.get(Counter::SelectorTruthCancellations), 1);- assert_eq!(counters.get(Counter::SelectorTruthRefreshes), 1);-}--#[test]-fn exact_tree_routing_is_reserved_for_incremental_changes() {- assert!(exact_tree_routing_is_selective(20, 8_000));- assert!(!exact_tree_routing_is_selective(8_000, 8_000));-}--#[test]-fn an_evicted_prefix_answer_is_a_typed_missing_key() {- let mut answers = PrefixAnswerCache::default();- let mut catalog = MatchAnswerCatalog::default();- let contribution_key = PrefixContributionKey {- program: ScopeProgramID(1),- matches: PrefixMatchSetID::default(),- };- assert!(matches!(- answers.prefix_contribution(&catalog, contribution_key),- Lookup::Missing(gap) if gap == contribution_key- ));- let contribution =- answers.remember_prefix_contribution(&mut catalog, contribution_key.program, contribution_key.matches, &[]);- let non_prefix = catalog.intern(&[]);- assert_eq!(contribution, non_prefix, "equal factors share one answer identity");- assert!(matches!(- answers.prefix_contribution(&catalog, contribution_key),- Lookup::Known((identity, matches)) if identity == contribution && matches.is_empty()- ));- let key = PrefixAnswerKey {- prefix_contribution: contribution,- non_prefix_matches: &[],- non_prefix_hash: super::intern_table::content_hash(&[] as &[RetainedRuleMatch]),- };- answers.remember(&mut catalog, key, &[], None, None, MatchAnswerID(1), true);-- answers.retain();- assert!(matches!(- answers.lookup(key),- Lookup::Known(answer)- if catalog.answer(answer.matches).is_some_and(|matches| matches.is_empty())- ));-- answers.make_scratch();-- assert!(matches!(answers.lookup(key), Lookup::Known(_)));- answers.retain();-- answers.release(&mut catalog);- assert!(catalog.answer(contribution).is_none());- let replacement = catalog.intern(&[]);- assert_ne!(replacement, contribution, "retired answer identities are never reused");- assert!(matches!(- answers.prefix_contribution(&catalog, contribution_key),- Lookup::Missing(gap) if gap == contribution_key- ));- assert!(matches!(answers.lookup(key), Lookup::Missing(gap) if gap == key));-}--#[test]-fn prefix_answer_keys_compare_content_after_hash_collisions() {- let mut answers = PrefixAnswerCache::default();- let mut catalog = MatchAnswerCatalog::default();- let mut effects = AnswerEffects::default();- let contribution =- answers.remember_prefix_contribution(&mut catalog, ScopeProgramID(1), PrefixMatchSetID::default(), &[]);- let matched = RetainedRuleMatch {- rule: RuleID(1),- program: SelectorProgramID(1),- entry: 0,- tree_scope: TreeScopeID::DOCUMENT,- scope_proximity: u32::MAX,- };- // Force every key into the same hash bucket, including across table growth.- for entry in 0..64 {- let content = [RetainedRuleMatch { entry, ..matched }];- let key = PrefixAnswerKey {- prefix_contribution: contribution,- non_prefix_matches: &content,- non_prefix_hash: 0,- };- assert!(matches!(answers.lookup(key), Lookup::Missing(_)));- assert!(matches!(answers.exact_answer(key), Lookup::Missing(_)));- answers.remember(- &mut catalog,- key,- &[],- None,- None,- MatchAnswerID(entry + 1),- entry % 2 == 0,- );- effects.remember_exact_answer(key, contribution, &mut catalog);- }- for entry in 0..64 {- let content = vec![RetainedRuleMatch { entry, ..matched }];- let key = PrefixAnswerKey {- prefix_contribution: contribution,- non_prefix_matches: &content,- non_prefix_hash: 0,- };- assert_eq!(effects.exact_answer(key), Some(contribution));- assert!(matches!(answers.exact_answer(key), Lookup::Missing(_)));- }- assert_eq!(catalog.pending_reference_count(), 64);- catalog.sweep_unreferenced();- effects.install(&mut RetainedMatchAnswers::default(), &mut catalog, &mut answers);- assert_eq!(catalog.pending_reference_count(), 0);- // Each probe has a different allocation from the insertion's expired local slice.- for entry in 0..64 {- let content = vec![RetainedRuleMatch { entry, ..matched }];- let key = PrefixAnswerKey {- prefix_contribution: contribution,- non_prefix_matches: &content,- non_prefix_hash: 0,- };- let answer = answers.lookup(key).sparse().unwrap();- assert_eq!(answer.cascade_input, MatchAnswerID(entry + 1));- assert_eq!(answer.cascade_winner_inventory_is_complete, entry % 2 == 0);- assert_eq!(answers.exact_answer(key).sparse().unwrap(), contribution);-- answers.remember(&mut catalog, key, &[], None, None, MatchAnswerID(100), true);- answers.remember_exact_answer(&mut catalog, key, contribution);- assert_eq!(answers.lookup(key).sparse().unwrap().cascade_input, MatchAnswerID(100));- }-- answers.retain();- answers.release(&mut catalog);-- assert!(catalog.answer(contribution).is_none());-}--#[test]-fn prefix_answer_payload_accounting_uses_the_retained_match_shape() {- let mut catalog = MatchAnswerCatalog::default();- let identity = catalog.intern(&[RuleMatch {- node: StyleNodeID::element(1),- pseudo_element: None,- rule: RuleID(1),- program: SelectorProgramID(1),- entry: 0,- cascade_order: 1,- specificity: Specificity::default(),- tree_scope: TreeScopeID::DOCUMENT,- scope_proximity: 0,- }]);-- catalog.retain_prefix(identity);- catalog.retain_prefix(identity);- catalog.release_prefix(identity);- catalog.release_prefix(identity);-}--fn retained_answer_test_programs() -> SelectorPrograms {- let mut programs = SelectorPrograms::new();- for (selector, name, atom) in [- (".a", "a", StyleAtomID(1)),- (".b", "b", StyleAtomID(2)),- (".c", "c", StyleAtomID(3)),- ] {- programs.add(test_selector_program(selector, &[(name, atom)]));- }- programs-}--#[test]-fn retained_answer_rule_queries_preserve_shared_nodes_and_query_boundaries() {- let mut catalog = MatchAnswerCatalog::default();- let mut answers = RetainedMatchAnswers::default();-- let programs = retained_answer_test_programs();- let mut expected = Vec::new();- for index in 1..=128 {- let node = StyleNodeID::element(index);- let rule = RuleID(index % 3 + 1);- let retained = RuleMatch {- node,- pseudo_element: None,- rule,- program: SelectorProgramID(1),- entry: 0,- cascade_order: 1,- specificity: Specificity::default(),- tree_scope: TreeScopeID::DOCUMENT,- scope_proximity: 0,- };- answers- .remember_prepared(- &mut catalog,- node,- prepare_retained_match_answer([retained].into_iter()),- &programs,- )- .unwrap();- expected.push((node, rule));- }- assert_eq!(- answers.answer_identity(StyleNodeID::element(1)),- answers.answer_identity(StyleNodeID::element(4)),- );- for removed in [None, Some(StyleNodeID::element(1)), Some(StyleNodeID::element(128))] {- if let Some(removed) = removed {- answers.forget(&mut catalog, removed);- expected.retain(|&(node, _)| node != removed);- }- for rules in [- vec![],- vec![RuleID(1)],- vec![RuleID(2)],- vec![RuleID(1), RuleID(3)],- vec![RuleID(99)],- ] {- let mut visited = Vec::new();- answers.for_each_answer_containing_any_rule(&catalog, &rules, |node| visited.push(node));- assert_eq!(- visited,- expected- .iter()- .filter_map(|&(node, rule)| rules.contains(&rule).then_some(node))- .collect::<Vec<_>>(),- );- }- }-}--#[test]-fn cascade_input_catalog_entries_follow_retained_column_lifetimes() {- let mut catalog = MatchAnswerCatalog::default();- let mut answers = RetainedMatchAnswers::default();-- let node = StyleNodeID::element(1);-- for _ in 0..128 {- let identity = catalog.intern(&[]);- answers.remember_cascade_input(&mut catalog, node, identity);- answers.forget(&mut catalog, node);- }-- catalog.sweep_unreferenced();- assert!(catalog.answers.live_is_empty());-}--#[test]-fn a_sweep_visits_only_answers_that_lost_their_last_reference_since_the_previous_sweep() {- let mut catalog = MatchAnswerCatalog::default();- let mut answers = RetainedMatchAnswers::default();-- let nodes: Vec<_> = (1..=8).map(StyleNodeID::element).collect();-- // A new answer is a candidate until a sweep finds it referenced.- let identity = catalog.intern(&[]);- assert_eq!(catalog.sweep_candidate_count(), 1);- for &node in &nodes {- answers.remember_cascade_input(&mut catalog, node, identity);- }- catalog.sweep_unreferenced();- assert_eq!(catalog.sweep_candidate_count(), 0);- assert_eq!(catalog.answers.live_len(), 1);-- // Releases that leave a reference behind note nothing for the next sweep.- for &node in &nodes[1..] {- answers.forget(&mut catalog, node);- }- assert_eq!(catalog.sweep_candidate_count(), 0);-- // An answer that loses its last reference twice before a sweep is noted once.- answers.forget(&mut catalog, nodes[0]);- answers.remember_cascade_input(&mut catalog, nodes[0], identity);- answers.forget(&mut catalog, nodes[0]);- assert_eq!(catalog.sweep_candidate_count(), 1);-- catalog.sweep_unreferenced();- assert_eq!(catalog.sweep_candidate_count(), 0);- assert!(catalog.answers.live_is_empty());-}--#[test]-fn retained_match_answer_payloads_are_evictable_without_losing_identity() {- assert_eq!(size_of::<RetainedRuleMatch>(), 20);-- let mut answers = RetainedMatchAnswers::default();- let mut catalog = MatchAnswerCatalog::default();- let node = StyleNodeID::element(1);- let mut programs = SelectorPrograms::new();- let program = programs.add(test_class_selector_program(- ".target",- &[("target", StyleAtomID(1))],- None,- ));- let retained = RuleMatch {- node,- pseudo_element: None,- rule: RuleID(1),- program,- entry: 0,- cascade_order: 7,- specificity: Specificity {- classes: 1,- ..Specificity::default()- },- tree_scope: TreeScopeID::DOCUMENT,- scope_proximity: 3,- };-- assert!(- answers- .remember_prepared(- &mut catalog,- node,- prepare_retained_match_answer([retained].into_iter()),- &programs- )- .is_ok()- );- let (identity, compact) = match answers.lookup(node) {- Lookup::Known(identity) => (*identity, catalog.retained_answer(*identity).unwrap()),- Lookup::KnownAbsent | Lookup::Missing(_) => panic!("expected a retained answer"),- };- assert_eq!(compact[0].materialize(node, &programs, 7), Some(retained));-- let cascade_input = catalog.intern(&[retained]);- assert_eq!(- cascade_input, identity,- "both answer owners share one canonical identity"- );- let same_retained_match = RuleMatch {- node: StyleNodeID::element(2),- cascade_order: 99,- ..retained- };- assert_eq!(catalog.intern(&[same_retained_match]), identity);- answers.remember_cascade_input(&mut catalog, node, cascade_input);-- answers.clear(&mut catalog);- assert!(catalog.retained_answer(identity).is_none());- assert!(matches!(answers.lookup(node), Lookup::Missing(gap) if gap == node));- assert!(matches!(- answers.cascade_input_lookup(node),- Lookup::Known(retained) if *retained == cascade_input- ));-}--#[test]-fn selector_truth_sets_intern_canonical_twelve_byte_rows() {- assert_eq!(size_of::<SelectorTruth>(), 12);-- let truth = SelectorTruth {- entry: EntryID(7),- tree_scope: TreeScopeID::DOCUMENT,- scope_proximity: 3,- };- let mut catalog = SelectorTruthSetCatalog::default();- let (first, first_reused) = catalog.intern_prepared(vec![truth]);- let (repeated, repeated_reused) = catalog.intern_prepared(vec![truth]);- let (distinct, distinct_reused) = catalog.intern_prepared(vec![SelectorTruth {- scope_proximity: 4,- ..truth- }]);-- assert!(!first_reused);- assert!(repeated_reused);- assert!(!distinct_reused);- assert_eq!(first, repeated);- assert_ne!(first, distinct);- assert_eq!(catalog.get(first).as_ref(), &[truth]);-- let answer = RetainedRuleMatch {- rule: RuleID(1),- program: SelectorProgramID(1),- entry: 0,- tree_scope: TreeScopeID::DOCUMENT,- scope_proximity: u32::MAX,- };- assert!(!catalog.verify_derived_answer(first, TreeScopeID::DOCUMENT, ProgramVersion(1), &[answer]));- assert!(catalog.verify_derived_answer(first, TreeScopeID::DOCUMENT, ProgramVersion(1), &[answer]));- assert!(!catalog.verify_derived_answer(first, TreeScopeID(1), ProgramVersion(1), &[]));-}--fn retained_answer_verifier_fixture() -> (StyleEngine, StyleNodeID, Vec<RetainedRuleMatch>, Vec<SelectorTruth>) {- let (mut engine, nodes) = linear_document();- let target = StyleAtomID(200);- let rule = add_target_rule(&mut engine, StyleSheetObjectID(1), target);- engine.set_rule_declared_properties(rule, &[(1, false)]);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- let exact = engine.match_element(nodes[1]).unwrap();- let retained = prepare_retained_match_answer(exact.iter().copied());- let truth = prepare_selector_truth_set(&retained, &engine.programs);- (engine, nodes[1], retained, truth)-}--#[test]-fn retained_answer_verifier_accepts_exact_selector_truth() {- let (mut engine, node, retained, truth) = retained_answer_verifier_fixture();- verification::with_selector_truth_derivation_enabled(|| {- engine.remember_prepared_retained_match_answer_with_truth(node, retained, Some(truth));- });-}--#[test]-fn retained_answer_verifier_rejects_a_dropped_selector_truth_row() {- let (mut engine, node, retained, mut truth) = retained_answer_verifier_fixture();- assert_eq!(truth.len(), 1);- truth.clear();-- let result = std::panic::catch_unwind(std::panic::AssertUnwindSafe(|| {- verification::with_selector_truth_derivation_enabled(|| {- engine.remember_prepared_retained_match_answer_with_truth(node, retained, Some(truth));- });- }));- assert!(result.is_err());-}--#[test]-fn retained_match_answer_replacement_releases_the_displaced_identity() {- let programs = retained_answer_test_programs();-- let mut answers = RetainedMatchAnswers::default();- let mut catalog = MatchAnswerCatalog::default();- let node = StyleNodeID::element(1);- let original = RuleMatch {- node,- pseudo_element: None,- rule: RuleID(1),- program: SelectorProgramID(1),- entry: 0,- cascade_order: 1,- specificity: Specificity::default(),- tree_scope: TreeScopeID::DOCUMENT,- scope_proximity: 0,- };-- assert!(- answers- .remember_prepared(- &mut catalog,- node,- prepare_retained_match_answer([original].into_iter()),- &programs,- )- .is_ok()- );- let original_identity = match answers.lookup(node) {- Lookup::Known(identity) => *identity,- Lookup::KnownAbsent | Lookup::Missing(_) => panic!("expected the original retained answer"),- };-- let replacement = RuleMatch {- rule: RuleID(2),- program: SelectorProgramID(2),- ..original- };- assert!(- answers- .remember_prepared(- &mut catalog,- node,- prepare_retained_match_answer([replacement].into_iter()),- &programs,- )- .is_ok()- );- let replacement_identity = match answers.lookup(node) {- Lookup::Known(identity) => *identity,- Lookup::KnownAbsent | Lookup::Missing(_) => panic!("expected the replacement retained answer"),- };- assert_ne!(replacement_identity, original_identity);- assert!(catalog.answer(original_identity).is_none());- assert_eq!(catalog.retained_answer_count, 1);-- let mut referenced_programs = Vec::new();- catalog.mark_referenced_selector_programs(&mut referenced_programs);- assert!(!referenced_programs[1]);- assert!(referenced_programs[2]);-}--#[test]-fn shared_retained_match_answer_lives_until_its_last_column_owner_forgets() {- let programs = retained_answer_test_programs();-- let mut answers = RetainedMatchAnswers::default();- let mut catalog = MatchAnswerCatalog::default();- let first_node = StyleNodeID::element(1);- let second_node = StyleNodeID::element(2);- let retained = RuleMatch {- node: first_node,- pseudo_element: None,- rule: RuleID(1),- program: SelectorProgramID(1),- entry: 0,- cascade_order: 1,- specificity: Specificity::default(),- tree_scope: TreeScopeID::DOCUMENT,- scope_proximity: 0,- };-- for node in [first_node, second_node] {- assert!(- answers- .remember_prepared(- &mut catalog,- node,- prepare_retained_match_answer([RuleMatch { node, ..retained }].into_iter()),- &programs,- )- .is_ok()- );- }- let shared_identity = match answers.lookup(first_node) {- Lookup::Known(identity) => *identity,- Lookup::KnownAbsent | Lookup::Missing(_) => panic!("expected a shared retained answer"),- };- assert_eq!(- catalog.answers[shared_identity].as_ref().unwrap().retained_references,- 2- );-- answers.forget_answer(&mut catalog, first_node);- assert_eq!(- catalog.answers[shared_identity].as_ref().unwrap().retained_references,- 1- );- assert!(catalog.retained_answer(shared_identity).is_some());-- answers.forget_answer(&mut catalog, second_node);- assert!(catalog.answer(shared_identity).is_none());- assert_eq!(catalog.retained_answer_count, 0);-}--#[test]-fn an_evicted_feature_posting_is_missing_instead_of_empty() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_target_rule(&mut engine, guard, target);- for (node, class) in [(nodes[1], guard), (nodes[3], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- let key = SelectorPostingKey::Class(target);- assert!(matches!(engine.facts.postings().lookup(key), Lookup::Known(_)));- engine.facts.postings_mut().drop_posting(key);- assert!(matches!(engine.facts.postings().lookup(key), Lookup::Missing(gap) if gap == key));-- remove_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes[3].raw()]);-}--#[test]-fn part_names_are_derived_from_their_host_pairs() {- let mut engine = StyleEngine::new();- let mut raw_nodes = [0; 3];- engine.allocate_style_nodes(&mut raw_nodes);- let element = StyleNodeID::from_raw(raw_nodes[0]).unwrap();- let inner_host = StyleNodeID::from_raw(raw_nodes[1]).unwrap();- let outer_host = StyleNodeID::from_raw(raw_nodes[2]).unwrap();- let inner_name = StyleAtomID(1);- let outer_name = StyleAtomID(2);- let pairs = [- (inner_name, inner_host),- (outer_name, outer_host),- (outer_name, inner_host),- ];-- engine.set_element_parts(element, &pairs);-- assert_eq!(engine.facts.parts_of(element), &[inner_name, outer_name]);- assert_eq!(engine.tree.part_hosts_of(element), &pairs);-}--#[test]-fn a_planned_node_never_returns_to_a_remaining_posting() {- let mut postings = FeaturePostings::new();- let key = SelectorPostingKey::Class(StyleAtomID(1));- let nodes = [- StyleNodeID::element(1),- StyleNodeID::element(2),- StyleNodeID::element(3),- ];- for node in nodes {- assert!(postings.insert(key, node));- }- let mut plan = ImpactRegions::new();- plan.add(ImpactRegion::Node(nodes[1]));- let mut workspace = ImpactPlanningWorkspace::default();- let mut candidates = Vec::new();-- let (reused, copied, inspected, pruned) = workspace- .extend_remaining_posting(key, &postings, &plan, &mut candidates, None)- .unwrap();- assert!(!reused);- assert_eq!(copied, 3);- assert_eq!(inspected, 3);- assert_eq!(pruned, 1);- assert_eq!(candidates, [nodes[0], nodes[2]]);-- plan.add(ImpactRegion::Node(nodes[0]));- candidates.clear();- let (reused, copied, inspected, pruned) = workspace- .extend_remaining_posting(key, &postings, &plan, &mut candidates, None)- .unwrap();- assert!(reused);- assert_eq!(copied, 0);- assert_eq!(inspected, 0);- assert_eq!(pruned, 1);- assert_eq!(candidates, [nodes[2]]);-- candidates.clear();- let (reused, copied, inspected, pruned) = workspace- .extend_remaining_posting(key, &postings, &plan, &mut candidates, None)- .unwrap();- assert!(reused);- assert_eq!(copied, 0);- assert_eq!(inspected, 0);- assert_eq!(pruned, 0);- assert_eq!(candidates, [nodes[2]]);-- let outside = StyleNodeID::element(4);- plan.add(ImpactRegion::Node(outside));- candidates.clear();- let (reused, copied, inspected, pruned) = workspace- .extend_remaining_posting(key, &postings, &plan, &mut candidates, None)- .unwrap();- assert!(reused);- assert_eq!(copied, 0);- assert_eq!(inspected, 0);- assert_eq!(pruned, 0);- assert_eq!(candidates, [nodes[2]]);-- plan.add(ImpactRegion::Node(nodes[2]));- plan.add(ImpactRegion::Node(StyleNodeID::element(5)));- candidates.clear();- let (reused, copied, inspected, pruned) = workspace- .extend_remaining_posting(key, &postings, &plan, &mut candidates, None)- .unwrap();- assert!(reused);- assert_eq!(copied, 0);- assert_eq!(inspected, 0);- assert_eq!(pruned, 1);- assert!(candidates.is_empty());-- let mut fallback_plan = ImpactRegions::new();- let mut fallback_workspace = ImpactPlanningWorkspace::default();- candidates.clear();- fallback_workspace- .extend_remaining_posting(key, &postings, &fallback_plan, &mut candidates, None)- .unwrap();- fallback_plan.add(ImpactRegion::Node(nodes[1]));- for index in 0..MAX_POINT_REMOVED_EXACT_NODES - 1 {- fallback_plan.add(ImpactRegion::Node(StyleNodeID::element(100 + index as u32)));- }- candidates.clear();- let (reused, copied, inspected, pruned) = fallback_workspace- .extend_remaining_posting(key, &postings, &fallback_plan, &mut candidates, None)- .unwrap();- assert!(reused);- assert_eq!(copied, 0);- assert_eq!(inspected, 0);- assert_eq!(pruned, 1);- assert_eq!(candidates, [nodes[0], nodes[2]]);-- let mut reordered_plan = ImpactRegions::new();- for index in (20..20 + impact::MAX_PAIRWISE_COALESCE as u32).rev() {- reordered_plan.add(ImpactRegion::Node(StyleNodeID::element(index)));- }- let mut reordered_workspace = ImpactPlanningWorkspace::default();- candidates.clear();- reordered_workspace- .extend_remaining_posting(key, &postings, &reordered_plan, &mut candidates, None)- .unwrap();- reordered_plan.add(ImpactRegion::Node(nodes[1]));- let tree = StyleNodeTree::new();- reordered_plan.normalize(&tree);- candidates.clear();- let (reused, copied, inspected, pruned) = reordered_workspace- .extend_remaining_posting(key, &postings, &reordered_plan, &mut candidates, None)- .unwrap();- assert!(reused);- assert_eq!(copied, 0);- assert_eq!(inspected, 3);- assert_eq!(pruned, 1);- assert_eq!(candidates, [nodes[0], nodes[2]]);-}--#[test]-fn routing_phases_share_remaining_postings_for_one_transaction() {- let mut engine = StyleEngine::new();- let guard = StyleAtomID(200);- let also = StyleAtomID(201);- let target = StyleAtomID(202);- add_guarded_nth_target_rule(&mut engine, guard, also, target);-- const CONTAINER_COUNT: usize = 16;- const LEAVES_PER_CONTAINER: usize = 32;- let mut raw = vec![0_u32; 1 + CONTAINER_COUNT * (1 + LEAVES_PER_CONTAINER)];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));-- let mut next = 1;- let mut previous_container = None;- let mut containers = Vec::new();- for _ in 0..CONTAINER_COUNT {- let container = nodes[next];- next += 1;- engine.record_tree_delta(- container,- None,- Some(relations(- Some(nodes[0].raw()),- previous_container.map(StyleNodeID::raw),- None,- )),- );- previous_container = Some(container);- containers.push(container);- for leaf_index in 0..LEAVES_PER_CONTAINER {- let leaf = nodes[next];- next += 1;- engine.record_tree_delta(- leaf,- None,- Some(relations(- Some(container.raw()),- (leaf_index != 0).then(|| nodes[next - 2].raw()),- None,- )),- );- if leaf_index == 0 {- add_feature(&mut engine, leaf, LocalFeatureKey::Class(target));- }- }- for class in [guard, also] {- add_feature(&mut engine, container, LocalFeatureKey::Class(class));- }- }- discard_transaction(&mut engine);-- let mut inserted_raw = [0_u32; 1];- engine.allocate_style_nodes(&mut inserted_raw);- let inserted = StyleNodeID::from_raw(inserted_raw[0]).unwrap();- engine.record_tree_delta(- inserted,- None,- Some(relations(Some(nodes[0].raw()), None, Some(containers[0].raw()))),- );- remove_feature(&mut engine, containers[0], LocalFeatureKey::Class(guard));-- let builds_before = engine.counters().get(Counter::RemainingPostingBuilds);- let reuses_before = engine.counters().get(Counter::RemainingPostingReuses);- assert!(engine.take_style_transaction_nodes(nodes[0], |_| {}));- assert_eq!(- engine.counters().get(Counter::RemainingPostingBuilds) - builds_before,- 1,- "the sequence and local routing phases must materialize the target posting once"- );- assert!(- engine.counters().get(Counter::RemainingPostingReuses) > reuses_before,- "the later routing phase must reuse the posting retained by the earlier phase"- );-}--#[test]-fn a_transaction_taken_inside_a_cold_matching_batch_retires_it() {- // The host holds a cold matching batch open while it applies a transaction's reactions, and- // takes the transaction they fed back inside it. One that reaches a selector changed the facts- // the batch was read from, so the batch is retired before the transaction begins its own.- let (mut engine, nodes) = linear_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_target_rule(&mut engine, guard, target);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(target));- for &node in &nodes {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, StyleAtomID(100));- }- discard_transaction(&mut engine);-- assert!(engine.begin_cold_matching_batch(nodes[0]));- assert!(engine.match_element(nodes[1]).unwrap().is_empty());- add_feature(&mut engine, nodes[0], LocalFeatureKey::Class(guard));- engine.take_style_transaction(nodes[0], |_, _, _| {});- engine.end_cold_matching_batch();-- assert!(engine.begin_cold_matching_batch(nodes[0]));- assert_eq!(engine.match_element(nodes[1]).unwrap().len(), 1);- engine.end_cold_matching_batch();-}--#[test]-fn a_document_root_arrival_is_already_a_whole_document_plan() {- let (mut engine, nodes) = linear_document();- let routed_before = engine.counters().get(Counter::RoutedEntryPoints);- let mut planned = Vec::new();-- assert!(!engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, nodes.iter().map(|node| node.raw()).collect::<Vec<_>>());- assert_eq!(engine.counters().get(Counter::RoutedEntryPoints), routed_before);-}--#[test]-fn a_non_bulk_document_root_arrival_publishes_style_reactions() {- let (mut engine, nodes) = linear_document();- for &node in &nodes {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, StyleAtomID(100));- }- let mut published = Vec::new();-- assert!(!take_every_wave(&mut engine, nodes[0], |_, _, reactions| {- published.extend(reactions.iter().map(|reaction| reaction.style_node));- }));- assert_eq!(published, nodes.iter().map(|node| node.raw()).collect::<Vec<_>>());- for node in nodes {- assert_eq!(engine.consume_published_match_answer(node), Some(Vec::new()));- }-}--#[test]-fn a_document_program_plan_skips_dom_routing() {- let (mut engine, nodes) = linear_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_target_rule(&mut engine, guard, target);-- let program = engine.programs.add(test_selector_program("*", &[]));- let sheet = engine.add_sheet(StyleSheetObjectID(2), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(2));- engine.replace_rule_version(rule, version);-- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- let routed_before = engine.counters().get(Counter::RoutedEntryPoints);- let mut planned = Vec::new();- assert!(!engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, nodes.iter().map(|node| node.raw()).collect::<Vec<_>>());- assert_eq!(- engine.counters().get(Counter::RoutedEntryPoints) - routed_before,- 0,- "the document envelope makes every DOM route redundant"- );-}--#[test]-fn a_program_change_does_not_repeat_an_arriving_subtree() {- let (mut engine, nodes) = linear_document();- let target = StyleAtomID(200);- add_feature(&mut engine, nodes[2], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- let mut raw = [0_u32; 4];- engine.allocate_style_nodes(&mut raw);- let arriving: Vec<StyleNodeID> = raw.into_iter().map(|raw| StyleNodeID::from_raw(raw).unwrap()).collect();- for (index, &node) in arriving.iter().enumerate() {- let relations = match index {- 0 => relations(Some(nodes[0].raw()), Some(nodes[3].raw()), None),- _ => relations(Some(arriving[index - 1].raw()), None, None),- };- engine.record_tree_delta(node, None, Some(relations));- add_feature(&mut engine, node, LocalFeatureKey::Class(target));- }- add_target_rule(&mut engine, StyleSheetObjectID(1), target);- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- planned.sort_unstable();- let mut expected = vec![nodes[2].raw()];- expected.extend(arriving.iter().map(|node| node.raw()));- expected.sort_unstable();- assert_eq!(planned, expected);-}--#[test]-fn a_rare_program_candidate_inside_an_arrival_is_already_covered() {- let (mut engine, nodes) = linear_document();- discard_transaction(&mut engine);-- let mut raw = [0_u32; 1];- engine.allocate_style_nodes(&mut raw);- let arriving = StyleNodeID::from_raw(raw[0]).unwrap();- let target = StyleAtomID(200);- engine.record_tree_delta(- arriving,- None,- Some(relations(Some(nodes[0].raw()), Some(nodes[3].raw()), None)),- );- add_feature(&mut engine, arriving, LocalFeatureKey::Class(target));- add_target_rule(&mut engine, StyleSheetObjectID(1), target);- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, [arriving.raw()]);-}--#[test]-fn a_program_region_inside_an_arrival_is_already_covered() {- let (mut engine, nodes) = linear_document();- discard_transaction(&mut engine);-- let mut raw = [0_u32; 2];- engine.allocate_style_nodes(&mut raw);- let arriving: Vec<StyleNodeID> = raw.into_iter().map(|raw| StyleNodeID::from_raw(raw).unwrap()).collect();- engine.record_tree_delta(- arriving[0],- None,- Some(relations(Some(nodes[0].raw()), Some(nodes[3].raw()), None)),- );- engine.record_tree_delta(arriving[1], None, Some(relations(Some(arriving[0].raw()), None, None)));- let guard = StyleAtomID(200);- add_feature(&mut engine, arriving[0], LocalFeatureKey::Class(guard));- add_guard_universal_rule(&mut engine, guard);- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, raw);-}--fn relations(parent: Option<u32>, previous: Option<u32>, next: Option<u32>) -> TreeRelations {- TreeRelations {- parent: parent.map(StyleNodeID::element),- previous_element_sibling: previous.map(StyleNodeID::element),- next_element_sibling: next.map(StyleNodeID::element),- ..TreeRelations::detached(TreeScopeID::DOCUMENT)- }-}--#[test]-fn a_departed_following_sibling_anchor_widens_when_its_old_next_sibling_relocated() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 4];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();-- // The departed node's old next sibling is now last: root -> [first, second, old_next].- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- engine.record_tree_delta(nodes[1], None, Some(relations(Some(raw[0]), None, Some(raw[2]))));- engine.record_tree_delta(- nodes[2],- None,- Some(relations(Some(raw[0]), Some(raw[1]), Some(raw[3]))),- );- engine.record_tree_delta(nodes[3], None, Some(relations(Some(raw[0]), Some(raw[2]), None)));- engine.apply_staged_tree_deltas();-- let departed_relations = relations(Some(raw[0]), None, Some(raw[3]));- let transaction_inputs = [NormalizedInput {- key: InputKey::TreeRelations(nodes[3]),- old: InputValue::TreeRelations(Some(relations(Some(raw[0]), None, Some(raw[1])))),- new: InputValue::TreeRelations(Some(relations(Some(raw[0]), Some(raw[2]), None))),- }];- let tree_routing = TreeRoutingMode {- use_exact: false,- has_before_sibling_relations: false,- transaction_inputs: &transaction_inputs,- };- let old_next_relocated = tree_routing.tree_position_changed(nodes[3]);- assert!(old_next_relocated);- assert_eq!(- engine.follow_from_departed_position(- departed_relations,- &[selector::InverseStep::FollowingSiblings],- old_next_relocated,- ),- Some(ImpactRegion::Children(nodes[0]))- );-}--#[test]-fn sibling_only_tree_staging_does_not_recompute_the_sibling_subtree_depth() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 4];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<_> = raw.into_iter().map(|raw| StyleNodeID::from_raw(raw).unwrap()).collect();- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- engine.record_tree_delta(nodes[1], None, Some(relations(Some(raw[0]), None, None)));- engine.record_tree_delta(nodes[2], None, Some(relations(Some(raw[1]), None, None)));- engine.record_tree_delta(nodes[3], None, Some(relations(Some(raw[2]), None, None)));- discard_transaction(&mut engine);- engine.tree.take_depth_recompute_visits();-- let mut inserted_raw = [0_u32; 1];- engine.allocate_style_nodes(&mut inserted_raw);- let inserted = StyleNodeID::from_raw(inserted_raw[0]).unwrap();- engine.record_tree_delta(inserted, None, Some(relations(Some(raw[0]), None, Some(raw[1]))));- engine.apply_staged_tree_deltas();-- assert_eq!(engine.tree.take_depth_recompute_visits(), 1);- assert_eq!(engine.tree.depth(nodes[3]), 3);-}--#[test]-fn depth_recompute_membership_is_sparse_for_high_node_identities() {- let engine = StyleEngine::new();- let relations = Some(TreeRelations::detached(TreeScopeID::DOCUMENT));- let high_rows = [- (StyleNodeID::element(1_000_000), None, relations),- (StyleNodeID::element(i32::MAX as u32), None, relations),- ];- let high_nodes = engine.depth_recompute_nodes(&high_rows);-- assert_eq!(high_nodes.len(), 2);- assert!(high_nodes.contains(&StyleNodeID::element(1_000_000)));- assert!(high_nodes.contains(&StyleNodeID::element(i32::MAX as u32)));-}--#[test]-fn wrapping_existing_children_recomputes_depth_from_the_arriving_parent() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 4];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<_> = raw.into_iter().map(|raw| StyleNodeID::from_raw(raw).unwrap()).collect();- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- engine.record_tree_delta(nodes[1], None, Some(relations(Some(raw[0]), None, Some(raw[2]))));- engine.record_tree_delta(nodes[2], None, Some(relations(Some(raw[0]), Some(raw[1]), None)));- engine.record_tree_delta(nodes[3], None, Some(relations(Some(raw[1]), None, None)));- discard_transaction(&mut engine);-- let mut wrapper_raw = [0_u32; 1];- engine.allocate_style_nodes(&mut wrapper_raw);- let wrapper = StyleNodeID::from_raw(wrapper_raw[0]).unwrap();- engine.record_tree_delta(- nodes[1],- Some(relations(Some(raw[0]), None, Some(raw[2]))),- Some(relations(Some(wrapper.raw()), None, Some(raw[2]))),- );- engine.record_tree_delta(- nodes[2],- Some(relations(Some(raw[0]), Some(raw[1]), None)),- Some(relations(Some(wrapper.raw()), Some(raw[1]), None)),- );- engine.record_tree_delta(wrapper, None, Some(relations(Some(raw[0]), None, None)));- engine.apply_staged_tree_deltas();-- assert_eq!(engine.tree.depth(wrapper), 1);- assert_eq!(engine.tree.depth(nodes[1]), 2);- assert_eq!(engine.tree.depth(nodes[2]), 2);- assert_eq!(engine.tree.depth(nodes[3]), 3);-}--#[test]-fn reparenting_between_equal_depth_parents_still_visits_the_subtree() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 5];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<_> = raw.into_iter().map(|raw| StyleNodeID::from_raw(raw).unwrap()).collect();- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- engine.record_tree_delta(nodes[1], None, Some(relations(Some(raw[0]), None, Some(raw[2]))));- engine.record_tree_delta(nodes[2], None, Some(relations(Some(raw[0]), Some(raw[1]), None)));- engine.record_tree_delta(nodes[3], None, Some(relations(Some(raw[1]), None, None)));- engine.record_tree_delta(nodes[4], None, Some(relations(Some(raw[3]), None, None)));- discard_transaction(&mut engine);- engine.tree.take_depth_recompute_visits();-- engine.record_tree_delta(- nodes[3],- Some(relations(Some(raw[1]), None, None)),- Some(relations(Some(raw[2]), None, None)),- );- engine.apply_staged_tree_deltas();-- assert_eq!(engine.tree.take_depth_recompute_visits(), 2);- assert_eq!(engine.tree.depth(nodes[3]), 2);- assert_eq!(engine.tree.depth(nodes[4]), 3);-}--#[test]-fn reparenting_below_a_sibling_only_staged_parent_recomputes_depth() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 7];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<_> = raw.into_iter().map(|raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let [root, a, b, m, p, c, n] = nodes.as_slice() else {- unreachable!();- };- engine.record_tree_delta(*root, None, Some(relations(None, None, None)));- engine.record_tree_delta(*a, None, Some(relations(Some(root.raw()), None, Some(b.raw()))));- engine.record_tree_delta(*b, None, Some(relations(Some(root.raw()), Some(a.raw()), None)));- engine.record_tree_delta(*m, None, Some(relations(Some(a.raw()), None, None)));- engine.record_tree_delta(*p, None, Some(relations(Some(m.raw()), None, None)));- engine.record_tree_delta(*c, None, Some(relations(Some(p.raw()), None, None)));- discard_transaction(&mut engine);-- engine.record_tree_delta(- *n,- None,- Some(relations(Some(root.raw()), Some(a.raw()), Some(b.raw()))),- );- engine.record_tree_delta(- *p,- Some(relations(Some(m.raw()), None, None)),- Some(relations(Some(b.raw()), None, None)),- );- engine.apply_staged_tree_deltas();-- assert_eq!(engine.tree.depth(*p), 2);- assert_eq!(engine.tree.depth(*c), 3);-}--#[test]-fn moving_back_after_an_intermediate_tree_apply_restores_depth() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 5];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<_> = raw.into_iter().map(|raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let [root, x, q1, q2, p] = nodes.as_slice() else {- unreachable!();- };- engine.record_tree_delta(*root, None, Some(relations(None, None, None)));- engine.record_tree_delta(*x, None, Some(relations(Some(root.raw()), None, Some(q1.raw()))));- engine.record_tree_delta(*q1, None, Some(relations(Some(root.raw()), Some(x.raw()), None)));- engine.record_tree_delta(*q2, None, Some(relations(Some(q1.raw()), None, None)));- engine.record_tree_delta(*p, None, Some(relations(Some(x.raw()), None, None)));- discard_transaction(&mut engine);-- engine.record_tree_delta(- *p,- Some(relations(Some(x.raw()), None, None)),- Some(relations(Some(q2.raw()), None, None)),- );- engine.apply_staged_tree_deltas();- assert_eq!(engine.tree.depth(*p), 3);-- engine.record_tree_delta(- *p,- Some(relations(Some(q2.raw()), None, None)),- Some(relations(Some(x.raw()), None, None)),- );- engine.apply_staged_tree_deltas();-- assert_eq!(engine.tree.depth(*p), 2);-}--/// Builds `root -> [a, b, c]` through the same delta path C++ drives.-pub(super) fn linear_document() -> (StyleEngine, Vec<StyleNodeID>) {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 4];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();-- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- engine.record_tree_delta(nodes[1], None, Some(relations(Some(nodes[0].raw()), None, None)));- engine.record_tree_delta(- nodes[2],- None,- Some(relations(Some(nodes[0].raw()), Some(nodes[1].raw()), None)),- );- engine.record_tree_delta(- nodes[3],- None,- Some(relations(Some(nodes[0].raw()), Some(nodes[2].raw()), None)),- );- (engine, nodes)-}--#[test]-fn a_node_scoped_acknowledgement_leaves_other_inputs_queued() {- let (mut engine, nodes) = linear_document();- discard_transaction(&mut engine);- for &node in &nodes[1..3] {- add_feature(&mut engine, node, LocalFeatureKey::Class(StyleAtomID(200)));- }- engine.host.journal.acknowledge_node(nodes[1]);- assert_eq!(engine.host.journal.len(), 1);- assert_eq!(- engine.host.journal.pending_old(InputKey::LocalFeature(- nodes[2],- LocalFeatureKey::Class(StyleAtomID(200))- )),- Some(InputValue::Feature(FeatureValue::Absent))- );-}--#[test]-fn a_read_only_record_demand_leaves_the_match_state_as_it_was() {- let (mut engine, nodes) = linear_document();- for &node in &nodes {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, StyleAtomID(100));- }- discard_transaction(&mut engine);- let retained_answers = engine.retained_match_answers.column.clone();- let retained_cascade_inputs = engine.retained_match_answers.cascade_input_column.clone();- let winner_generation = engine.winner_groups.generation();- let published_count = engine.published_match_answers.entries.len();-- // An engine no document hosts computes no records: the demand matches, then declines.- assert!(- engine- .answer_record_demand(- nodes[1],- publication::RecordDemand::Element(bridge::FfiRecordDemand::ElementRead)- )- .is_err()- );- assert_eq!(engine.retained_match_answers.column, retained_answers);- assert_eq!(- engine.retained_match_answers.cascade_input_column,- retained_cascade_inputs- );- assert_eq!(engine.winner_groups.generation(), winner_generation);- assert_eq!(engine.published_match_answers.entries.len(), published_count);- assert!(engine.batch_matching_traversal.is_none());- assert!(engine.demand_records.is_empty());-}--#[test]-fn a_pseudo_record_demand_answers_absence_without_rules() {- let (mut engine, nodes) = linear_document();- for &node in &nodes {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, StyleAtomID(100));- }- discard_transaction(&mut engine);- engine.publish_computed_groups(- computed::ComputedStyleTarget::new(nodes[1], u8::MAX),- &[],- 0,- 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(),- },- );- // ::before, which no rule styles.- let answer = engine.answer_record_demand(- nodes[1],- publication::RecordDemand::PseudoElement(- bridge::FfiPseudoElementRecordDemand::CssomRead,- bridge::FfiDemandedPseudoElement::Before,- ),- );- assert!(- matches!(- answer,- Ok(publication::RecordDemandAnswer::Absent {- custom_property_environment: 0- })- ),- "{answer:?}"- );-}--/// Builds `root -> outer -> inner -> target`.-fn attach_shadow_tree(- engine: &mut StyleEngine,- host: StyleNodeID,- scope: TreeScopeID,- depth: usize,-) -> Vec<StyleNodeID> {- let mut raw = vec![0_u32; depth + 1];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<_> = raw.iter().map(|&id| StyleNodeID::from_raw(id).unwrap()).collect();- engine.record_tree_delta(nodes[0], None, Some(TreeRelations::detached(scope)));- for pair in nodes.windows(2) {- engine.record_tree_delta(- pair[1],- None,- Some(TreeRelations {- parent: Some(pair[0]),- tree_scope: scope,- ..TreeRelations::detached(scope)- }),- );- set_atom_feature(engine, pair[1], LocalFeatureKey::TagName, StyleAtomID(100));- }- engine.set_shadow_root(host, nodes[0]);- engine.set_tree_scope_root(scope, nodes[0]);- nodes-}--fn nested_document() -> (StyleEngine, Vec<StyleNodeID>) {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 4];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- for index in 1..nodes.len() {- engine.record_tree_delta(- nodes[index],- None,- Some(relations(Some(nodes[index - 1].raw()), None, None)),- );- }- for &node in &nodes {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, StyleAtomID(100));- }- (engine, nodes)-}--fn add_guard_target_rule(engine: &mut StyleEngine, guard: StyleAtomID, target: StyleAtomID) -> RuleID {- let program = engine.programs.add(test_selector_program_with_metadata(- ".guard .target",- &[("guard", guard), ("target", target)],- Some(Specificity {- classes: 2,- ..Specificity::default()- }),- None,- ));-- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);- rule-}--fn add_guard_target_rule_in_sheet(- engine: &mut StyleEngine,- sheet_object: StyleSheetObjectID,- guard: StyleAtomID,- target: StyleAtomID,-) -> RuleID {- let program = engine.programs.add(test_selector_program_with_metadata(- ".guard .target",- &[("guard", guard), ("target", target)],- Some(Specificity {- classes: 2,- ..Specificity::default()- }),- None,- ));- let sheet = engine.add_sheet(sheet_object, CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);- rule-}--fn add_guard_universal_rule(engine: &mut StyleEngine, guard: StyleAtomID) {- let program = engine- .programs- .add(test_selector_program(".guard *", &[("guard", guard)]));-- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);-}--fn add_has_descendant_rule(engine: &mut StyleEngine, anchor: StyleAtomID, witness: StyleAtomID) {- let mut builder = selector::SelectorProgramBuilder::new();- let witness_test = builder.push_feature(selector::FeatureTest::Class(witness));- let has_witness = builder.push_relative_exists(relative_selector::RelativeQuery {- axis: RelativeAxis::Descendant,- compound: witness_test,- driving_feature: Some(LocalFeatureKey::Class(witness)),- simple: true,- witness_is_below_the_axis: false,- match_in_shadow_tree: false,- });- let anchor = builder.push_feature(selector::FeatureTest::Class(anchor));- let selector = builder.push_compound(&[anchor, has_witness]);- builder.push_entry(selector);- let program = engine.programs.add(builder.finish());-- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);- engine.set_rule_declared_properties(rule, &[(property_id::COLOR, false)]);-}--#[test]-fn a_nested_arrival_routes_relational_facts_from_the_outer_subtree() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 3];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let anchor = StyleAtomID(200);- let witness = StyleAtomID(201);- add_has_descendant_rule(&mut engine, anchor, witness);-- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- add_feature(&mut engine, nodes[0], LocalFeatureKey::Class(anchor));- discard_transaction(&mut engine);-- engine.record_tree_delta(nodes[1], None, Some(relations(Some(nodes[0].raw()), None, None)));- engine.record_tree_delta(nodes[2], None, Some(relations(Some(nodes[1].raw()), None, None)));- add_feature(&mut engine, nodes[2], LocalFeatureKey::Class(witness));-- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, raw);-}--fn add_has_sibling_rule(engine: &mut StyleEngine, anchor: StyleAtomID, witness: StyleAtomID, axis: RelativeAxis) {- let mut builder = selector::SelectorProgramBuilder::new();- let witness_test = builder.push_feature(selector::FeatureTest::Class(witness));- let has_witness = builder.push_relative_exists(relative_selector::RelativeQuery {- axis,- compound: witness_test,- driving_feature: Some(LocalFeatureKey::Class(witness)),- simple: matches!(axis, RelativeAxis::NextSibling | RelativeAxis::FollowingSibling),- witness_is_below_the_axis: false,- match_in_shadow_tree: false,- });- let anchor = builder.push_feature(selector::FeatureTest::Class(anchor));- let selector = builder.push_compound(&[anchor, has_witness]);- builder.push_entry(selector);- let program = engine.programs.add(builder.finish());-- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);-}--#[test]-fn a_batch_of_arrivals_routes_a_following_sibling_anchor_once() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 6];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let anchor = StyleAtomID(200);- let witness = StyleAtomID(201);- add_has_sibling_rule(&mut engine, anchor, witness, RelativeAxis::FollowingSibling);-- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- engine.record_tree_delta(nodes[1], None, Some(relations(Some(raw[0]), None, None)));- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(anchor));- discard_transaction(&mut engine);-- for index in 2..6 {- engine.record_tree_delta(- nodes[index],- None,- Some(relations(Some(raw[0]), Some(raw[index - 1]), None)),- );- }- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert!(planned.contains(&raw[1]), "the anchor is in the plan");-}--#[test]-fn a_batch_of_departures_routes_a_following_sibling_anchor_once() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 6];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let anchor = StyleAtomID(200);- let witness = StyleAtomID(201);- add_has_sibling_rule(&mut engine, anchor, witness, RelativeAxis::FollowingSibling);-- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- engine.record_tree_delta(nodes[1], None, Some(relations(Some(raw[0]), None, None)));- for index in 2..6 {- engine.record_tree_delta(- nodes[index],- None,- Some(relations(Some(raw[0]), Some(raw[index - 1]), None)),- );- }- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(anchor));- discard_transaction(&mut engine);-- // Two departures from one sequence, and the first one's recorded neighbour leaves right- // after it: the anchors are asked once for the whole sequence, and a seam whose- // neighbours are gone still places itself through the sibling on its other side.- engine.record_tree_delta(- nodes[4],- Some(relations(Some(raw[0]), Some(raw[3]), Some(raw[5]))),- None,- );- engine.record_tree_delta(- nodes[3],- Some(relations(Some(raw[0]), Some(raw[2]), Some(raw[5]))),- None,- );- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert!(planned.contains(&raw[1]), "the anchor is in the plan");-}--#[test]-fn an_arrival_within_the_adjacent_reach_routes_the_anchor() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 4];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let anchor = StyleAtomID(200);- let witness = StyleAtomID(201);- add_has_sibling_rule(&mut engine, anchor, witness, RelativeAxis::NextSibling);-- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- engine.record_tree_delta(nodes[1], None, Some(relations(Some(raw[0]), None, None)));- engine.record_tree_delta(nodes[2], None, Some(relations(Some(raw[0]), Some(raw[1]), None)));- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(anchor));- discard_transaction(&mut engine);-- // An element landing right beside the anchor breaks `.a:has(+ .w)` however little it- // carries, so the anchor is asked.- engine.record_tree_delta(- nodes[3],- None,- Some(relations(Some(raw[0]), Some(raw[1]), Some(raw[2]))),- );- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert!(planned.contains(&raw[1]), "the anchor is in the plan");-}--#[test]-fn an_arrival_beyond_the_adjacent_reach_routes_no_anchor() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 4];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let anchor = StyleAtomID(200);- let witness = StyleAtomID(201);- add_has_sibling_rule(&mut engine, anchor, witness, RelativeAxis::NextSibling);-- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- engine.record_tree_delta(nodes[1], None, Some(relations(Some(raw[0]), None, None)));- engine.record_tree_delta(nodes[2], None, Some(relations(Some(raw[0]), Some(raw[1]), None)));- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(anchor));- discard_transaction(&mut engine);-- // An adjacent chain reaches one step back, so an element landing two steps past the- // anchor cannot have moved `.a:has(+ .w)` and nothing is routed.- engine.record_tree_delta(nodes[3], None, Some(relations(Some(raw[0]), Some(raw[2]), None)));- engine.take_style_transaction_nodes(nodes[0], |_| {});-}--#[test]-fn a_departed_subtree_routes_sibling_subtree_anchors_above_its_parent() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 5];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let anchor = StyleAtomID(200);- let witness = StyleAtomID(201);- add_has_sibling_rule(&mut engine, anchor, witness, RelativeAxis::FollowingSiblingSubtree);-- // root -> [x(.a), p]; p -> [c1, c2]. `x:has(~ p .w)` reaches under p, so c2 leaving has- // to ask x even though nothing beside x moved.- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- engine.record_tree_delta(nodes[1], None, Some(relations(Some(raw[0]), None, None)));- engine.record_tree_delta(nodes[2], None, Some(relations(Some(raw[0]), Some(raw[1]), None)));- engine.record_tree_delta(nodes[3], None, Some(relations(Some(raw[2]), None, None)));- engine.record_tree_delta(nodes[4], None, Some(relations(Some(raw[2]), Some(raw[3]), None)));- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(anchor));- discard_transaction(&mut engine);-- engine.record_tree_delta(nodes[4], Some(relations(Some(raw[2]), Some(raw[3]), None)), None);- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert!(planned.contains(&raw[1]), "the anchor is in the plan");-}--#[test]-fn reparented_witnesses_reach_the_destination_without_fact_changes() {- for axis in [RelativeAxis::Descendant, RelativeAxis::Child] {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 4];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<_> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let card = StyleAtomID(200);- let error = StyleAtomID(201);- let mut builder = selector::SelectorProgramBuilder::new();- let witness_test = builder.push_feature(selector::FeatureTest::Class(error));- let has_witness = builder.push_relative_exists(relative_selector::RelativeQuery {- axis,- compound: witness_test,- driving_feature: Some(LocalFeatureKey::Class(error)),- simple: true,- witness_is_below_the_axis: false,- match_in_shadow_tree: false,- });- let anchor_test = builder.push_feature(selector::FeatureTest::Class(card));- let compound = builder.push_compound(&[anchor_test, has_witness]);- builder.push_entry(compound);- let program = engine.programs.add(builder.finish());- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);-- // Two sibling cards, with the witness initially in the first. No other rule can- // accidentally include the destination in a conservative refresh.- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- engine.record_tree_delta(nodes[1], None, Some(relations(Some(raw[0]), None, Some(raw[2]))));- engine.record_tree_delta(nodes[2], None, Some(relations(Some(raw[0]), Some(raw[1]), None)));- engine.record_tree_delta(nodes[3], None, Some(relations(Some(raw[1]), None, None)));- for node in [nodes[1], nodes[2]] {- add_feature(&mut engine, node, LocalFeatureKey::Class(card));- }- add_feature(&mut engine, nodes[3], LocalFeatureKey::Class(error));- discard_transaction(&mut engine);- engine.record_tree_delta(- nodes[3],- Some(relations(Some(raw[1]), None, None)),- Some(relations(Some(raw[2]), None, None)),- );- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert!(planned.contains(&raw[1]), "{axis:?}: the old anchor lost its witness");- assert!(- planned.contains(&raw[2]),- "{axis:?}: the destination gained a witness without a fact change"- );- }-}--#[test]-fn a_retained_witness_carries_an_anchor_through_its_lifecycle() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 4];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let anchor = StyleAtomID(200);- let witness = StyleAtomID(201);- add_has_descendant_rule(&mut engine, anchor, witness);-- // root -> card(.card) -> [w1(.error), w2]- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- engine.record_tree_delta(nodes[1], None, Some(relations(Some(raw[0]), None, None)));- engine.record_tree_delta(nodes[2], None, Some(relations(Some(raw[1]), None, None)));- engine.record_tree_delta(nodes[3], None, Some(relations(Some(raw[1]), Some(raw[2]), None)));- for (node, class) in [(nodes[1], anchor), (nodes[2], witness)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- for &node in &nodes {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, StyleAtomID(100));- }- discard_transaction(&mut engine);-- assert!(engine.begin_cold_matching_batch(nodes[0]));- assert!(!engine.match_element(nodes[1]).unwrap().is_empty());- let (key, retained) = engine- .retained- .pending_witness_effects- .iter()- .find_map(|effect| match effect {- WitnessEffect::Retain(key, witness) if key.anchor == nodes[1] => Some((*key, *witness)),- _ => None,- })- .expect("matching must produce a positive witness effect");- assert!(matches!(- engine.retained.relational_witnesses.lookup(key),- Lookup::Missing(_)- ));- engine.match_element(nodes[2]).unwrap();- engine.end_cold_matching_batch();- assert!(engine.retained.pending_witness_effects.is_empty());- assert!(matches!(engine.retained.relational_witnesses.lookup(key), Lookup::Known(&node) if node == retained));-- // A second witness appearing cannot flip an anchor that is already true, so the retained- // witness answers for it and nothing is routed.- add_feature(&mut engine, nodes[3], LocalFeatureKey::Class(witness));- let mut planned = Vec::new();- engine.take_style_transaction(nodes[0], |_, _, reactions| {- planned.extend(reactions.iter().map(|reaction| reaction.style_node));- });- assert_eq!(engine.counters().get(Counter::RelationalAnchorsSkippedByWitness), 1);- assert!(!planned.contains(&raw[1]), "the anchor stays out of the plan");-- // The witness the entry does not name losing the feature cannot flip the anchor either,- // and the retained witness proves it without any evaluation of the anchor.- remove_feature(&mut engine, nodes[3], LocalFeatureKey::Class(witness));- let mut planned = Vec::new();- engine.take_style_transaction(nodes[0], |_, _, reactions| {- planned.extend(reactions.iter().map(|reaction| reaction.style_node));- });- assert_eq!(engine.counters().get(Counter::RelationalAnchorsSkippedByWitness), 2);- assert!(!planned.contains(&raw[1]), "the anchor still stays out of the plan");-- // The retained witness losing the feature is exactly what the entry cannot vouch past:- // the anchor is routed, recomputes to false, and the entry is cleared.- remove_feature(&mut engine, nodes[2], LocalFeatureKey::Class(witness));- let mut planned = Vec::new();- engine.take_style_transaction(nodes[0], |_, _, reactions| {- planned.extend(reactions.iter().map(|reaction| reaction.style_node));- });- assert!(- planned.contains(&raw[1]),- "the anchor is asked once its witness is gone"- );- assert!(engine.match_element(nodes[1]).unwrap().is_empty(), "no witness left");-- // A witness returning is routed rather than skipped: false-to-true discovery never- // consults a witness, it creates one.- add_feature(&mut engine, nodes[2], LocalFeatureKey::Class(witness));- let mut planned = Vec::new();- engine.take_style_transaction(nodes[0], |_, _, reactions| {- planned.extend(reactions.iter().map(|reaction| reaction.style_node));- });- assert!(planned.contains(&raw[1]));- assert!(!engine.match_element(nodes[1]).unwrap().is_empty());- assert_eq!(engine.counters().get(Counter::RelationalAnchorsSkippedByWitness), 2);-}--#[test]-fn a_retained_witness_absorbs_arrivals_into_a_watched_sequence() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 5];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let anchor = StyleAtomID(200);- let witness = StyleAtomID(201);- let other = StyleAtomID(202);- add_has_sibling_rule(&mut engine, anchor, witness, RelativeAxis::FollowingSibling);-- // root -> [a(.a), b(.other), w(.w)]- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- engine.record_tree_delta(nodes[1], None, Some(relations(Some(raw[0]), None, None)));- engine.record_tree_delta(nodes[2], None, Some(relations(Some(raw[0]), Some(raw[1]), None)));- engine.record_tree_delta(nodes[3], None, Some(relations(Some(raw[0]), Some(raw[2]), None)));- for (node, class) in [(nodes[1], anchor), (nodes[2], other), (nodes[3], witness)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);- assert!(!engine.match_element(nodes[1]).unwrap().is_empty());-- // An element landing in the sequence moves the seams, but a `~` witness that still follows- // the anchor still witnesses it, so the anchor drops out of the plan.- engine.record_tree_delta(- nodes[4],- None,- Some(relations(Some(raw[0]), Some(raw[2]), Some(raw[3]))),- );- let mut planned = Vec::new();- engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes));- assert_eq!(engine.counters().get(Counter::RelationalAnchorsSkippedByWitness), 1);- assert!(!planned.contains(&raw[1]), "the anchor stays out of the plan");-- // The witness itself departing is a different matter.- engine.record_tree_delta(nodes[3], Some(relations(Some(raw[0]), Some(raw[4]), None)), None);- let mut planned = Vec::new();- engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes));- assert!(planned.contains(&raw[1]), "the anchor is asked once its witness left");-}--#[test]-fn an_element_landing_between_an_anchor_and_its_adjacent_witness_routes_it() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 4];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let anchor = StyleAtomID(200);- let witness = StyleAtomID(201);- let other = StyleAtomID(202);- add_has_sibling_rule(&mut engine, anchor, witness, RelativeAxis::NextSibling);-- // root -> [a(.a), w(.w)]- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- engine.record_tree_delta(nodes[1], None, Some(relations(Some(raw[0]), None, None)));- engine.record_tree_delta(nodes[2], None, Some(relations(Some(raw[0]), Some(raw[1]), None)));- for (node, class) in [(nodes[1], anchor), (nodes[2], witness)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);- assert!(!engine.match_element(nodes[1]).unwrap().is_empty());-- // The arrival breaks the adjacency the retained witness proved, so the entry cannot vouch- // for the anchor and it is routed.- engine.record_tree_delta(- nodes[3],- None,- Some(relations(Some(raw[0]), Some(raw[1]), Some(raw[2]))),- );- add_feature(&mut engine, nodes[3], LocalFeatureKey::Class(other));- let mut planned = Vec::new();- engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes));- assert_eq!(engine.counters().get(Counter::RelationalAnchorsSkippedByWitness), 0);- assert!(planned.contains(&raw[1]), "the anchor is in the plan");- assert!(- engine.match_element(nodes[1]).unwrap().is_empty(),- "the adjacency is broken"- );-}--fn add_guard_sibling_target_rule(engine: &mut StyleEngine, guard: StyleAtomID, target: StyleAtomID) -> RuleID {- let program = engine.programs.add(test_selector_program(- ".guard ~ .target",- &[("guard", guard), ("target", target)],- ));-- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);- rule-}--#[test]-fn hover_requires_style_state_only_when_an_origin_may_be_present() {- let (mut engine, nodes) = linear_document();- let first = StyleAtomID(200);- let second = StyleAtomID(201);- let mut builder = selector::SelectorProgramBuilder::new();- let first_class = builder.push_feature(selector::FeatureTest::Class(first));- let second_class = builder.push_feature(selector::FeatureTest::Class(second));- let either_class = builder.push_any_of(&[first_class, second_class]);- let hover = builder.push(selector::SelectorOp::State(StateFact::Hover));- let subject = builder.push_compound(&[either_class, hover]);- builder.push_entry(subject);- let program = engine.programs.add(builder.finish());- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);- discard_transaction(&mut engine);- assert!(!engine.hover_needs_style_state(nodes[0]));-- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(first));- discard_transaction(&mut engine);- assert!(engine.hover_needs_style_state(nodes[0]));- remove_feature(&mut engine, nodes[1], LocalFeatureKey::Class(first));- discard_transaction(&mut engine);- assert!(!engine.hover_needs_style_state(nodes[0]));-- engine- .facts- .postings_mut()- .drop_posting(SelectorPostingKey::Class(second));- assert!(engine.hover_needs_style_state(nodes[0]));-}--fn add_hover_sibling_target_rule(engine: &mut StyleEngine, target: StyleAtomID) {- let mut builder = selector::SelectorProgramBuilder::new();- let hover = builder.push(selector::SelectorOp::State(StateFact::Hover));- let preceding_sibling = builder.push(selector::SelectorOp::PrecedingSibling(hover));- let target = builder.push_feature(selector::FeatureTest::Class(target));- let selector = builder.push_compound(&[target, preceding_sibling]);- builder.push_entry(selector);- let program = engine.programs.add(builder.finish());-- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);-}--fn add_focused_grandchild_rule(engine: &mut StyleEngine, guard: StyleAtomID, mid: StyleAtomID) {- let mut builder = selector::SelectorProgramBuilder::new();- let guard_test = builder.push_feature(selector::FeatureTest::Class(guard));- let guard_parent = builder.push(selector::SelectorOp::Parent(guard_test));- let mid_test = builder.push_feature(selector::FeatureTest::Class(mid));- let mid_compound = builder.push_compound(&[mid_test, guard_parent]);- let mid_parent = builder.push(selector::SelectorOp::Parent(mid_compound));- let focus = builder.push(selector::SelectorOp::State(StateFact::Focus));- let subject = builder.push_compound(&[focus, mid_parent]);- builder.push_entry(subject);- let program = engine.programs.add(builder.finish());-- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);-}--#[test]-fn an_unfocused_subject_state_routes_to_no_descendant() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let mid = StyleAtomID(201);- add_focused_grandchild_rule(&mut engine, guard, mid);- add_feature(&mut engine, nodes[2], LocalFeatureKey::Class(mid));- discard_transaction(&mut engine);-- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- let batch_nodes_before = engine.counters().get(Counter::ExactRegionBatchNodes);- let convergence_nodes_before = engine.counters().get(Counter::PrefixConvergenceNodes);- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert!(planned.is_empty());- assert_eq!(- engine.counters().get(Counter::ExactRegionBatchNodes),- batch_nodes_before- );- assert_eq!(- engine.counters().get(Counter::PrefixConvergenceNodes),- convergence_nodes_before- );-- engine.record_input(- InputKey::State(nodes[3], StateFact::Focus),- InputValue::State(false),- InputValue::State(true),- );- discard_transaction(&mut engine);-- remove_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert!(planned.contains(&nodes[3].raw()));-}--#[test]-fn clearing_state_while_departing_routes_following_siblings() {- let (mut engine, nodes) = linear_document();- let target = StyleAtomID(200);- add_hover_sibling_target_rule(&mut engine, target);- engine.record_input(- InputKey::State(nodes[1], StateFact::Hover),- InputValue::State(false),- InputValue::State(true),- );- add_feature(&mut engine, nodes[2], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);- engine.begin_adaptive_cold_matching_batch(nodes[0]);- engine.match_element(nodes[2]).unwrap();- engine.end_cold_matching_batch();-- engine.record_input(- InputKey::State(nodes[1], StateFact::Hover),- InputValue::State(true),- InputValue::State(false),- );- engine.record_tree_delta(- nodes[1],- Some(relations(Some(nodes[0].raw()), None, Some(nodes[2].raw()))),- None,- );-- let mut published = Vec::new();- assert!(engine.take_style_transaction(nodes[0], |_, _, reactions| {- published.extend(reactions.iter().map(|reaction| reaction.style_node));- }));- assert!(- published.contains(&nodes[2].raw()),- "the following sibling is published: {published:?}"- );-}--/// An always-true positional test keeps a compound off every linear chain without changing-/// what it matches, so tests of the exact fallback machinery keep their workload now that-/// plain sibling chains answer from the prefix automaton.-/// A truth-neutral operand that keeps its compound off the prefix automaton: the doubly-/// negated positional test matches every element, and negation is neither prefix-local nor-/// canonical, so fixtures built with this stay on the exact match evaluator.-fn push_all_positions(builder: &mut selector::SelectorProgramBuilder) -> selector::SelectorNodeID {- let position = builder.push(selector::SelectorOp::NthPosition(selector::NthPosition {- step: 1,- offset: 0,- from_end: false,- of_selector: None,- of_type: false,- }));- let negated = builder.push(selector::SelectorOp::Not(position));- builder.push(selector::SelectorOp::Not(negated))-}--fn add_guard_sibling_target_fallback_rule(engine: &mut StyleEngine, guard: StyleAtomID, target: StyleAtomID) -> RuleID {- let mut builder = selector::SelectorProgramBuilder::new();- let guard = builder.push_feature(selector::FeatureTest::Class(guard));- let preceding_sibling = builder.push(selector::SelectorOp::PrecedingSibling(guard));- let target = builder.push_feature(selector::FeatureTest::Class(target));- let all_positions = push_all_positions(&mut builder);- let selector = builder.push_compound(&[target, all_positions, preceding_sibling]);- builder.push_entry(selector);- let program = engine.programs.add(builder.finish());-- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);- rule-}--fn add_guard_target_selector_list_rule(- engine: &mut StyleEngine,- first_guard: StyleAtomID,- second_guard: StyleAtomID,- target: StyleAtomID,-) -> RuleID {- let program = engine.programs.add(test_selector_program(- ".first-guard .target, .second-guard .target",- &[- ("first-guard", first_guard),- ("second-guard", second_guard),- ("target", target),- ],- ));-- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);- rule-}--fn add_target_rule_with_origin(- engine: &mut StyleEngine,- sheet_object: StyleSheetObjectID,- target: StyleAtomID,- origin: CascadeOrigin,-) -> RuleID {- let program = engine- .programs- .add(test_class_selector_program(".target", &[("target", target)], None));-- let sheet = engine.add_sheet(sheet_object, origin);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);- rule-}--fn add_target_rule(engine: &mut StyleEngine, sheet_object: StyleSheetObjectID, target: StyleAtomID) -> RuleID {- add_target_rule_with_origin(engine, sheet_object, target, CascadeOrigin::Author)-}--/// Declares the longhands beside one custom property, which never reaches the winner columns and-/// so leaves the rule's declarations incomplete.-fn set_rule_declared_properties_beside_a_custom_property(- engine: &mut StyleEngine,- rule: RuleID,- declared: &[(u16, bool)],-) {- let declared: Vec<DeclaredProperty> = declared- .iter()- .map(|&(property, important)| DeclaredProperty {- property,- important,- operator: CascadeOperator::Declared,- value: SpecifiedValueID((u64::from(rule.0) << 16) ^ u64::from(property)),- })- .collect();- let custom = super::program::CustomDeclaration {- name: StyleAtomID(0xC0FFEE),- important: false,- operator: CascadeOperator::Declared,- value: SpecifiedValueID(u64::from(rule.0) << 32),- };- engine.set_rule_declared_properties_with_written_values(rule, &declared, Vec::new(), vec![custom], Vec::new());-}--fn add_selector_list_rule(- engine: &mut StyleEngine,- first: StyleAtomID,- second: StyleAtomID,-) -> (RuleID, SelectorProgramID) {- let program = engine.programs.add(test_class_selector_program(- ".first, .second",- &[("first", first), ("second", second)],- None,- ));- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);- (rule, program)-}--fn add_custom_state_rule(- engine: &mut StyleEngine,- sheet_object: StyleSheetObjectID,- state: StyleAtomID,- matches_state: bool,-) -> RuleID {- let selector_text = if matches_state {- ":state(target)"- } else {- ":not(:state(target))"- };- let program = engine- .programs- .add(test_class_selector_program(selector_text, &[("target", state)], None));-- let sheet = engine.add_sheet(sheet_object, CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);- rule-}--fn concrete_rule_match(- engine: &StyleEngine,- node: StyleNodeID,- rule: RuleID,- cascade_order: u32,- pseudo_element: Option<PseudoElementTarget>,-) -> RuleMatch {- RuleMatch {- node,- pseudo_element,- rule,- program: engine.current_rule_version(rule).selector_program.unwrap(),- entry: 0,- cascade_order,- specificity: Specificity {- classes: 1,- ..Specificity::default()- },- tree_scope: TreeScopeID::DOCUMENT,- scope_proximity: u32::MAX,- }-}--fn add_pseudo_target_rule(- engine: &mut StyleEngine,- sheet_object: StyleSheetObjectID,- target: StyleAtomID,- pseudo: PseudoElementTarget,-) -> RuleID {- let program = engine.programs.add(test_class_selector_program(- ".target",- &[("target", target)],- Some(pseudo),- ));- let sheet = engine.add_sheet(sheet_object, CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);- rule-}--fn commit_test_setup(engine: &mut StyleEngine) {- discard_transaction(engine);-}--#[test]-fn cascade_matching_discards_rules_that_lose_every_property() {- let (mut engine, nodes) = linear_document();- let lower = add_target_rule(&mut engine, StyleSheetObjectID(1), StyleAtomID(200));- let winner = add_target_rule(&mut engine, StyleSheetObjectID(2), StyleAtomID(201));- engine.set_rule_declared_properties(lower, &[(1, false)]);- engine.set_rule_declared_properties(winner, &[(1, false)]);- commit_test_setup(&mut engine);- let matches = vec![- concrete_rule_match(&engine, nodes[0], lower, 0, None),- concrete_rule_match(&engine, nodes[0], winner, 1, None),- ];-- let compacted = engine.matches_for_cascade(matches, false, None);-- assert_eq!(compacted.len(), 1);- assert_eq!(compacted[0].rule, winner);-}--#[test]-fn cascade_matching_publishes_the_same_top_1_winners_it_compacts() {- let (mut engine, nodes) = linear_document();- let lower = add_target_rule(&mut engine, StyleSheetObjectID(1), StyleAtomID(200));- let later = add_target_rule(&mut engine, StyleSheetObjectID(2), StyleAtomID(201));- engine.set_rule_declared_properties(lower, &[(1, false), (2, false)]);- engine.set_rule_declared_properties(later, &[(1, false)]);- commit_test_setup(&mut engine);- let matches = vec![- concrete_rule_match(&engine, nodes[0], lower, 0, None),- concrete_rule_match(&engine, nodes[0], later, 1, None),- ];-- let compacted = engine.matches_for_cascade(matches, false, Some(nodes[0]));-- assert_eq!(- compacted.iter().map(|entry| entry.rule).collect::<Vec<_>>(),- vec![lower, later]- );- let key = WinnerGroupKey::current(nodes[0], engine.program.version());- assert!(- matches!(engine.winner_groups.winner(key, 1), Lookup::Known(winner) if winner.source == WinnerSource::Rule(later))- );- assert!(- matches!(engine.winner_groups.winner(key, 2), Lookup::Known(winner) if winner.source == WinnerSource::Rule(lower))- );- assert_eq!(engine.counters().get(Counter::CascadeNodeHandlesPublished), 1);- assert_eq!(engine.counters().get(Counter::CascadeStatesInterned), 1);- assert_eq!(engine.counters().get(Counter::CascadeWinnerGroupsInterned), 1);- assert_eq!(engine.counters().get(Counter::CascadeWinnerEntriesInterned), 2);-}--#[test]-fn a_repeated_match_list_publishes_what_its_first_compaction_decided() {- let (mut engine, nodes) = linear_document();- let losing = add_target_rule(&mut engine, StyleSheetObjectID(1), StyleAtomID(200));- let lower = add_target_rule(&mut engine, StyleSheetObjectID(2), StyleAtomID(201));- let later = add_target_rule(&mut engine, StyleSheetObjectID(3), StyleAtomID(202));- engine.set_rule_declared_properties(losing, &[(1, false)]);- engine.set_rule_declared_properties(lower, &[(1, false), (2, false)]);- engine.set_rule_declared_properties(later, &[(1, false)]);- commit_test_setup(&mut engine);- let matches_of = |engine: &StyleEngine, node| {- vec![- concrete_rule_match(engine, node, losing, 0, None),- concrete_rule_match(engine, node, lower, 1, None),- concrete_rule_match(engine, node, later, 2, None),- ]- };-- // The second list marks it as one to remember, and the third publishes what was remembered.- for node in [nodes[0], nodes[1], nodes[2]] {- let compacted = engine.matches_for_cascade(matches_of(&engine, node), false, Some(node));-- assert_eq!(- compacted.iter().map(|entry| entry.rule).collect::<Vec<_>>(),- vec![lower, later]- );- let key = WinnerGroupKey::current(node, engine.program.version());- assert!(- matches!(engine.winner_groups.winner(key, 1), Lookup::Known(winner) if winner.source == WinnerSource::Rule(later))- );- assert!(- matches!(engine.winner_groups.winner(key, 2), Lookup::Known(winner) if winner.source == WinnerSource::Rule(lower))- );- }- assert_eq!(engine.counters().get(Counter::CascadeNodeHandlesPublished), 3);- assert_eq!(engine.counters().get(Counter::CascadeStatesInterned), 1);-}--#[test]-fn a_pseudo_winner_keeps_only_its_own_target_matches() {- let (mut engine, nodes) = linear_document();- let before = PseudoElementTarget::new(PseudoElementKind(0));- let after = PseudoElementTarget::new(PseudoElementKind(1));- let list = add_target_rule(&mut engine, StyleSheetObjectID(1), StyleAtomID(200));- let later = add_target_rule(&mut engine, StyleSheetObjectID(2), StyleAtomID(201));- engine.set_rule_declared_properties(list, &[(1, false)]);- engine.set_rule_declared_properties(later, &[(1, false)]);- commit_test_setup(&mut engine);- let mut list_after = concrete_rule_match(&engine, nodes[0], list, 1, Some(after));- list_after.entry = 1;- let matches = vec![- concrete_rule_match(&engine, nodes[0], list, 0, Some(before)),- list_after,- concrete_rule_match(&engine, nodes[0], later, 2, Some(before)),- ];-- let compacted = engine.matches_for_cascade(matches, false, Some(nodes[0]));-- assert_eq!(- compacted- .iter()- .map(|entry| (entry.rule, entry.pseudo_element))- .collect::<Vec<_>>(),- vec![(list, Some(after)), (later, Some(before))]- );-}--#[test]-fn cascade_directed_matching_equals_compacting_the_exact_answer() {- let (mut engine, nodes) = linear_document();- let target = StyleAtomID(200);- let lower = add_target_rule(&mut engine, StyleSheetObjectID(1), target);- let winner = add_target_rule(&mut engine, StyleSheetObjectID(2), target);- engine.set_rule_declared_properties(lower, &[(1, false)]);- engine.set_rule_declared_properties(winner, &[(1, false)]);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- let exact = engine.match_element(nodes[1]).unwrap();- let expected = engine.matches_for_cascade(exact, false, None);- let rejected_before = engine.counters().get(Counter::CascadeCandidatesRejectedByWinner);- let actual = engine.match_element_for_cascade(nodes[1]).unwrap();-- assert_eq!(actual, expected);- assert_eq!(actual.len(), 1);- assert_eq!(actual[0].rule, winner);- assert_eq!(- engine.counters().get(Counter::CascadeCandidatesRejectedByWinner) - rejected_before,- 1- );-}--#[test]-fn an_incomplete_matching_rule_blocks_cascade_directed_pruning() {- let (mut engine, nodes) = linear_document();- let target = StyleAtomID(200);- let lower = add_target_rule(&mut engine, StyleSheetObjectID(1), target);- let winner = add_target_rule(&mut engine, StyleSheetObjectID(2), target);- let incomplete = add_target_rule(&mut engine, StyleSheetObjectID(3), target);- engine.set_rule_declared_properties(lower, &[(1, false)]);- engine.set_rule_declared_properties(winner, &[(1, false)]);- set_rule_declared_properties_beside_a_custom_property(&mut engine, incomplete, &[(2, false)]);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- let exact = engine.match_element(nodes[1]).unwrap();- let expected = engine.matches_for_cascade(exact, false, None);- let rejected_before = engine.counters().get(Counter::CascadeCandidatesRejectedByWinner);- let actual = engine.match_element_for_cascade(nodes[1]).unwrap();-- assert_eq!(actual, expected);- assert_eq!(actual.len(), 3);- assert_eq!(- engine.counters().get(Counter::CascadeCandidatesRejectedByWinner),- rejected_before- );-}--#[test]-fn cascade_matching_keeps_rules_that_win_different_properties() {- let (mut engine, nodes) = linear_document();- let first = add_target_rule(&mut engine, StyleSheetObjectID(1), StyleAtomID(200));- let second = add_target_rule(&mut engine, StyleSheetObjectID(2), StyleAtomID(201));- engine.set_rule_declared_properties(first, &[(1, false)]);- engine.set_rule_declared_properties(second, &[(2, false)]);- commit_test_setup(&mut engine);- let matches = vec![- concrete_rule_match(&engine, nodes[0], first, 0, None),- concrete_rule_match(&engine, nodes[0], second, 1, None),- ];-- let compacted = engine.matches_for_cascade(matches, false, None);-- assert_eq!(- compacted.iter().map(|entry| entry.rule).collect::<Vec<_>>(),- vec![first, second]- );-}--#[test]-fn cascade_matching_accounts_for_important_declarations() {- let (mut engine, nodes) = linear_document();- let important = add_target_rule(&mut engine, StyleSheetObjectID(1), StyleAtomID(200));- let later = add_target_rule(&mut engine, StyleSheetObjectID(2), StyleAtomID(201));- engine.set_rule_declared_properties(important, &[(1, true)]);- engine.set_rule_declared_properties(later, &[(1, false)]);- commit_test_setup(&mut engine);- let matches = vec![- concrete_rule_match(&engine, nodes[0], important, 0, None),- concrete_rule_match(&engine, nodes[0], later, 1, None),- ];-- let compacted = engine.matches_for_cascade(matches, false, None);-- assert_eq!(compacted.len(), 1);- assert_eq!(compacted[0].rule, important);-}--#[test]-fn a_layer_reorder_patches_the_retained_compact_answer() {- let (mut engine, nodes) = linear_document();- let target = StyleAtomID(200);- let base_rule = add_target_rule(&mut engine, StyleSheetObjectID(1), target);- let theme_rule = add_target_rule(&mut engine, StyleSheetObjectID(2), target);- engine.set_rule_declared_properties(base_rule, &[(1, false)]);- engine.set_rule_declared_properties(theme_rule, &[(1, false)]);- let base = CascadeLayerID(1);- let theme = CascadeLayerID(2);- engine.set_layer_order(TreeScopeID::DOCUMENT, &[base, theme]);- engine.set_rule_layer(base_rule, base);- engine.set_rule_layer(theme_rule, theme);- engine.set_rule_in_a_layer(base_rule);- engine.set_rule_in_a_layer(theme_rule);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- let exact_answer = engine.match_element(nodes[1]).unwrap();- let old_answer = engine.matches_for_cascade(exact_answer.clone(), false, Some(nodes[1]));- engine.remember_retained_match_answer(nodes[1], &exact_answer);- engine.remember_cascade_input(nodes[1], &old_answer);- assert_eq!(old_answer.len(), 1);- assert_eq!(old_answer[0].rule, theme_rule);-- engine.set_layer_order(TreeScopeID::DOCUMENT, &[theme, base]);- engine.record_layer_statement(engine.program.rule_sheet(base_rule));- let patches_before = engine.counters().get(Counter::RetainedMatchAnswerDeltaPatches);- let feature_tests_before = engine.counters().get(Counter::LocalFeatureTests);- let selector_upqueries_before = engine.counters().get(Counter::SelectorTruthRepairUpqueries);- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes[1].raw()]);- assert_eq!(- engine.counters().get(Counter::RetainedMatchAnswerDeltaPatches),- patches_before + 1- );- assert_eq!(engine.counters().get(Counter::LocalFeatureTests), feature_tests_before);- assert_eq!(- engine.counters().get(Counter::SelectorTruthRepairUpqueries),- selector_upqueries_before- );-- engine.begin_adaptive_cold_matching_batch(nodes[0]);- let new_answer = engine.match_element_for_cascade(nodes[1]).unwrap();- engine.end_cold_matching_batch();- assert_eq!(new_answer.len(), 1);- assert_eq!(new_answer[0].rule, base_rule);- assert_eq!(engine.counters().get(Counter::RetainedMatchAnswerReuses), 1);-}--#[test]-fn an_unused_layer_priority_shift_stops_before_recomputation() {- let (mut engine, nodes) = linear_document();- let target = StyleAtomID(200);- let base_rule = add_target_rule(&mut engine, StyleSheetObjectID(1), target);- let theme_rule = add_target_rule(&mut engine, StyleSheetObjectID(2), target);- engine.set_rule_declared_properties(base_rule, &[(1, false)]);- engine.set_rule_declared_properties(theme_rule, &[(1, false)]);- let base = CascadeLayerID(1);- let theme = CascadeLayerID(2);- let unused = CascadeLayerID(3);- engine.set_layer_order(TreeScopeID::DOCUMENT, &[base, theme]);- engine.set_rule_layer(base_rule, base);- engine.set_rule_layer(theme_rule, theme);- engine.set_rule_in_a_layer(base_rule);- engine.set_rule_in_a_layer(theme_rule);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- let exact_answer = engine.match_element(nodes[1]).unwrap();- let old_answer = engine.matches_for_cascade(exact_answer.clone(), false, Some(nodes[1]));- engine.remember_retained_match_answer(nodes[1], &exact_answer);- engine.remember_cascade_input(nodes[1], &old_answer);- assert_eq!(old_answer.len(), 1);- assert_eq!(old_answer[0].rule, theme_rule);-- engine.set_layer_order(TreeScopeID::DOCUMENT, &[base, unused, theme]);- engine.record_layer_statement(engine.program.rule_sheet(base_rule));- let mut planned = Vec::new();- assert!(engine.take_style_transaction(nodes[0], |_, _, reactions| {- planned.extend(reactions.iter().map(|reaction| reaction.style_node));- }));- assert!(planned.is_empty());-- engine.begin_adaptive_cold_matching_batch(nodes[0]);- let new_answer = engine.match_element_for_cascade(nodes[1]).unwrap();- engine.end_cold_matching_batch();- assert_eq!(new_answer.len(), 1);- assert_eq!(new_answer[0].rule, theme_rule);-}--#[test]-fn an_evicted_retained_match_answer_falls_back_to_cold_matching() {- let (mut engine, nodes) = linear_document();- let target = StyleAtomID(200);- let base_rule = add_target_rule(&mut engine, StyleSheetObjectID(1), target);- let theme_rule = add_target_rule(&mut engine, StyleSheetObjectID(2), target);- engine.set_rule_declared_properties(base_rule, &[(1, false)]);- engine.set_rule_declared_properties(theme_rule, &[(1, false)]);- let base = CascadeLayerID(1);- let theme = CascadeLayerID(2);- engine.set_layer_order(TreeScopeID::DOCUMENT, &[base, theme]);- engine.set_rule_layer(base_rule, base);- engine.set_rule_layer(theme_rule, theme);- engine.set_rule_in_a_layer(base_rule);- engine.set_rule_in_a_layer(theme_rule);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- let exact_answer = engine.match_element(nodes[1]).unwrap();- let compact_answer = engine.matches_for_cascade(exact_answer.clone(), false, None);- engine.remember_retained_match_answer(nodes[1], &exact_answer);- engine.remember_cascade_input(nodes[1], &compact_answer);- engine- .retained- .retained_match_answers- .clear(&mut engine.retained.match_answers);- assert!(matches!(- engine.retained_match_answer(nodes[1]),- Lookup::Missing(gap) if gap == nodes[1]- ));- assert!(matches!(- engine.retained_match_answers.cascade_input_lookup(nodes[1]),- Lookup::Known(cascade_input) if *cascade_input != MatchAnswerID::default()- ));-- engine.set_layer_order(TreeScopeID::DOCUMENT, &[theme, base]);- engine.record_layer_statement(engine.program.rule_sheet(base_rule));- let misses_before = engine.counters().get(Counter::RetainedMatchAnswerPatchMisses);- let mut planned = Vec::new();- assert!(engine.take_style_transaction(nodes[0], |_, _, reactions| {- planned.extend(reactions.iter().map(|reaction| reaction.style_node));- }));- assert_eq!(planned, vec![nodes[1].raw()]);- assert_eq!(- engine.counters().get(Counter::RetainedMatchAnswerPatchMisses),- misses_before + 1- );-- engine.begin_adaptive_cold_matching_batch(nodes[0]);- let new_answer = engine.match_element_for_cascade(nodes[1]).unwrap();- engine.end_cold_matching_batch();- assert_eq!(new_answer.len(), 1);- assert_eq!(new_answer[0].rule, base_rule);- assert_eq!(- engine- .counters()- .get(Counter::MatchElementCallsDuringPublishedStyleTransaction),- 0- );-}--#[test]-fn layer_order_inputs_only_name_rules_whose_rank_changed() {- let (mut engine, _) = linear_document();- let base = CascadeLayerID(1);- let middle = CascadeLayerID(2);- let theme = CascadeLayerID(3);- let mut rules = Vec::new();- for (index, layer) in [base, middle, theme].into_iter().enumerate() {- let rule = add_target_rule(&mut engine, StyleSheetObjectID(index as u32 + 1), StyleAtomID(200));- engine.set_rule_layer(rule, layer);- engine.set_rule_in_a_layer(rule);- rules.push(rule);- }- engine.set_layer_order(TreeScopeID::DOCUMENT, &[base, middle, theme]);- discard_transaction(&mut engine);-- engine.set_layer_order(TreeScopeID::DOCUMENT, &[theme, middle, base]);- let transaction = engine.take_transaction();- let mut changed: Vec<_> = transaction.program_joins.iter().map(|delta| delta.rule).collect();- changed.sort_unstable();- assert_eq!(changed, vec![rules[0], rules[2]]);- engine.release_transaction(transaction);-- engine.set_layer_order(TreeScopeID::DOCUMENT, &[theme, middle, base, CascadeLayerID(4)]);- let transaction = engine.take_transaction();- assert!(transaction.program_joins.is_empty());- engine.release_transaction(transaction);-}--#[test]-fn an_evicted_answer_payload_repairs_to_its_retained_identity() {- let (mut engine, nodes) = linear_document();- let target = StyleAtomID(200);- let losing_rule = add_target_rule(&mut engine, StyleSheetObjectID(1), target);- let winning_rule = add_target_rule(&mut engine, StyleSheetObjectID(2), target);- engine.set_rule_declared_properties(losing_rule, &[(1, false)]);- engine.set_rule_declared_properties(winning_rule, &[(1, false)]);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- let exact_answer = engine.match_element(nodes[1]).unwrap();- let compact_answer = engine.matches_for_cascade(exact_answer.clone(), false, None);- assert_eq!(compact_answer.len(), 1);- assert_eq!(compact_answer[0].rule, winning_rule);- engine.remember_retained_match_answer(nodes[1], &exact_answer);- engine.remember_cascade_input(nodes[1], &compact_answer);- engine- .retained- .retained_match_answers- .clear(&mut engine.retained.match_answers);-- engine.set_rule_conditions_hold(losing_rule, false);- let repairs_before = engine.counters().get(Counter::PublishedMatchAnswerIdentityRepairs);- let stops_before = engine.counters().get(Counter::PublishedMatchAnswerIdentityRepairStops);- let mut planned = Vec::new();- assert!(engine.take_style_transaction(nodes[0], |_, _, reactions| {- planned.extend(reactions.iter().map(|reaction| reaction.style_node));- }));- assert!(planned.is_empty());- assert_eq!(- engine.counters().get(Counter::PublishedMatchAnswerIdentityRepairs),- repairs_before + 1- );- assert_eq!(- engine.counters().get(Counter::PublishedMatchAnswerIdentityRepairStops),- stops_before + 1- );-}--#[test]-fn an_exact_unchanged_cascade_stops_before_style_recomputation() {- let (mut engine, nodes) = linear_document();- let first_class = StyleAtomID(200);- let second_class = StyleAtomID(201);- let first_rule = add_target_rule(&mut engine, StyleSheetObjectID(1), first_class);- let second_rule = add_target_rule(&mut engine, StyleSheetObjectID(2), second_class);- let value = SpecifiedValueID(101);- engine.set_rule_declared_properties_with_values(first_rule, &[(1, false, value)]);- engine.set_rule_declared_properties_with_values(second_rule, &[(1, false, value)]);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(first_class));- discard_transaction(&mut engine);-- let old_answer = engine.match_element_for_cascade(nodes[1]).unwrap();- assert_eq!(old_answer.len(), 1);- assert_eq!(old_answer[0].rule, first_rule);- publish_current_cascade_as_computed(&mut engine, nodes[1]);-- remove_feature(&mut engine, nodes[1], LocalFeatureKey::Class(first_class));- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(second_class));- let stops_before = engine.counters().get(Counter::PublishedExactCascadeStops);- let mut planned = Vec::new();- assert!(engine.take_style_transaction(nodes[0], |_, _, reactions| {- planned.extend(reactions.iter().map(|reaction| reaction.style_node));- }));-- assert!(planned.is_empty());- assert_eq!(- engine.counters().get(Counter::PublishedExactCascadeStops),- stops_before + 1- );- let current = engine.match_element_for_cascade(nodes[1]).unwrap();- assert_eq!(current.len(), 1);- assert_eq!(current[0].rule, second_rule);-}--#[test]-fn a_changed_exact_cascade_is_still_published_for_recomputation() {- let (mut engine, nodes) = linear_document();- let first_class = StyleAtomID(200);- let second_class = StyleAtomID(201);- let first_rule = add_target_rule(&mut engine, StyleSheetObjectID(1), first_class);- let second_rule = add_target_rule(&mut engine, StyleSheetObjectID(2), second_class);- engine.set_rule_declared_properties_with_values(first_rule, &[(1, false, SpecifiedValueID(101))]);- engine.set_rule_declared_properties_with_values(second_rule, &[(1, false, SpecifiedValueID(102))]);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(first_class));- discard_transaction(&mut engine);- engine.match_element_for_cascade(nodes[1]).unwrap();- publish_current_cascade_as_computed(&mut engine, nodes[1]);-- remove_feature(&mut engine, nodes[1], LocalFeatureKey::Class(first_class));- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(second_class));- let mut planned = Vec::new();- assert!(engine.take_style_transaction(nodes[0], |_, _, reactions| {- planned.extend(reactions.iter().map(|reaction| reaction.style_node));- }));-- assert_eq!(planned, vec![nodes[1].raw()]);-}--/// A styled root, and arriving under it a parent with 38 children: the parent is the last node,-/// allocated after its children so that preorder and node identity disagree.-fn root_with_arriving_parent_of_children() -> (StyleEngine, [u32; 40]) {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 40];- engine.allocate_style_nodes(&mut raw);- let node = |index: usize| StyleNodeID::from_raw(raw[index]).unwrap();- engine.record_tree_delta(node(0), None, Some(relations(None, None, None)));- set_atom_feature(&mut engine, node(0), LocalFeatureKey::TagName, StyleAtomID(100));- discard_transaction(&mut engine);- engine.match_element_for_cascade(node(0)).unwrap();- publish_current_cascade_as_computed(&mut engine, node(0));-- engine.record_tree_delta(node(39), None, Some(relations(Some(raw[0]), None, None)));- set_atom_feature(&mut engine, node(39), LocalFeatureKey::TagName, StyleAtomID(100));- for index in 1..39 {- let previous = (index > 1).then_some(raw[index - 1]);- engine.record_tree_delta(node(index), None, Some(relations(Some(raw[39]), previous, None)));- set_atom_feature(&mut engine, node(index), LocalFeatureKey::TagName, StyleAtomID(100));- }- (engine, raw)-}--#[test]-fn published_ancestor_checks_follow_preorder_instead_of_node_identity() {- let (mut engine, raw) = root_with_arriving_parent_of_children();- let mut waves = Vec::new();- assert!(take_every_wave(- &mut engine,- StyleNodeID::from_raw(raw[0]).unwrap(),- |_, _, reactions| {- waves.push(reactions.iter().map(|reaction| reaction.style_node).collect::<Vec<_>>());- }- ));- // The pass stops before the first child, which reads the parent only the host settles; the- // next wave drives every child over the installed parent.- assert_eq!(waves, vec![vec![raw[39]], raw[1..39].to_vec()]);-}--#[test]-fn an_input_submitted_between_waves_gives_the_pass_up() {- let (mut engine, raw) = root_with_arriving_parent_of_children();- let root = StyleNodeID::from_raw(raw[0]).unwrap();- let mut first_wave = Vec::new();- engine.take_style_transaction(root, |_, _, reactions| {- first_wave.extend(reactions.iter().map(|reaction| reaction.style_node));- });- assert_eq!(first_wave, vec![raw[39]]);-- // Installing the parent rewrote a declaration of a child the pass has not reached, which the- // host submits before it takes the next wave.- engine.record_input(- InputKey::ElementDeclaration(- StyleNodeID::from_raw(raw[1]).unwrap(),- ElementDeclarationKind::InlineStyle,- ),- InputValue::ElementDeclaration(None),- InputValue::ElementDeclaration(Some(DeclarationBlockID(1))),- );- let mut recomputed = Vec::new();- take_every_wave(&mut engine, root, |_, _, reactions| {- recomputed.extend(- reactions- .iter()- .filter(|reaction| reaction.reaction & transaction::STYLE_REACTION_RECOMPUTE_STYLE != 0)- .map(|reaction| reaction.style_node),- );- });- // The children are owed to the transaction that takes the declaration, not settled over the- // declarations the pass was planned from.- recomputed.sort_unstable();- let mut children = raw[1..39].to_vec();- children.sort_unstable();- assert_eq!(recomputed, children);-}--#[test]-fn a_pass_given_up_gives_back_what_moved_under_the_rows_it_did_not_reach() {- let (mut engine, raw) = root_with_arriving_parent_of_children();- let node = |index: usize| StyleNodeID::from_raw(raw[index]).unwrap();- // What the host recorded beside the style inputs it owes the parent and two of its children.- engine.record_container_query_input(node(39));- engine.record_container_query_input(node(1));- engine.retained.row_inputs_moved.note_parent_display_moved(node(2));- let mut first_wave = Vec::new();- engine.take_style_transaction(node(0), |_, _, reactions| {- first_wave.extend(reactions.iter().map(|reaction| reaction.style_node));- });- assert_eq!(first_wave, vec![raw[39]]);-- engine.discard_style_transaction_outputs();- // The next transaction drives the children over their moved containers and parent display, as- // this one would have, and in full: what else moved under them only this one saw. The parent's- // row was given to the host, with what moved under it.- let owed = &engine.retained.row_inputs_moved;- assert!(owed.containers_moved(node(1)));- assert!(owed.parent_display_moved(node(2)));- assert!(!owed.containers_moved(node(39)));- assert!((1..39).all(|index| owed.given_up(node(index))));- assert!(!owed.given_up(node(39)));-}--#[test]-fn a_changed_cascade_survives_an_earlier_exact_cascade_stop() {- let (mut engine, nodes) = linear_document();- let classes = [StyleAtomID(200), StyleAtomID(201), StyleAtomID(202)];- for (index, class) in classes.into_iter().enumerate() {- let rule = add_target_rule(&mut engine, StyleSheetObjectID(index as u32 + 1), class);- let value = SpecifiedValueID(if index == 2 { 102 } else { 101 });- engine.set_rule_declared_properties_with_values(rule, &[(1, false, value)]);- }- for &node in &nodes[1..3] {- add_feature(&mut engine, node, LocalFeatureKey::Class(classes[0]));- }- discard_transaction(&mut engine);- for &node in &nodes[1..3] {- engine.match_element_for_cascade(node).unwrap();- publish_current_cascade_as_computed(&mut engine, node);- }- for index in 1..3 {- remove_feature(&mut engine, nodes[index], LocalFeatureKey::Class(classes[0]));- add_feature(&mut engine, nodes[index], LocalFeatureKey::Class(classes[index]));- }- let stops_before = engine.counters().get(Counter::PublishedExactCascadeStops);- let mut published = Vec::new();- assert!(engine.take_style_transaction(nodes[0], |_, _, reactions| {- published.extend(reactions.iter().map(|reaction| reaction.style_node));- }));- assert_eq!(published, [nodes[2].raw()]);- assert_eq!(- engine.counters().get(Counter::PublishedExactCascadeStops),- stops_before + 1- );-}--#[test]-fn program_and_local_routes_merge_retained_answer_attribution() {- let (mut engine, nodes) = linear_document();- let departing_class = StyleAtomID(200);- let arriving_class = StyleAtomID(201);- let departing_rule = add_target_rule(&mut engine, StyleSheetObjectID(1), departing_class);- engine.set_rule_declared_properties(departing_rule, &[(1, false)]);- for class in [departing_class, arriving_class] {- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- let old_answer = engine.match_element_for_cascade(nodes[1]).unwrap();- assert_eq!(old_answer.len(), 1);- assert_eq!(old_answer[0].rule, departing_rule);- publish_current_cascade_as_computed(&mut engine, nodes[1]);-- remove_feature(&mut engine, nodes[1], LocalFeatureKey::Class(departing_class));-- let program = engine.programs.add(test_class_selector_program(- ".arriving",- &[("arriving", arriving_class)],- None,- ));- let sheet = engine.program.rule_sheet(departing_rule);- let arriving_rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(arriving_rule, program);- let mut version = engine.program.rule_version(arriving_rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(2));- engine.replace_rule_version(arriving_rule, version);- engine.set_rule_declared_properties(arriving_rule, &[(2, false)]);-- let mut planned = Vec::new();- assert!(engine.take_style_transaction(nodes[0], |_, _, reactions| {- planned.extend(reactions.iter().map(|reaction| reaction.style_node));- }));-- assert_eq!(planned, vec![nodes[1].raw()]);- let retained = match engine.retained_match_answer(nodes[1]) {- Lookup::Known(answer) => answer,- Lookup::KnownAbsent | Lookup::Missing(_) => panic!("expected a retained answer"),- };- assert_eq!(retained.len(), 1);- assert_eq!(retained[0].rule, arriving_rule);-}--#[test]-fn an_exact_unchanged_custom_state_cascade_stops_before_style_recomputation() {- let (mut engine, nodes) = linear_document();- let state = StyleAtomID(200);- let first_rule = add_custom_state_rule(&mut engine, StyleSheetObjectID(1), state, false);- let second_rule = add_custom_state_rule(&mut engine, StyleSheetObjectID(2), state, true);- let value = SpecifiedValueID(101);- engine.set_rule_declared_properties_with_values(first_rule, &[(1, false, value)]);- engine.set_rule_declared_properties_with_values(second_rule, &[(1, false, value)]);- discard_transaction(&mut engine);- engine.retained.facts.set_custom_states(nodes[1], &[]);- engine.retained.facts.apply_staged();-- let old_answer = engine.match_element_for_cascade(nodes[1]).unwrap();- assert_eq!(old_answer.len(), 1);- assert_eq!(old_answer[0].rule, first_rule);- publish_current_cascade_as_computed(&mut engine, nodes[1]);-- engine.set_element_custom_states(nodes[1], &[state]);- let stops_before = engine.counters().get(Counter::PublishedExactCascadeStops);- let mut planned = Vec::new();- assert!(engine.take_style_transaction(nodes[0], |_, _, reactions| {- planned.extend(reactions.iter().map(|reaction| reaction.style_node));- }));-- assert!(planned.is_empty());- assert_eq!(- engine.counters().get(Counter::PublishedExactCascadeStops),- stops_before + 1- );- let current = engine.match_element_for_cascade(nodes[1]).unwrap();- assert_eq!(current.len(), 1);- assert_eq!(current[0].rule, second_rule);-}--#[test]-fn retained_answer_patching_evaluates_narrow_affected_rules_directly() {- let (mut engine, nodes) = linear_document();- let matching_class = StyleAtomID(200);- let unrelated_class = StyleAtomID(201);- let matching_rule = add_target_rule(&mut engine, StyleSheetObjectID(1), matching_class);- let unrelated_rule = add_target_rule(&mut engine, StyleSheetObjectID(2), unrelated_class);- engine.set_rule_declared_properties(matching_rule, &[(1, false)]);- engine.set_rule_declared_properties(unrelated_rule, &[(2, false)]);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(matching_class));- discard_transaction(&mut engine);-- let exact_answer = engine.match_element(nodes[1]).unwrap();- let compact_answer = engine.matches_for_cascade(exact_answer.clone(), false, None);- engine.remember_retained_match_answer(nodes[1], &exact_answer);- engine.remember_cascade_input(nodes[1], &compact_answer);- let matching_program = engine- .retained- .program- .rule_version(matching_rule)- .selector_program- .unwrap();- let unrelated_program = engine- .retained- .program- .rule_version(unrelated_rule)- .selector_program- .unwrap();- let mut patch = engine.prepare_retained_answer_patch(RetainedAnswerPatchSelection {- affected: vec![- RetainedAnswerPatchSelectionRule {- rule: matching_rule,- program: matching_program,- evaluate: true,- },- RetainedAnswerPatchSelectionRule {- rule: unrelated_rule,- program: unrelated_program,- evaluate: true,- },- ],- always_emit: false,- orders_shifted: false,- requires_full_match: false,- ..Default::default()- });- let feature_tests_before = engine.counters().get(Counter::LocalFeatureTests);-- assert_eq!(- engine- .patch_retained_match_answer(nodes[1], &mut patch, SelectorTruthPatch::Full)- .map(|outcome| outcome.emit),- Some(false)- );- // The narrow repair path filters out the unrelated rule before selector evaluation without- // paying the fixed cost to gather and filter the node's subject dispatch buckets.- assert_eq!(- engine.counters().get(Counter::LocalFeatureTests),- feature_tests_before + 1- );-}--#[test]-fn retained_answer_patching_applies_complete_signed_deltas_without_matching() {- let (mut engine, nodes) = linear_document();- let target = StyleAtomID(200);- let rule = add_target_rule(&mut engine, StyleSheetObjectID(1), target);- engine.set_rule_declared_properties(rule, &[(1, false)]);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- let exact_answer = engine.match_element(nodes[1]).unwrap();- let compact_answer = engine.matches_for_cascade(exact_answer.clone(), false, Some(nodes[1]));- engine.remember_retained_match_answer(nodes[1], &exact_answer);- engine.remember_cascade_input(nodes[1], &compact_answer);- remove_feature(&mut engine, nodes[1], LocalFeatureKey::Class(target));- let program = engine.program.rule_version(rule).selector_program.unwrap();- // Match-input preparation follows fact commit, as it does in a style transaction.- engine.retained.facts.apply_staged();- let mut patch = engine.prepare_retained_answer_patch(RetainedAnswerPatchSelection {- affected: vec![RetainedAnswerPatchSelectionRule {- rule,- program,- evaluate: true,- }],- always_emit: false,- orders_shifted: false,- requires_full_match: false,- ..Default::default()- });- let feature_tests_before = engine.counters().get(Counter::LocalFeatureTests);-- let outcome = engine- .patch_retained_match_answer(- nodes[1],- &mut patch,- SelectorTruthPatch::Direct(&[SelectorTruthDelta {- node: nodes[1],- rule,- entry: engine.programs.entry_id(program, 0),- change: SetChange::Removed,- selector_truth_changed: true,- }]),- )- .unwrap();- assert!(outcome.emit);- assert!(outcome.incremental_cascade_answer.is_some());- assert_eq!(engine.counters().get(Counter::LocalFeatureTests), feature_tests_before);- assert_eq!(engine.counters().get(Counter::RetainedMatchAnswerDeltaPatches), 1);- assert_eq!(engine.counters().get(Counter::RetainedMatchAnswerDeltaEntries), 1);- assert!(matches!(engine.retained_match_answer(nodes[1]), Lookup::Known(answer) if answer.is_empty()));-- assert!(engine.apply_cascade_winner_match_deltas(- nodes[1],- &exact_answer,- &[SelectorTruthDelta {- node: nodes[1],- rule,- entry: engine.programs.entry_id(program, 0),- change: SetChange::Added,- selector_truth_changed: true,- }],- &mut Vec::new(),- ));- assert!(matches!(- engine- .winner_groups- .winner(WinnerGroupKey::current(nodes[1], engine.program.version()), 1),- Lookup::Known(winner) if winner.source == WinnerSource::Rule(rule)- ));-}--#[test]-fn incremental_winner_repair_ignores_shorthand_declarations() {- let (mut engine, nodes) = linear_document();- let base = add_target_rule(&mut engine, StyleSheetObjectID(1), StyleAtomID(200));- let shorthand = add_target_rule(&mut engine, StyleSheetObjectID(2), StyleAtomID(201));- let shorthand_property = crate::css::property_metadata::LAST_LONGHAND_PROPERTY_ID + 1;- engine.set_rule_declared_properties_with_values(base, &[(1, false, SpecifiedValueID(101))]);- engine.set_rule_declared_properties_with_values(shorthand, &[(shorthand_property, false, SpecifiedValueID(201))]);- commit_test_setup(&mut engine);- let base_match = concrete_rule_match(&engine, nodes[0], base, 0, None);- let shorthand_match = concrete_rule_match(&engine, nodes[0], shorthand, 1, None);- engine.matches_for_cascade(vec![base_match], false, Some(nodes[0]));- let key = WinnerGroupKey::current(nodes[0], engine.program.version());- let added = SelectorTruthDelta {- node: nodes[0],- rule: shorthand,- entry: engine.programs.entry_id(shorthand_match.program, shorthand_match.entry),- change: SetChange::Added,- selector_truth_changed: true,- };-- assert!(engine.apply_cascade_winner_match_deltas(- nodes[0],- &[base_match, shorthand_match],- &[added],- &mut Vec::new()- ));- assert!(matches!(- engine.winner_groups.winner(key, shorthand_property),- Lookup::KnownAbsent- ));-}--#[test]-fn prefix_match_deltas_only_publish_deciding_rules() {- let (mut engine, nodes) = linear_document();- let target = StyleAtomID(200);- let rule = add_target_rule(&mut engine, StyleSheetObjectID(1), target);- discard_transaction(&mut engine);- let sheet = engine.program.rule_sheet(rule);- let selector = engine.program.rule_version(rule).selector_program.unwrap();- let entry = engine.programs.entry_id(selector, 0);- let (_, dispatch) = engine.prepare_scope_program(TreeScopeID::DOCUMENT);- assert!(dispatch.prefixes().contains_entry(entry));-- // Activation changes preserve selector topology. An exact prefix answer can still name- // the selector while its declarations are excluded from the cascade.- for (rule_conditions, sheet_conditions, sheet_enabled) in [- (false, true, true),- (true, false, true),- (true, true, false),- (true, true, true),- ] {- engine.program.set_rule_conditions_hold(rule, rule_conditions);- engine.program.set_sheet_conditions_hold(sheet, sheet_conditions);- engine.program.set_sheet_enabled(sheet, sheet_enabled);- for (old, new) in [(&[][..], &[entry][..]), (&[entry][..], &[][..])] {- let mut changes = SelectorTruthChanges::default();- record_match_set_difference(&mut changes, true, nodes[1], old, new, &dispatch, &engine.program);- let deltas = changes.deltas.as_slice();- if rule_conditions && sheet_conditions && sheet_enabled {- assert_eq!(deltas.len(), 1);- assert_eq!(deltas[0].rule, rule);- assert_eq!(deltas[0].entry, entry);- assert_eq!(- deltas[0].change,- if old.is_empty() {- SetChange::Added- } else {- SetChange::Removed- }- );- } else {- assert!(deltas.is_empty());- }- }- }-}--#[test]-fn recycled_selector_entries_keep_delta_answers_canonical() {- let (mut engine, nodes) = linear_document();- let discarded = engine.programs.add(test_class_selector_program(- ".discarded-a, .discarded-b",- &[("discarded-a", StyleAtomID(300)), ("discarded-b", StyleAtomID(301))],- None,- ));- assert_eq!(engine.programs.get(discarded).entries().len(), 2);- engine.programs.sweep_unreferenced(&[false]);-- let first = StyleAtomID(200);- let second = StyleAtomID(201);- let (rule, program) = add_selector_list_rule(&mut engine, first, second);- engine.set_rule_declared_properties(rule, &[(1, false)]);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(first));- discard_transaction(&mut engine);-- let retained = engine.match_element(nodes[1]).unwrap();- let compact = engine.matches_for_cascade(retained.clone(), false, Some(nodes[1]));- engine.remember_retained_match_answer(nodes[1], &retained);- engine.remember_cascade_input(nodes[1], &compact);- let old_identity = match engine.retained_match_answers.lookup(nodes[1]) {- Lookup::Known(identity) => *identity,- _ => panic!("initial answer must be retained"),- };- let old_cascade_input = match engine.retained_match_answers.cascade_input_lookup(nodes[1]) {- Lookup::Known(identity) => *identity,- _ => panic!("initial cascade input must be retained"),- };- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(second));- engine.retained.facts.apply_staged();-- let mut patch = engine.prepare_retained_answer_patch(RetainedAnswerPatchSelection {- affected: vec![RetainedAnswerPatchSelectionRule {- rule,- program,- evaluate: true,- }],- requires_full_match: true,- ..Default::default()- });- engine- .apply_retained_match_answer_deltas(- nodes[1],- &mut patch,- old_identity,- old_cascade_input,- &[SelectorTruthDelta {- node: nodes[1],- rule,- entry: engine.programs.entry_id(program, 1),- change: SetChange::Added,- selector_truth_changed: true,- }],- )- .unwrap();- let patched_identity = match engine.retained_match_answers.lookup(nodes[1]) {- Lookup::Known(identity) => *identity,- _ => panic!("patched answer must be retained"),- };- let patched = match engine.retained_match_answer(nodes[1]) {- Lookup::Known(answer) => answer,- _ => panic!("patched answer payload must be retained"),- }- .to_vec();- assert!(patched.is_sorted());-- let mut cold = patched;- cold.sort_unstable();- let cold_identity = engine- .retained- .match_answers- .intern_prepared(cold, &engine.retained.programs);- assert_eq!(patched_identity, cold_identity);-}--#[test]-fn retained_answer_patching_matches_only_unresolved_rules_after_signed_deltas() {- let (mut engine, nodes) = linear_document();- let delta_target = StyleAtomID(200);- let second_delta_target = StyleAtomID(201);- let refresh_target = StyleAtomID(202);- let mut add_rule = |target, sheet_object| {- let program = engine- .programs- .add(test_selector_program(".target:nth-child(2n+1)", &[("target", target)]));- let sheet = engine.add_sheet(sheet_object, CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);- (rule, program)- };- let (delta_rule, delta_program) = add_rule(delta_target, StyleSheetObjectID(1));- let (second_delta_rule, second_delta_program) = add_rule(second_delta_target, StyleSheetObjectID(2));- let (refresh_rule, refresh_program) = add_rule(refresh_target, StyleSheetObjectID(3));- engine.set_rule_declared_properties(delta_rule, &[(1, false)]);- engine.set_rule_declared_properties(second_delta_rule, &[(2, false)]);- engine.set_rule_declared_properties(refresh_rule, &[(3, false)]);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(refresh_target));- discard_transaction(&mut engine);-- let exact_answer = engine.match_element(nodes[1]).unwrap();- let compact_answer = engine.matches_for_cascade(exact_answer.clone(), false, None);- engine.remember_retained_match_answer(nodes[1], &exact_answer);- engine.remember_cascade_input(nodes[1], &compact_answer);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(delta_target));- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(second_delta_target));- engine.retained.facts.apply_staged();- let mut patch = engine.prepare_retained_answer_patch(RetainedAnswerPatchSelection {- affected: vec![- RetainedAnswerPatchSelectionRule {- rule: delta_rule,- program: delta_program,- evaluate: true,- },- RetainedAnswerPatchSelectionRule {- rule: second_delta_rule,- program: second_delta_program,- evaluate: true,- },- RetainedAnswerPatchSelectionRule {- rule: refresh_rule,- program: refresh_program,- evaluate: true,- },- ],- always_emit: false,- orders_shifted: false,- requires_full_match: false,- ..Default::default()- });- let candidate_checks_before = engine.counters().get(Counter::CandidateChecks);-- assert_eq!(- engine- .patch_retained_match_answer(- nodes[1],- &mut patch,- SelectorTruthPatch::Refresh {- deltas: &[- SelectorTruthDelta {- node: nodes[1],- rule: delta_rule,- entry: engine.programs.entry_id(delta_program, 0),- change: SetChange::Added,- selector_truth_changed: true,- },- SelectorTruthDelta {- node: nodes[1],- rule: second_delta_rule,- entry: engine.programs.entry_id(second_delta_program, 0),- change: SetChange::Added,- selector_truth_changed: true,- },- ],- refreshes: &[SelectorTruthRefresh {- node: nodes[1],- rule: Some((refresh_rule, engine.programs.entry_id(refresh_program, 0))),- }],- },- )- .map(|outcome| outcome.emit),- Some(true)- );- assert_eq!(- engine.counters().get(Counter::CandidateChecks),- candidate_checks_before + 1- );- assert!(matches!(- engine.retained_match_answer(nodes[1]),- Lookup::Known(answer) if answer.len() == 3- ));-}--#[test]-fn retained_answer_patching_preserves_held_container_cascade_winners() {- let (mut engine, nodes) = linear_document();- let target = StyleAtomID(200);- let winning_target = StyleAtomID(201);- let pseudo = PseudoElementTarget::new(PseudoElementKind(0));- let gated_rule = add_pseudo_target_rule(&mut engine, StyleSheetObjectID(1), target, pseudo);- let winning_rule = add_target_rule(&mut engine, StyleSheetObjectID(2), winning_target);- engine.set_rule_declared_properties(gated_rule, &[(1, false)]);- engine.set_rule_declared_properties(winning_rule, &[(2, false)]);- engine.set_rule_gated_by_container_query(gated_rule);- for class in [target, winning_target] {- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- let exact_answer = engine.match_element(nodes[1]).unwrap();- assert_eq!(exact_answer.len(), 2);- let compact_answer = engine.matches_for_cascade(exact_answer.clone(), false, Some(nodes[1]));- engine.remember_retained_match_answer(nodes[1], &exact_answer);- engine.remember_cascade_input(nodes[1], &compact_answer);- let winning_program = engine.program.rule_version(winning_rule).selector_program.unwrap();- let mut patch = engine.prepare_retained_answer_patch(RetainedAnswerPatchSelection {- affected: vec![RetainedAnswerPatchSelectionRule {- rule: winning_rule,- program: winning_program,- evaluate: true,- }],- always_emit: false,- orders_shifted: false,- requires_full_match: false,- ..Default::default()- });-- let outcome = engine- .patch_retained_match_answer(- nodes[1],- &mut patch,- SelectorTruthPatch::Direct(&[SelectorTruthDelta {- node: nodes[1],- rule: winning_rule,- entry: engine.programs.entry_id(winning_program, 0),- change: SetChange::Removed,- selector_truth_changed: true,- }]),- )- .unwrap();- let incremental = outcome.incremental_cascade_answer.unwrap();- // A pseudo-element's gated rule is held like the element's: the winners decide it.- assert!(incremental.cascade_winners_are_complete);-}--#[test]-fn selector_list_entry_deltas_fall_back_when_the_compact_winner_is_insufficient() {- let (mut engine, nodes) = linear_document();- let (rule, program) = add_selector_list_rule(&mut engine, StyleAtomID(200), StyleAtomID(201));- let mut patch = engine.prepare_retained_answer_patch(RetainedAnswerPatchSelection {- affected: vec![RetainedAnswerPatchSelectionRule {- rule,- program,- evaluate: true,- }],- always_emit: false,- orders_shifted: false,- requires_full_match: false,- ..Default::default()- });- let retained = [RetainedRuleMatch {- rule,- program,- entry: 1,- tree_scope: TreeScopeID::DOCUMENT,- scope_proximity: u32::MAX,- }];- engine.remember_prepared_retained_match_answer_with_truth(nodes[1], retained.to_vec(), None);- let old_identity = *engine.retained_match_answers.lookup(nodes[1]).sparse().unwrap();- let entries = [- engine.programs.entry_id(program, 0),- engine.programs.entry_id(program, 1),- ];- let delta = |entry: usize, change| SelectorTruthDelta {- node: nodes[1],- rule,- entry: entries[entry],- change,- selector_truth_changed: true,- };-- assert!(- engine- .apply_retained_match_answer_deltas(- nodes[1],- &mut patch,- old_identity,- MatchAnswerID::default(),- &[delta(0, SetChange::Added)],- )- .is_none(),- "a newly matching hidden loser needs rule-scoped repair"- );- assert!(- engine- .apply_retained_match_answer_deltas(- nodes[1],- &mut patch,- old_identity,- MatchAnswerID::default(),- &[delta(1, SetChange::Removed)],- )- .is_none(),- "removing a winner must recover any hidden matching loser"- );- engine.prefix_caches.borrow_mut().states.release();-}--#[test]-fn retained_answer_repair_returns_signed_selector_truth() {- let (mut engine, nodes) = linear_document();- let target = StyleAtomID(200);- let rule = add_target_rule(&mut engine, StyleSheetObjectID(1), target);- engine.set_rule_declared_properties(rule, &[(1, false)]);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- let exact_answer = engine.match_element(nodes[1]).unwrap();- let compact_answer = engine.matches_for_cascade(exact_answer.clone(), false, None);- engine.remember_retained_match_answer(nodes[1], &exact_answer);- engine.remember_cascade_input(nodes[1], &compact_answer);- remove_feature(&mut engine, nodes[1], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);- let program = engine.program.rule_version(rule).selector_program.unwrap();- let mut patch = engine.prepare_retained_answer_patch(RetainedAnswerPatchSelection {- affected: vec![RetainedAnswerPatchSelectionRule {- rule,- program,- evaluate: true,- }],- always_emit: false,- orders_shifted: false,- requires_full_match: false,- ..Default::default()- });- let repair_upqueries_before = engine.counters().get(Counter::SelectorTruthRepairUpqueries);- let repair_removals_before = engine.counters().get(Counter::SelectorTruthRepairRemovals);- let delta_patches_before = engine.counters().get(Counter::RetainedMatchAnswerDeltaPatches);-- assert_eq!(- engine- .patch_retained_match_answer(- nodes[1],- &mut patch,- SelectorTruthPatch::Refresh {- deltas: &[],- refreshes: &[SelectorTruthRefresh {- node: nodes[1],- rule: Some((rule, engine.programs.entry_id(program, 0))),- }],- },- )- .map(|outcome| outcome.emit),- Some(true)- );- assert_eq!(- engine.counters().get(Counter::SelectorTruthRepairUpqueries),- repair_upqueries_before + 1- );- assert_eq!(- engine.counters().get(Counter::SelectorTruthRepairRemovals),- repair_removals_before + 1- );- assert_eq!(- engine.counters().get(Counter::RetainedMatchAnswerDeltaPatches),- delta_patches_before + 1- );- assert!(matches!(engine.retained_match_answer(nodes[1]), Lookup::Known(answer) if answer.is_empty()));-}--#[test]-fn patch_attributions_preserve_the_same_coverage_without_preorder_coordinates() {- let (mut engine, nodes) = nested_document();- discard_transaction(&mut engine);- let first = (RuleID(1), EntryID(1));- let second = (RuleID(2), EntryID(2));- for indexed in [false, true] {- let mut regions = if indexed {- ImpactRegions::with_topology(&engine.tree, nodes[0])- } else {- ImpactRegions::new()- };- regions.add_attributed(ImpactRegion::Subtree(nodes[1]), first);- regions.add_attributed(ImpactRegion::Children(nodes[1]), second);- regions.add_attributed(ImpactRegion::Node(nodes[3]), second);- regions.attribute_extent(ImpactRegion::Node(nodes[3]), first);- let cover = regions.compile_patch_cover(&engine.tree, Some(nodes[0]));- let mut sweep = AttributionSweep::default();- let mut covering = Vec::new();- // Visit out of order and overlap extents, exercising both the indexed stab and the- // direct relation walk. Precise attribution never becomes a full refresh request.- for (index, expected) in [- (3, vec![first, second]),- (0, vec![]),- (2, vec![first, second]),- (1, vec![first]),- ] {- let node = nodes[index];- assert!(!regions.batch_contains_node(&cover.full, node));- assert!(regions.covering_attributions(&cover, &engine.tree, &mut sweep, node, &mut covering));- assert_eq!(covering, expected);- }- }-}--#[test]-fn already_planned_routes_attribute_their_extent() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- let rule = add_guard_target_rule(&mut engine, guard, target);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- add_feature(&mut engine, nodes[3], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- let exact_answer = engine.match_element(nodes[3]).unwrap();- engine.remember_retained_match_answer(nodes[3], &exact_answer);- engine.remember_cascade_input(nodes[3], &exact_answer);-- remove_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- let mut transaction = engine.take_transaction();- let mut regions = ImpactRegions::with_topology(&engine.tree, nodes[0]);- regions.add(ImpactRegion::Node(nodes[3]));- engine.transaction_fact_view = Some(engine.transaction_fact_view_for(&mut transaction, nodes[0], ®ions));- engine.selector_truth_changes_active = true;- let program = engine.program.rule_version(rule).selector_program.unwrap();- let site = RoutingSite {- subject: &[DispatchKey::Class(target)],- subject_required: &[],- position: SubjectPosition::UNBOUNDED,- path: &[],- waypoints: &[],- in_flux: None,- exact_entry: Some((rule, engine.programs.entry_id(program, 0))),- exact_tree_evaluation: None,- refresh_rule: None,- };- engine.add_narrowed_region(ImpactRegion::Node(nodes[3]), &site, &mut regions);-- // The route leaves no per-node row behind: its extent attribution alone must carry the- // rule into the node's patch union.- assert!(engine.already_planned_selector_truth.as_slice().is_empty());- engine.resolve_already_planned_selector_truth(®ions, None);- engine- .retained- .selector_truth_changes- .consolidate(&engine.retained.counters);- assert!(engine.selector_truth_changes.deltas.as_slice().is_empty());- assert!(engine.selector_truth_changes.refreshes.as_slice().is_empty());-- let cover = regions.compile_patch_cover(&engine.tree, Some(nodes[0]));- let mut sweep = AttributionSweep::default();- let mut covering = Vec::new();- assert!(regions.covering_attributions(&cover, &engine.tree, &mut sweep, nodes[3], &mut covering));- assert_eq!(covering, vec![(rule, engine.programs.entry_id(program, 0))]);-- engine.selector_truth_changes = SelectorTruthChanges::default();- engine.record_already_planned_selector_truth(nodes[3], &site);- let mut coarse_regions = ImpactRegions::new();- coarse_regions.add(ImpactRegion::Subtree(nodes[0]));- let coarse_cover = coarse_regions.compile_union(coarse_regions.regions(), &engine.tree, Some(nodes[0]));- engine.resolve_already_planned_selector_truth(&coarse_regions, Some(&coarse_cover));- assert!(engine.selector_truth_changes.deltas.as_slice().is_empty());- assert!(engine.selector_truth_changes.refreshes.as_slice().is_empty());- engine.transaction_fact_view = None;- engine.release_transaction(transaction);-}--#[test]-fn routes_covered_by_an_attributed_subtree_still_attribute_their_extent() {- let (mut engine, nodes) = nested_document();- let rule_a = add_guard_target_rule(&mut engine, StyleAtomID(200), StyleAtomID(201));- let rule_b = add_guard_target_rule(&mut engine, StyleAtomID(202), StyleAtomID(203));- let program_a = engine.current_rule_version(rule_a).selector_program.unwrap();- let program_b = engine.current_rule_version(rule_b).selector_program.unwrap();- discard_transaction(&mut engine);- let mut regions = ImpactRegions::with_topology(&engine.tree, nodes[0]);- regions.add_attributed(- ImpactRegion::Subtree(nodes[0]),- (rule_a, engine.programs.entry_id(program_a, 0)),- );- engine.selector_truth_changes_active = true;-- // A covering subtree attributed to one rule narrows the patches of every node under it,- // so a second route dropped for that coverage must still enter the attribution union.- let site = RoutingSite {- subject: &[DispatchKey::Class(StyleAtomID(203))],- subject_required: &[],- position: SubjectPosition::UNBOUNDED,- path: &[],- waypoints: &[],- in_flux: None,- exact_entry: Some((rule_b, engine.programs.entry_id(program_b, 0))),- exact_tree_evaluation: None,- refresh_rule: None,- };- let mut routed_regions = vec![ImpactRegion::Node(nodes[3])];- engine.discard_regions_covered_by_subtree(&mut routed_regions, &site, &mut regions);- assert!(routed_regions.is_empty());-- let cover = regions.compile_patch_cover(&engine.tree, Some(nodes[0]));- assert!(!regions.batch_contains_node(&cover.full, nodes[3]));- let mut sweep = AttributionSweep::default();- let mut covering = Vec::new();- assert!(regions.covering_attributions(&cover, &engine.tree, &mut sweep, nodes[3], &mut covering));- assert_eq!(- covering,- vec![- (rule_a, engine.programs.entry_id(program_a, 0)),- (rule_b, engine.programs.entry_id(program_b, 0)),- ]- );-- // A dropped route that names no rule must poison instead: a node region by refresh, a- // wider region by joining the full re-derivation cover.- let unnamed = RoutingSite {- exact_entry: None,- ..site- };- let mut node_region = vec![ImpactRegion::Node(nodes[3])];- engine.discard_regions_covered_by_subtree(&mut node_region, &unnamed, &mut regions);- assert!(node_region.is_empty());- assert!(- engine- .selector_truth_changes- .refreshes- .as_slice()- .iter()- .any(|refresh| refresh.node == nodes[3] && refresh.rule.is_none())- );- let mut wide_region = vec![ImpactRegion::Children(nodes[1])];- engine.discard_regions_covered_by_subtree(&mut wide_region, &unnamed, &mut regions);- assert!(wide_region.is_empty());- let poisoned_cover = regions.compile_patch_cover(&engine.tree, Some(nodes[0]));- assert!(regions.batch_contains_node(&poisoned_cover.full, nodes[2]));-- // Coverage by an unattributed subtree already forces full re-derivation, so a route- // dropped for that coverage stays silent: no attribution and no poison.- let mut full_regions = ImpactRegions::with_topology(&engine.tree, nodes[0]);- full_regions.add(ImpactRegion::Subtree(nodes[0]));- let refreshes_before = engine.selector_truth_changes.refreshes.as_slice().len();- let mut silent_region = vec![ImpactRegion::Node(nodes[3])];- engine.discard_regions_covered_by_subtree(&mut silent_region, &unnamed, &mut full_regions);- assert!(silent_region.is_empty());- assert_eq!(- engine.selector_truth_changes.refreshes.as_slice().len(),- refreshes_before- );-}--#[test]-fn already_planned_routes_skip_truth_without_a_retained_answer() {- let (mut engine, nodes) = nested_document();- let rule = add_guard_target_rule(&mut engine, StyleAtomID(200), StyleAtomID(201));- let program = engine.current_rule_version(rule).selector_program.unwrap();- let site = RoutingSite {- subject: &[],- subject_required: &[],- position: SubjectPosition::UNBOUNDED,- path: &[],- waypoints: &[],- in_flux: None,- exact_entry: Some((rule, engine.programs.entry_id(program, 0))),- exact_tree_evaluation: None,- refresh_rule: None,- };- engine.selector_truth_changes_active = true;-- engine.record_already_planned_selector_truth(nodes[3], &site);-- assert!(engine.already_planned_selector_truth.as_slice().is_empty());-}--#[test]-fn cascade_matching_refuses_incomplete_declaration_inventories() {- let (mut engine, nodes) = linear_document();- let incomplete = add_target_rule(&mut engine, StyleSheetObjectID(1), StyleAtomID(200));- let winner = add_target_rule(&mut engine, StyleSheetObjectID(2), StyleAtomID(201));- set_rule_declared_properties_beside_a_custom_property(&mut engine, incomplete, &[(1, false)]);- engine.set_rule_declared_properties(winner, &[(1, false)]);- commit_test_setup(&mut engine);- let matches = vec![- concrete_rule_match(&engine, nodes[0], incomplete, 0, None),- concrete_rule_match(&engine, nodes[0], winner, 1, None),- ];-- let compacted = engine.matches_for_cascade(matches, false, None);-- assert_eq!(compacted.len(), 2);-}--#[test]-fn cascade_matching_preserves_non_author_rules() {- let (mut engine, nodes) = linear_document();- let user_agent = add_target_rule_with_origin(- &mut engine,- StyleSheetObjectID(1),- StyleAtomID(200),- CascadeOrigin::UserAgent,- );- let author = add_target_rule(&mut engine, StyleSheetObjectID(2), StyleAtomID(201));- engine.set_rule_declared_properties(user_agent, &[(1, false)]);- engine.set_rule_declared_properties(author, &[(1, false)]);- commit_test_setup(&mut engine);- let matches = vec![- concrete_rule_match(&engine, nodes[0], user_agent, 0, None),- concrete_rule_match(&engine, nodes[0], author, 1, None),- ];-- let compacted = engine.matches_for_cascade(matches, false, None);-- assert_eq!(compacted.len(), 2);-}--#[test]-fn cascade_state_includes_non_author_origins() {- let (mut engine, nodes) = linear_document();- let user_agent = add_target_rule_with_origin(- &mut engine,- StyleSheetObjectID(1),- StyleAtomID(200),- CascadeOrigin::UserAgent,- );- let author = add_target_rule(&mut engine, StyleSheetObjectID(2), StyleAtomID(201));- engine.set_rule_declared_properties(user_agent, &[(1, true)]);- engine.set_rule_declared_properties(author, &[(1, false)]);- commit_test_setup(&mut engine);- let matches = vec![- concrete_rule_match(&engine, nodes[0], user_agent, 0, None),- concrete_rule_match(&engine, nodes[0], author, 1, None),- ];-- let compacted = engine.matches_for_cascade(matches, false, Some(nodes[0]));-- assert_eq!(compacted.len(), 1);- assert_eq!(compacted[0].rule, user_agent);- let key = WinnerGroupKey::current(nodes[0], engine.program.version());- assert!(- matches!(engine.winner_groups.winner(key, 1), Lookup::Known(winner) if winner.source == WinnerSource::Rule(user_agent))- );-}--#[test]-fn author_revert_retains_and_repairs_its_user_agent_continuation() {- let (mut engine, nodes) = linear_document();- let user_agent = add_target_rule_with_origin(- &mut engine,- StyleSheetObjectID(1),- StyleAtomID(200),- CascadeOrigin::UserAgent,- );- let author_value = add_target_rule(&mut engine, StyleSheetObjectID(2), StyleAtomID(201));- let author_revert = add_target_rule(&mut engine, StyleSheetObjectID(3), StyleAtomID(202));- let declared = |value, operator| DeclaredProperty {- property: 1,- important: false,- operator,- value: SpecifiedValueID(value),- };- engine.set_rule_declared_properties_with_operators(user_agent, &[declared(101, CascadeOperator::Declared)]);- engine.set_rule_declared_properties_with_operators(author_value, &[declared(201, CascadeOperator::Declared)]);- engine.set_rule_declared_properties_with_operators(author_revert, &[declared(301, CascadeOperator::Revert)]);- commit_test_setup(&mut engine);- let user_agent_match = concrete_rule_match(&engine, nodes[0], user_agent, 0, None);- let author_value_match = concrete_rule_match(&engine, nodes[0], author_value, 1, None);- let author_revert_match = concrete_rule_match(&engine, nodes[0], author_revert, 2, None);- let matches = vec![user_agent_match, author_value_match, author_revert_match];-- let compacted = engine.matches_for_cascade(matches, false, Some(nodes[0]));-- assert_eq!(- compacted.iter().map(|matched| matched.rule).collect::<Vec<_>>(),- [user_agent, author_revert]- );- let key = WinnerGroupKey::current(nodes[0], engine.program.version());- let Lookup::Known(winner) = engine.winner_groups.winner(key, 1) else {- panic!("revert winner was not retained");- };- assert_eq!(winner.source, WinnerSource::Rule(author_revert));- assert_eq!(winner.key.operator, CascadeOperator::Revert);- assert_eq!(- engine.winner_groups.resolved_winner(winner).unwrap().source,- WinnerSource::Rule(user_agent)- );-- let removed = SelectorTruthDelta {- node: nodes[0],- rule: user_agent,- entry: engine- .programs- .entry_id(user_agent_match.program, user_agent_match.entry),- change: SetChange::Removed,- selector_truth_changed: true,- };- assert!(engine.apply_cascade_winner_match_deltas(- nodes[0],- &[author_value_match, author_revert_match],- &[removed],- &mut Vec::new()- ));- let Lookup::Known(repaired) = engine.winner_groups.winner(key, 1) else {- panic!("revert winner was not repaired");- };- assert_eq!(repaired.source, WinnerSource::Rule(author_revert));- assert!(engine.winner_groups.resolved_winner(repaired).is_none());-}--#[test]-fn exact_cascade_winner_repair_reduces_only_requested_properties() {- let (mut engine, nodes) = linear_document();- let lower = add_target_rule(&mut engine, StyleSheetObjectID(1), StyleAtomID(200));- let higher = add_target_rule(&mut engine, StyleSheetObjectID(2), StyleAtomID(201));- engine.set_rule_declared_properties_with_values(- lower,- &[(1, false, SpecifiedValueID(101)), (2, false, SpecifiedValueID(102))],- );- engine.set_rule_declared_properties_with_values(higher, &[(1, false, SpecifiedValueID(201))]);- commit_test_setup(&mut engine);- let lower_match = concrete_rule_match(&engine, nodes[0], lower, 0, None);- let higher_match = concrete_rule_match(&engine, nodes[0], higher, 1, None);-- let updates = engine- .exact_cascade_winner_updates_for_properties(nodes[0], &[lower_match, higher_match], None, &[1, 2, 3])- .unwrap();- assert_eq!(updates.len(), 3);- assert_eq!(updates[0].winner.unwrap().source, WinnerSource::Rule(higher));- assert_eq!(updates[1].winner.unwrap().source, WinnerSource::Rule(lower));- assert!(updates[2].winner.is_none());-- let repaired = engine- .exact_cascade_winner_updates_for_properties(nodes[0], &[lower_match], None, &[1])- .unwrap();- assert_eq!(repaired[0].winner.unwrap().source, WinnerSource::Rule(lower));-}--#[test]-fn cascade_state_includes_exact_element_declarations() {- let (mut engine, nodes) = linear_document();- let author = add_target_rule(&mut engine, StyleSheetObjectID(1), StyleAtomID(200));- engine.set_rule_declared_properties(author, &[(1, false), (2, false)]);- engine.set_element_declared_properties(- nodes[0],- ElementDeclarationKind::PresentationalHint,- unwritten_declarations(&[- DeclaredProperty {- property: 1,- important: false,- operator: CascadeOperator::Declared,- value: SpecifiedValueID(101),- },- DeclaredProperty {- property: 3,- important: false,- operator: CascadeOperator::Declared,- value: SpecifiedValueID(103),- },- ]),- Vec::new(),- );- engine.set_element_declared_properties(- nodes[0],- ElementDeclarationKind::InlineStyle,- unwritten_declarations(&[DeclaredProperty {- property: 2,- important: false,- operator: CascadeOperator::Declared,- value: SpecifiedValueID(102),- }]),- Vec::new(),- );- commit_test_setup(&mut engine);- let matches = vec![concrete_rule_match(&engine, nodes[0], author, 0, None)];-- engine.matches_for_cascade(matches, false, Some(nodes[0]));-- let key = WinnerGroupKey::current(nodes[0], engine.program.version());- assert!(- matches!(engine.winner_groups.winner(key, 1), Lookup::Known(winner) if winner.source == WinnerSource::Rule(author))- );- assert!(- matches!(engine.winner_groups.winner(key, 2), Lookup::Known(winner) if winner.source == WinnerSource::Element(ElementDeclarationKind::InlineStyle) && winner.key.value == SpecifiedValueID(102))- );- assert!(- matches!(engine.winner_groups.winner(key, 3), Lookup::Known(winner) if winner.source == WinnerSource::Element(ElementDeclarationKind::PresentationalHint) && winner.key.value == SpecifiedValueID(103))- );-}--#[test]-fn element_declaration_edits_repair_only_their_property_inventory() {- let (mut engine, nodes) = linear_document();- let author = add_target_rule(&mut engine, StyleSheetObjectID(1), StyleAtomID(200));- engine.set_rule_declared_properties_with_values(- author,- &[(1, false, SpecifiedValueID(101)), (2, false, SpecifiedValueID(102))],- );- engine.set_element_declared_properties(- nodes[0],- ElementDeclarationKind::PresentationalHint,- unwritten_declarations(&[- DeclaredProperty {- property: 1,- important: false,- operator: CascadeOperator::Declared,- value: SpecifiedValueID(201),- },- DeclaredProperty {- property: 3,- important: false,- operator: CascadeOperator::Declared,- value: SpecifiedValueID(203),- },- ]),- Vec::new(),- );- commit_test_setup(&mut engine);- let matches = vec![concrete_rule_match(&engine, nodes[0], author, 0, None)];- engine.matches_for_cascade(matches.clone(), false, Some(nodes[0]));- engine.remember_retained_match_answer(nodes[0], &matches);-- engine.set_element_declared_properties(- nodes[0],- ElementDeclarationKind::PresentationalHint,- unwritten_declarations(&[- DeclaredProperty {- property: 1,- important: false,- operator: CascadeOperator::Declared,- value: SpecifiedValueID(301),- },- DeclaredProperty {- property: 3,- important: false,- operator: CascadeOperator::Declared,- value: SpecifiedValueID(303),- },- ]),- Vec::new(),- );-- let key = WinnerGroupKey::current(nodes[0], engine.program.version());- assert!(- matches!(engine.winner_groups.winner(key, 1), Lookup::Known(winner) if winner.source == WinnerSource::Rule(author) && winner.key.value == SpecifiedValueID(101))- );- assert!(- matches!(engine.winner_groups.winner(key, 3), Lookup::Known(winner) if winner.source == WinnerSource::Element(ElementDeclarationKind::PresentationalHint) && winner.key.value == SpecifiedValueID(303))- );-}--#[test]-fn element_declaration_repairs_materialize_only_rules_declaring_their_properties() {- let (mut engine, nodes) = linear_document();- let deciding = add_target_rule(&mut engine, StyleSheetObjectID(1), StyleAtomID(200));- engine.set_rule_declared_properties_with_values(deciding, &[(1, false, SpecifiedValueID(101))]);- let unrelated = add_target_rule(&mut engine, StyleSheetObjectID(2), StyleAtomID(200));- engine.set_rule_declared_properties_with_values(unrelated, &[(5, false, SpecifiedValueID(105))]);- for kind in ElementDeclarationKind::ALL {- engine.set_element_declared_properties(nodes[0], kind, Vec::new(), Vec::new());- }- commit_test_setup(&mut engine);- let matches = vec![- concrete_rule_match(&engine, nodes[0], deciding, 0, None),- concrete_rule_match(&engine, nodes[0], unrelated, 1, None),- ];- engine.matches_for_cascade(matches.clone(), false, Some(nodes[0]));- engine.remember_retained_match_answer(nodes[0], &matches);-- let materialized_before = engine.counters().get(Counter::ElementDeclarationRepairMatches);- engine.set_element_declared_properties(- nodes[0],- ElementDeclarationKind::PresentationalHint,- unwritten_declarations(&[- DeclaredProperty {- property: 1,- important: false,- operator: CascadeOperator::Declared,- value: SpecifiedValueID(301),- },- DeclaredProperty {- property: 3,- important: false,- operator: CascadeOperator::Declared,- value: SpecifiedValueID(303),- },- ]),- Vec::new(),- );- assert_eq!(- engine.counters().get(Counter::ElementDeclarationRepairMatches) - materialized_before,- 1- );-- let key = WinnerGroupKey::current(nodes[0], engine.program.version());- assert!(- matches!(engine.winner_groups.winner(key, 1), Lookup::Known(winner) if winner.source == WinnerSource::Rule(deciding) && winner.key.value == SpecifiedValueID(101))- );- assert!(- matches!(engine.winner_groups.winner(key, 3), Lookup::Known(winner) if winner.source == WinnerSource::Element(ElementDeclarationKind::PresentationalHint) && winner.key.value == SpecifiedValueID(303))- );- assert!(- matches!(engine.winner_groups.winner(key, 5), Lookup::Known(winner) if winner.source == WinnerSource::Rule(unrelated) && winner.key.value == SpecifiedValueID(105))- );-}--#[test]-fn rule_declaration_edits_repair_only_their_property_inventory() {- let (mut engine, nodes) = linear_document();- let target = StyleAtomID(200);- let rule = add_target_rule(&mut engine, StyleSheetObjectID(1), target);- engine.set_rule_declared_properties_with_values(rule, &[(1, false, SpecifiedValueID(101))]);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- let exact_answer = engine.match_element(nodes[1]).unwrap();- let compact_answer = engine.matches_for_cascade(exact_answer.clone(), false, Some(nodes[1]));- engine.remember_retained_match_answer(nodes[1], &exact_answer);- engine.remember_cascade_input(nodes[1], &compact_answer);-- engine.set_rule_declared_properties_with_values(rule, &[(2, false, SpecifiedValueID(202))]);- let mut version = engine.program.rule_version(rule);- version.declaration_block = Some(DeclarationBlockID(2));- engine.replace_rule_version(rule, version);- assert_eq!(engine.host.program_staging.rule_declaration_changes.len(), 1);- assert_eq!(- engine.host.program_staging.rule_declaration_changes[0].old_properties,- [1]- );- assert_eq!(- engine.host.program_staging.rule_declaration_changes[0].new_properties,- [2]- );- assert_eq!(engine.program.declared_properties_of(rule)[0].property, 1);- assert_eq!(engine.current_declared_properties_of(rule)[0].property, 2);- assert!(engine.host.program_staging.base_version.is_some());- let feature_tests_before = engine.counters().get(Counter::LocalFeatureTests);-- let mut planned = Vec::new();- assert!(engine.take_style_transaction(nodes[0], |_, _, answers| {- assert!(- answers- .iter()- .all(|answer| answer.reaction & transaction::STYLE_REACTION_PSEUDO_INPUTS_MAY_HAVE_CHANGED != 0)- );- planned.extend(answers.iter().map(|answer| answer.style_node));- }));- assert_eq!(planned, vec![nodes[1].raw()]);- assert_eq!(engine.program.declared_properties_of(rule)[0].property, 2);- assert_eq!(engine.counters().get(Counter::LocalFeatureTests), feature_tests_before);- let key = WinnerGroupKey::current(nodes[1], engine.program.version());- assert!(matches!(engine.winner_groups.winner(key, 1), Lookup::KnownAbsent));- assert!(- matches!(engine.winner_groups.winner(key, 2), Lookup::Known(winner) if winner.source == WinnerSource::Rule(rule) && winner.key.value == SpecifiedValueID(202))- );- engine.discard_style_transaction_outputs();-}--#[test]-fn cascade_matching_preserves_empty_pseudo_element_presence() {- let (mut engine, nodes) = linear_document();- let first = add_target_rule(&mut engine, StyleSheetObjectID(1), StyleAtomID(200));- let second = add_target_rule(&mut engine, StyleSheetObjectID(2), StyleAtomID(201));- engine.set_rule_declared_properties(first, &[]);- engine.set_rule_declared_properties(second, &[]);- commit_test_setup(&mut engine);- let pseudo_element = Some(PseudoElementTarget::new(PseudoElementKind(0)));- let matches = vec![- concrete_rule_match(&engine, nodes[0], first, 0, pseudo_element),- concrete_rule_match(&engine, nodes[0], second, 1, pseudo_element),- ];-- let compacted = engine.matches_for_cascade(matches, false, None);-- assert_eq!(compacted.len(), 1);- assert_eq!(compacted[0].pseudo_element, pseudo_element);-}--#[test]-fn pseudo_winner_deltas_update_only_their_sparse_cascade_row() {- let (mut engine, nodes) = linear_document();- let pseudo = PseudoElementTarget::new(PseudoElementKind(0));- let element = add_target_rule(&mut engine, StyleSheetObjectID(1), StyleAtomID(200));- let lower = add_pseudo_target_rule(&mut engine, StyleSheetObjectID(2), StyleAtomID(201), pseudo);- let higher = add_pseudo_target_rule(&mut engine, StyleSheetObjectID(3), StyleAtomID(202), pseudo);- engine.set_rule_declared_properties_with_values(element, &[(1, false, SpecifiedValueID(100))]);- engine.set_rule_declared_properties_with_values(lower, &[(1, false, SpecifiedValueID(200))]);- engine.set_rule_declared_properties_with_values(higher, &[(1, false, SpecifiedValueID(300))]);- commit_test_setup(&mut engine);- let element_match = concrete_rule_match(&engine, nodes[0], element, 0, None);- let lower_match = concrete_rule_match(&engine, nodes[0], lower, 1, Some(pseudo));- let higher_match = concrete_rule_match(&engine, nodes[0], higher, 2, Some(pseudo));- engine.matches_for_cascade(vec![element_match, lower_match, higher_match], false, Some(nodes[0]));-- let element_key = WinnerGroupKey::current(nodes[0], engine.program.version());- let pseudo_key = WinnerGroupKey::current_pseudo(nodes[0], pseudo, engine.program.version());- let Lookup::Known((_, element_state)) = engine.winner_groups.token_for(element_key) else {- panic!("element winner state was not retained");- };- let removed = SelectorTruthDelta {- node: nodes[0],- rule: higher,- entry: engine.programs.entry_id(higher_match.program, higher_match.entry),- change: SetChange::Removed,- selector_truth_changed: true,- };-- assert!(engine.apply_cascade_winner_match_deltas(- nodes[0],- &[element_match, lower_match],- &[removed],- &mut Vec::new()- ));- assert!(matches!(- engine.winner_groups.token_for(element_key),- Lookup::Known((_, state)) if state == element_state- ));- assert!(matches!(- engine.winner_groups.winner(pseudo_key, 1),- Lookup::Known(winner) if winner.source == WinnerSource::Rule(lower)- ));-}--#[test]-fn held_pseudo_styles_without_witnesses_force_a_recompute() {- let mut engine = StyleEngine::new();- let mut raw_nodes = [0; 1];- engine.allocate_style_nodes(&mut raw_nodes);- let node = StyleNodeID::from_raw(raw_nodes[0]).unwrap();-- // No held pseudo styles: nothing to vouch for, the skip is safe.- assert!(engine.pseudo_cascade_states_are_unchanged(node));-- // A held pseudo style with neither a computed cascade record nor a winner row has no- // witness the check can judge, so it must force a recompute instead of passing- // vacuously.- let pseudo_kind = 2_u8;- engine- .computed_group_sets- .record_pseudo_kind_for_test(node, pseudo_kind);- assert!(!engine.pseudo_cascade_states_are_unchanged(node));-- // A current winner row plus the matching computed cascade record witness the held style- // and prove it unchanged.- let state = engine.intern_cascade_state(&[], None);- let target = tree::PseudoElementTarget::new(tree::PseudoElementKind(u16::from(pseudo_kind)));- let version = engine.program.version();- assert!(engine.winner_groups.set_pseudo(node, target, state, version));- engine- .retained- .computed_group_sets- .observe_pseudo_retained_cascade_state(- computed::ComputedStyleTarget::new(node, pseudo_kind),- Some((engine.retained.winner_groups.generation(), state)),- );- assert!(engine.pseudo_cascade_states_are_unchanged(node));-}--#[test]-fn assigned_marker_and_backdrop_winners_without_retained_states_force_a_recompute() {- for pseudo_kind in [1_u8, 5_u8] {- let mut engine = StyleEngine::new();- let mut raw_nodes = [0; 1];- engine.allocate_style_nodes(&mut raw_nodes);- let node = StyleNodeID::from_raw(raw_nodes[0]).unwrap();- let state = engine.intern_cascade_state(&[], None);- let target = tree::PseudoElementTarget::new(tree::PseudoElementKind(u16::from(pseudo_kind)));-- engine- .computed_group_sets- .record_pseudo_kind_for_test(node, pseudo_kind);- assert!(- engine- .retained- .winner_groups- .set_pseudo(node, target, state, engine.retained.program.version())- );-- assert!(- !engine.pseudo_cascade_states_are_unchanged(node),- "pseudo kind {pseudo_kind} passed without a retained cascade state"- );- }-}--fn add_two_class_target_rule(- engine: &mut StyleEngine,- sheet_object: StyleSheetObjectID,- target: StyleAtomID,- required: StyleAtomID,-) {- let program = engine.programs.add(test_selector_program(- ".target.required",- &[("target", target), ("required", required)],- ));-- let sheet = engine.add_sheet(sheet_object, CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);-}--fn add_nested_sibling_target_rule(- engine: &mut StyleEngine,- sheet_object: StyleSheetObjectID,- guard: StyleAtomID,- container: StyleAtomID,- target: StyleAtomID,-) {- let program = engine.programs.add(test_selector_program(- ".guard ~ .container .target",- &[("guard", guard), ("container", container), ("target", target)],- ));-- let sheet = engine.add_sheet(sheet_object, CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);-}--fn add_nested_sibling_target_fallback_rule(- engine: &mut StyleEngine,- sheet_object: StyleSheetObjectID,- guard: StyleAtomID,- container: StyleAtomID,- target: StyleAtomID,-) {- let mut builder = selector::SelectorProgramBuilder::new();- let guard = builder.push_feature(selector::FeatureTest::Class(guard));- let preceding = builder.push(selector::SelectorOp::PrecedingSibling(guard));- let container = builder.push_feature(selector::FeatureTest::Class(container));- let guarded_container = builder.push_compound(&[container, preceding]);- let ancestor = builder.push_ancestor(guarded_container);- let target = builder.push_feature(selector::FeatureTest::Class(target));- let all_positions = push_all_positions(&mut builder);- let selector = builder.push_compound(&[target, all_positions, ancestor]);- builder.push_entry(selector);- let program = engine.programs.add(builder.finish());-- let sheet = engine.add_sheet(sheet_object, CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);-}--fn add_retrying_selector_list_rule(- engine: &mut StyleEngine,- guard: StyleAtomID,- target: StyleAtomID,- extra: StyleAtomID,-) {- let mut builder = selector::SelectorProgramBuilder::new();- let target = builder.push_feature(selector::FeatureTest::Class(target));- builder.push_entry(target);- let extra = builder.push_feature(selector::FeatureTest::Class(extra));- let guard = builder.push_feature(selector::FeatureTest::Class(guard));- let preceding = builder.push(selector::SelectorOp::PrecedingSibling(guard));- let all_positions = push_all_positions(&mut builder);- let more_specific = builder.push_compound(&[target, extra, all_positions, preceding]);- let more_specific_entry = builder.push_entry(more_specific);- builder.set_entry_specificity(- more_specific_entry,- Specificity {- classes: 3,- ..Specificity::default()- },- );- let program = engine.programs.add(builder.finish());-- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);-}--fn add_nth_of_type_target_rule(engine: &mut StyleEngine, target: StyleAtomID, step: i32, offset: i32) {- let selector_text = format!(".target:nth-of-type({step}n{offset:+})");- let program = engine- .programs- .add(test_selector_program(&selector_text, &[("target", target)]));-- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);-}--fn add_nth_target_rule(engine: &mut StyleEngine, target: StyleAtomID, step: i32, offset: i32) {- let selector_text = format!(".target:nth-child({step}n{offset:+})");- let program = engine- .programs- .add(test_selector_program(&selector_text, &[("target", target)]));-- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);-}--fn add_guarded_nth_target_rule(engine: &mut StyleEngine, guard: StyleAtomID, also: StyleAtomID, target: StyleAtomID) {- let program = engine.programs.add(test_selector_program(- ".guard.also:nth-child(2n+1) .target",- &[("guard", guard), ("also", also), ("target", target)],- ));-- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);-}--/// `.guard.also + .target`, whose predecessor is found by one class and required to carry two.-fn add_two_class_adjacent_target_rule(- engine: &mut StyleEngine,- guard: StyleAtomID,- also: StyleAtomID,- target: StyleAtomID,-) {- let program = engine.programs.add(test_selector_program(- ".guard.also + .target",- &[("guard", guard), ("also", also), ("target", target)],- ));-- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);-}--/// `.guard + .guard + .target`.-fn add_double_guard_adjacent_target_rule(engine: &mut StyleEngine, guard: StyleAtomID, target: StyleAtomID) {- let program = engine.programs.add(test_selector_program(- ".guard + .guard + .target",- &[("guard", guard), ("target", target)],- ));-- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);-}--#[test]-fn structural_deltas_maintain_the_relation_columns() {- let (mut engine, nodes) = linear_document();- discard_transaction(&mut engine);- assert_eq!(- engine.tree().children(nodes[0]).collect::<Vec<_>>(),- vec![nodes[1], nodes[2], nodes[3]]- );- assert_eq!(- engine.tree().preorder(nodes[0]).collect::<Vec<_>>(),- vec![nodes[0], nodes[1], nodes[2], nodes[3]]- );- assert_eq!(engine.tree().connected_element_count(), 4);-}--#[test]-fn candidate_narrowing_requires_the_whole_subject_compound() {- let (mut engine, nodes) = linear_document();- let tag_span = StyleAtomID(100);- let tag_div = StyleAtomID(101);- let class_target = StyleAtomID(200);- for (node, tag) in [(nodes[1], tag_span), (nodes[2], tag_div)] {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, tag);- add_feature(&mut engine, node, LocalFeatureKey::Class(class_target));- }- discard_transaction(&mut engine);- prepare_empty_transaction_fact_view(&mut engine, nodes[0]);-- let mut regions = ImpactRegions::new();- engine.add_narrowed_region(- ImpactRegion::Subtree(nodes[0]),- &RoutingSite {- subject: &[DispatchKey::Class(class_target)],- subject_required: &[DispatchKey::TagName(tag_span)],- position: SubjectPosition::UNBOUNDED,- path: &[],- waypoints: &[],- in_flux: None,- exact_entry: None,- exact_tree_evaluation: None,- refresh_rule: None,- },- &mut regions,- );-- assert_eq!(regions.regions(), &[ImpactRegion::Node(nodes[1])]);-}--#[test]-fn exact_node_narrowing_does_not_enumerate_the_subject_posting() {- let (mut engine, nodes) = linear_document();- let class_target = StyleAtomID(200);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(class_target));- add_feature(&mut engine, nodes[2], LocalFeatureKey::Class(class_target));- discard_transaction(&mut engine);- prepare_empty_transaction_fact_view(&mut engine, nodes[0]);-- let posting_builds = engine.counters().get(Counter::RemainingPostingBuilds);- let mut regions = ImpactRegions::new();- engine.add_narrowed_region(- ImpactRegion::Node(nodes[1]),- &RoutingSite {- subject: &[DispatchKey::Class(class_target)],- subject_required: &[],- position: SubjectPosition::UNBOUNDED,- path: &[],- waypoints: &[],- in_flux: None,- exact_entry: None,- exact_tree_evaluation: None,- refresh_rule: None,- },- &mut regions,- );-- assert_eq!(regions.regions(), &[ImpactRegion::Node(nodes[1])]);- assert_eq!(engine.counters().get(Counter::RemainingPostingBuilds), posting_builds);-}--#[test]-fn exact_node_narrowing_preserves_posting_history_for_truth_patches() {- let (mut engine, nodes) = linear_document();- let class_target = StyleAtomID(200);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(class_target));- add_feature(&mut engine, nodes[2], LocalFeatureKey::Class(class_target));- discard_transaction(&mut engine);- prepare_empty_transaction_fact_view(&mut engine, nodes[0]);- engine.selector_truth_changes_active = true;-- let posting_builds = engine.counters().get(Counter::RemainingPostingBuilds);- let mut regions = ImpactRegions::new();- engine.add_narrowed_region(- ImpactRegion::Node(nodes[1]),- &RoutingSite {- subject: &[DispatchKey::Class(class_target)],- subject_required: &[],- position: SubjectPosition::UNBOUNDED,- path: &[],- waypoints: &[],- in_flux: None,- exact_entry: None,- exact_tree_evaluation: None,- refresh_rule: None,- },- &mut regions,- );-- assert_eq!(regions.regions(), &[ImpactRegion::Node(nodes[1])]);- // Truth patches also consume the posting's accumulated already-planned history, so this path- // must not replace the posting walk with local membership tests.- assert_eq!(- engine.counters().get(Counter::RemainingPostingBuilds),- posting_builds + 1- );-}--#[test]-fn a_required_key_in_flux_admits_both_sides_of_the_change() {- let (mut engine, nodes) = linear_document();- let class_target = StyleAtomID(200);- discard_transaction(&mut engine);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(class_target));- let mut transaction = engine.take_transaction();- let view = engine.transaction_fact_view_for(&mut transaction, nodes[0], &ImpactRegions::new());- engine.release_transaction(transaction);- engine.transaction_fact_view = Some(view);-- let mut regions = ImpactRegions::new();- engine.add_narrowed_region(- ImpactRegion::Node(nodes[1]),- &RoutingSite {- subject: &[DispatchKey::Class(class_target)],- subject_required: &[DispatchKey::Class(class_target)],- position: SubjectPosition::UNBOUNDED,- path: &[],- waypoints: &[],- in_flux: Some((nodes[1], DispatchKey::Class(class_target))),- exact_entry: None,- exact_tree_evaluation: None,- refresh_rule: None,- },- &mut regions,- );-- assert_eq!(regions.regions(), &[ImpactRegion::Node(nodes[1])]);-}--#[test]-fn an_attribute_in_flux_includes_every_name_form() {- let (mut engine, nodes) = linear_document();- let qualified_name = StyleAtomID(200);- let local_name = StyleAtomID(201);- let folded_qualified_name = StyleAtomID(202);- let folded_local_name = StyleAtomID(203);- engine.note_attribute_name_forms(- qualified_name,- index::AttributeNameForms {- local: local_name,- folded_name: folded_qualified_name,- folded_local: folded_local_name,- },- );- add_feature(&mut engine, nodes[1], LocalFeatureKey::Attribute(qualified_name));- discard_transaction(&mut engine);- remove_feature(&mut engine, nodes[1], LocalFeatureKey::Attribute(qualified_name));- let transaction = engine.take_transaction();- let features = engine.feature_delta_for(&transaction);-- for name in [qualified_name, local_name, folded_qualified_name, folded_local_name] {- assert!(- features- .keys_of_node(nodes[1])- .contains(&DispatchKey::AttributeName(name)),- "missing {name:?}"- );- }- engine.transaction_fact_view = Some(TransactionFactView {- root: nodes[0],- moved_features: features,- 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,- });- assert!(!engine.moved_features_of(nodes[1]).is_empty());- assert!(engine.moved_features_of(nodes[2]).is_empty());- engine.release_transaction(transaction);-}--#[test]-fn an_alternate_ancestor_witness_keeps_a_candidate_out_of_the_plan() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_target_rule(&mut engine, guard, target);- for node in [nodes[1], nodes[2]] {- add_feature(&mut engine, node, LocalFeatureKey::Class(guard));- }- add_feature(&mut engine, nodes[3], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- assert!(engine.begin_cold_matching_batch(nodes[0]));- for &node in &nodes {- engine.match_element(node).unwrap();- }- engine.end_cold_matching_batch();-- remove_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert!(planned.is_empty());- assert_eq!(engine.counters().get(Counter::PrefixConvergencePasses), 1);- assert_eq!(engine.counters().get(Counter::PrefixConvergenceNodes), 2);- assert_eq!(engine.counters().get(Counter::PrefixConvergenceStops), 1);-}--fn test_prefix_relation(engine: &mut StyleEngine, root: StyleNodeID) -> (Arc<RuleDispatch>, prefix::PrefixRelation) {- for node in engine.retained.tree.preorder(root) {- engine.retained.facts.ensure_row(node);- }- engine.retained.facts.apply_staged();- let (_, dispatch) = engine.prepare_scope_program(TreeScopeID::DOCUMENT);- let mut workspace = MatchScratch::default();- let facts = engine.retained.facts.primary();- let mut evaluator = MatchEvaluator::new(&engine.retained.tree, facts)- .with_match_workspace(&mut workspace, MatchEvaluationSide::Current);- let mut evaluation = PrefixEvaluation::new(- dispatch.prefixes(),- &engine.retained.tree,- facts,- &engine.retained.programs,- &mut evaluator,- None,- None,- );- let relation = dispatch- .prefixes()- .build_relation(&mut evaluation, root, &engine.retained.counters);- (dispatch, relation)-}--fn update_test_prefix_relation(- engine: &StyleEngine,- dispatch: &RuleDispatch,- relation: &mut prefix::PrefixRelation,- old_facts: &StyleNodeFacts,- changed: &[StyleNodeID],- geometry_root: Option<StyleNodeID>,-) -> Counters {- let mut workspace = MatchScratch::default();- let facts = engine.facts.primary();- let mut evaluator =- MatchEvaluator::new(&engine.tree, facts).with_match_workspace(&mut workspace, MatchEvaluationSide::Current);- let mut old_workspace = MatchScratch::default();- let mut old_evaluator = MatchEvaluator::new(&engine.tree, old_facts)- .with_match_workspace(&mut old_workspace, MatchEvaluationSide::OldTree);- let mut evaluation = PrefixEvaluation::new(- dispatch.prefixes(),- &engine.tree,- facts,- &engine.programs,- &mut evaluator,- None,- None,- );- let mut old_evaluation = PrefixEvaluation::new(- dispatch.prefixes(),- &engine.tree,- old_facts,- &engine.programs,- &mut old_evaluator,- None,- None,- );- let mut changed = changed.to_vec();- let counters = Counters::default();- if let Some(root) = geometry_root {- let mut geometry_nodes: Vec<_> = (0..old_facts.row_count())- .filter_map(|row| {- let row = u32::try_from(row).unwrap();- old_facts.has_row(row).then(|| old_facts.node_at(row))- })- .collect();- geometry_nodes.extend(engine.tree.preorder(root));- geometry_nodes.sort_unstable();- geometry_nodes.dedup();- changed.extend(relation.update_geometry(dispatch.prefixes(), &mut evaluation, &geometry_nodes, &counters));- changed.sort_unstable();- changed.dedup();- }- relation.update(- dispatch.prefixes(),- &mut evaluation,- &mut old_evaluation,- &changed,- &counters,- );- counters-}--#[test]-fn prefix_relation_copies_only_dispatch_complete_predicates() {- let (mut engine, nodes) = linear_document();- let first_class = StyleAtomID(200);- let second_class = StyleAtomID(201);- let id = StyleAtomID(202);- for &node in &nodes {- add_feature(&mut engine, node, LocalFeatureKey::Class(first_class));- }- add_feature(&mut engine, nodes[2], LocalFeatureKey::Class(second_class));- set_atom_feature(&mut engine, nodes[3], LocalFeatureKey::Id, id);- let mut builder = selector::SelectorProgramBuilder::new();- let feature = builder.push_feature(selector::FeatureTest::Id(id));- builder.push_entry(feature);- let atoms = [("first", first_class), ("second", second_class)];- let mut selectors = vec![- test_selector_program("*", &[]),- test_selector_program(".first", &atoms),- builder.finish(),- ];- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- for additional_tests in [false, true] {- for selector in selectors.drain(..) {- let program = engine.programs.add(selector);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);- }- discard_transaction(&mut engine);- let before = engine.counters.get(Counter::PrefixCompoundsEvaluated);- let (_, mut relation) = test_prefix_relation(&mut engine, nodes[0]);- let evaluated = engine.counters.get(Counter::PrefixCompoundsEvaluated) - before;- if additional_tests {- assert!(evaluated > 0);- } else {- assert_eq!(evaluated, 0);- }- let mut states = PrefixStates::new();- relation.install_answers(&mut states);- let expected = if additional_tests { [2, 2, 4, 3] } else { [2, 2, 2, 3] };- for (&node, count) in nodes.iter().zip(expected) {- assert_eq!(states.retained_matches_for(node).unwrap().len(), count);- }- selectors = vec![- test_selector_program(".first.second", &atoms),- test_selector_program(".first:nth-child(2n)", &atoms),- ];- }-}--#[test]-fn prefix_completion_reuses_positive_and_negative_relation_answers() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_target_rule(&mut engine, guard, target);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- add_feature(&mut engine, nodes[3], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);- let (dispatch, mut relation) = test_prefix_relation(&mut engine, nodes[0]);- let facts = engine.facts.primary();- let mut evaluator = MatchEvaluator::new(&engine.tree, facts);- let mut evaluation = PrefixEvaluation::new(- dispatch.prefixes(),- &engine.tree,- facts,- &engine.programs,- &mut evaluator,- None,- None,- );- let counters = Counters::default();- let mut states = PrefixStates::new();- let mut context = super::prefix::PrefixTransitionContext::new(&mut states, facts);- assert!(!states.complete_nodes_with_budget(- &mut context.scratch,- &mut context.effects,- &mut evaluation,- nodes.iter().copied(),- 0,- &counters- ));- relation.install_answers(&mut states);- states.relation = Some(Box::new(relation));- assert!(states.retained_matches_for(nodes[0]).unwrap().is_empty());- assert_eq!(states.retained_matches_for(nodes[3]).unwrap().len(), 1);- for budget in [0, usize::MAX] {- assert!(states.complete_nodes_with_budget(- &mut context.scratch,- &mut context.effects,- &mut evaluation,- nodes.iter().copied(),- budget,- &counters- ));- assert_eq!(counters.get(Counter::PrefixCompoundsEvaluated), 0);- assert_eq!(counters.get(Counter::PrefixTransitionMemoMisses), 0);- }-}--#[test]-fn prefix_relations_share_program_predicates_without_merging_their_paths() {- let (mut engine, nodes) = nested_document();- let attribute_name = StyleAtomID(200);- let disabled = StyleAtomID(201);- let target = StyleAtomID(202);- let ready = StyleAtomID(203);- let other = StyleAtomID(204);- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- for index in 0..33 {- let scope = StyleAtomID(300 + if index == 32 { 0 } else { index });- let literal: Vec<u16> = if index == 32 { "other" } else { "ready" }.encode_utf16().collect();- let mut builder = selector::SelectorProgramBuilder::new();- // Equal predicates deliberately have different program-relative text offsets.- builder.push_literal(&vec![0; index as usize]);- let (value_offset, value_length) = builder.push_literal(&literal);- let scope = builder.push_feature(selector::FeatureTest::Class(scope));- let ancestor_scope = builder.push_ancestor(scope);- let attribute = builder.push_feature(selector::FeatureTest::Attribute(selector::AttributeTest {- name: attribute_name,- any_namespace: false,- folded: attribute_name,- fold_in_namespace: StyleAtomID::NONE,- operator: selector::AttributeOperator::Substring,- value_atom: StyleAtomID::NONE,- value_offset,- value_length,- case: selector::AttributeCase::Sensitive,- }));- let disabled = builder.push_feature(selector::FeatureTest::Class(disabled));- let not_disabled = builder.push(selector::SelectorOp::Not(disabled));- let middle = builder.push_compound(&[attribute, not_disabled, ancestor_scope]);- let ancestor_middle = builder.push_ancestor(middle);- let subject = builder.push_feature(selector::FeatureTest::Class(target));- let subject = builder.push_compound(&[subject, ancestor_middle]);- builder.push_entry(subject);- let program = engine.programs.add(builder.finish());- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);- }- add_feature(&mut engine, nodes[0], LocalFeatureKey::Class(StyleAtomID(300)));- add_feature(&mut engine, nodes[3], LocalFeatureKey::Class(target));- engine.set_attribute_value_text(ready, &"ready".encode_utf16().collect::<Vec<_>>());- engine.set_attribute_value_text(other, &"other".encode_utf16().collect::<Vec<_>>());- engine.record_input(- InputKey::LocalFeature(nodes[1], LocalFeatureKey::Attribute(attribute_name)),- InputValue::Feature(FeatureValue::Absent),- InputValue::Feature(FeatureValue::Atom(ready)),- );- discard_transaction(&mut engine);- let before = engine.counters.get(Counter::PrefixCompoundsEvaluated);- let (dispatch, mut relation) = test_prefix_relation(&mut engine, nodes[0]);- assert_eq!(engine.counters.get(Counter::PrefixCompoundsEvaluated) - before, 2);- let mut states = PrefixStates::new();- relation.install_answers(&mut states);- let original = states.retained_matches_for(nodes[3]).unwrap().to_vec();- assert_eq!(original.len(), 1);-- let old_facts = engine.facts.primary().clone();- engine.record_input(- InputKey::LocalFeature(nodes[1], LocalFeatureKey::Attribute(attribute_name)),- InputValue::Feature(FeatureValue::Atom(ready)),- InputValue::Feature(FeatureValue::Atom(other)),- );- discard_transaction(&mut engine);- let counters = update_test_prefix_relation(&engine, &dispatch, &mut relation, &old_facts, &[nodes[1]], None);- assert_eq!(counters.get(Counter::PrefixCompoundsEvaluated), 2);- assert_eq!(relation.changed_answers.len(), 1);- assert_eq!(relation.changed_answers[0].0, nodes[3]);- assert_eq!(relation.changed_answers[0].1, original);- assert_eq!(relation.changed_answers[0].2.len(), 1);- assert_ne!(relation.changed_answers[0].1, relation.changed_answers[0].2);-}--#[test]-fn prefix_relation_reuses_local_facts_without_sharing_position() {- let mut engine = StyleEngine::new();- let mut raw = [0; 65];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<_> = raw.into_iter().map(|raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let class = StyleAtomID(200);- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- for index in 1..nodes.len() {- engine.record_tree_delta(- nodes[index],- None,- Some(relations(- Some(nodes[0].raw()),- (index > 1).then(|| nodes[index - 1].raw()),- None,- )),- );- }- let unused_attribute = StyleAtomID(202);- let observed_attribute = StyleAtomID(203);- for (index, &node) in nodes.iter().enumerate() {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- engine.record_input(- InputKey::LocalFeature(node, LocalFeatureKey::Id),- InputValue::Feature(FeatureValue::Absent),- InputValue::Feature(FeatureValue::Atom(StyleAtomID(500 + index as u32))),- );- engine.record_input(- InputKey::LocalFeature(node, LocalFeatureKey::Attribute(unused_attribute)),- InputValue::Feature(FeatureValue::Absent),- InputValue::Feature(FeatureValue::Atom(StyleAtomID(600 + index as u32))),- );- }-- // The root has the same local facts as its children, but :root and nth-child- // still distinguish their positions. :not(:root) uses a program predicate.- let mut builder = selector::SelectorProgramBuilder::new();- let feature = builder.push_feature(selector::FeatureTest::Class(class));- let root = builder.push(selector::SelectorOp::Root);- let not_root = builder.push(selector::SelectorOp::Not(root));- let attribute = builder.push_feature(selector::FeatureTest::Attribute(selector::AttributeTest {- name: observed_attribute,- any_namespace: false,- folded: observed_attribute,- fold_in_namespace: StyleAtomID::NONE,- operator: selector::AttributeOperator::Presence,- value_atom: StyleAtomID::NONE,- value_offset: 0,- value_length: 0,- case: selector::AttributeCase::Sensitive,- }));- let not_attribute = builder.push(selector::SelectorOp::Not(attribute));- let compound = builder.push_compound(&[feature, not_root, not_attribute]);- builder.push_entry_for_pseudo(compound, None);- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- for selector in [- builder.finish(),- test_selector_program(".same:nth-child(2n)", &[("same", class)]),- ] {- let program = engine.programs.add(selector);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);- }- discard_transaction(&mut engine);- let before = engine.counters.get(Counter::PrefixCompoundsEvaluated);- let (dispatch, mut relation) = test_prefix_relation(&mut engine, nodes[0]);- let evaluations = engine.counters.get(Counter::PrefixCompoundsEvaluated) - before;- assert!(- evaluations < 16,- "repeated local facts required {evaluations} evaluations"- );- let old_facts = engine.facts.primary().clone();- let counters = update_test_prefix_relation(&engine, &dispatch, &mut relation, &old_facts, &nodes, None);- let evaluations = counters.get(Counter::PrefixCompoundsEvaluated);- assert_eq!(- evaluations, 0,- "unchanged local facts must retain their predicate answers"- );- let mut states = PrefixStates::new();- relation.install_answers(&mut states);- assert!(states.retained_matches_for(nodes[0]).unwrap().is_empty());- for (index, &node) in nodes.iter().enumerate().skip(1) {- assert_eq!(- states.retained_matches_for(node).unwrap().len(),- 1 + usize::from(index % 2 == 0)- );- }- let old_facts = engine.facts.primary().clone();- for (index, &node) in nodes.iter().enumerate() {- engine.record_input(- InputKey::LocalFeature(node, LocalFeatureKey::Attribute(unused_attribute)),- InputValue::Feature(FeatureValue::Atom(StyleAtomID(600 + index as u32))),- InputValue::Feature(FeatureValue::Atom(StyleAtomID(1000 + index as u32))),- );- }- discard_transaction(&mut engine);- let counters = update_test_prefix_relation(&engine, &dispatch, &mut relation, &old_facts, &nodes, None);- assert_eq!(counters.get(Counter::PrefixCompoundsEvaluated), 0);- assert!(relation.changed_answers.is_empty());-- // A dependency nested inside :not() must still invalidate the predicate.- let old_facts = engine.facts.primary().clone();- add_feature(&mut engine, nodes[1], LocalFeatureKey::Attribute(observed_attribute));- discard_transaction(&mut engine);- update_test_prefix_relation(&engine, &dispatch, &mut relation, &old_facts, &[nodes[1]], None);- assert_eq!(relation.changed_answers.len(), 1);- assert_eq!(relation.changed_answers[0].0, nodes[1]);- assert!(relation.changed_answers[0].2.is_empty());-}--#[test]-fn prefix_relation_local_fact_cache_separates_predicates_and_tracks_changes() {- for negate in [false, true] {- let mut engine = StyleEngine::new();- let mut raw = [0; 65];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<_> = raw.into_iter().map(|raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let same = StyleAtomID(200);- let selected = StyleAtomID(201);- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- for index in 1..nodes.len() {- engine.record_tree_delta(- nodes[index],- None,- Some(relations(- Some(nodes[0].raw()),- (index > 1).then(|| nodes[index - 1].raw()),- None,- )),- );- }- for (index, &node) in nodes.iter().enumerate() {- add_feature(&mut engine, node, LocalFeatureKey::Class(same));- if index % 2 == 0 {- add_feature(&mut engine, node, LocalFeatureKey::Class(selected));- }- }- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- // Both compounds dispatch on .same, but have different answers. Negation- // exercises program predicates, including shared false results.- for require_selected in [false, true] {- let mut builder = selector::SelectorProgramBuilder::new();- let same = builder.push_feature(selector::FeatureTest::Class(same));- let mut operands = vec![same];- if require_selected {- let selected = builder.push_feature(selector::FeatureTest::Class(selected));- operands.push(if negate {- builder.push(selector::SelectorOp::Not(selected))- } else {- selected- });- }- let compound = builder.push_compound(&operands);- builder.push_entry_for_pseudo(compound, None);- let program = engine.programs.add(builder.finish());- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);- }- discard_transaction(&mut engine);- let before = engine.counters.get(Counter::PrefixCompoundsEvaluated);- let (dispatch, mut relation) = test_prefix_relation(&mut engine, nodes[0]);- let evaluations = engine.counters.get(Counter::PrefixCompoundsEvaluated) - before;- assert!(- evaluations < 16,- "repeated local facts required {evaluations} evaluations"- );- let mut states = PrefixStates::new();- relation.install_answers(&mut states);- for (index, &node) in nodes.iter().enumerate() {- assert_eq!(- states.retained_matches_for(node).unwrap().len(),- 1 + usize::from((index % 2 == 0) != negate)- );- }-- // Move every element between fact groups. Shared positive and negative- // answers must change, and rebuilding must agree with the update.- let old_facts = engine.facts.primary().clone();- for (index, &node) in nodes.iter().enumerate() {- if index % 2 == 0 {- remove_feature(&mut engine, node, LocalFeatureKey::Class(selected));- } else {- add_feature(&mut engine, node, LocalFeatureKey::Class(selected));- }- }- discard_transaction(&mut engine);- let counters = update_test_prefix_relation(&engine, &dispatch, &mut relation, &old_facts, &nodes, None);- let evaluations = counters.get(Counter::PrefixCompoundsEvaluated);- assert!(- evaluations < 16,- "repeated local facts required {evaluations} update evaluations"- );- assert_eq!(relation.changed_answers.len(), nodes.len());- relation.install_answers(&mut states);- let (_, mut rebuilt) = test_prefix_relation(&mut engine, nodes[0]);- let mut rebuilt_states = PrefixStates::new();- rebuilt.install_answers(&mut rebuilt_states);- for (index, &node) in nodes.iter().enumerate() {- let selected = index % 2 != 0;- let matches = states.retained_matches_for(node).unwrap();- assert_eq!(matches.len(), 1 + usize::from(selected != negate));- assert_eq!(matches, rebuilt_states.retained_matches_for(node).unwrap());- }- }-}--#[test]-fn prefix_relations_propagate_local_changes_over_every_axis() {- for (selector, nested, guard_index, target_index) in [- (".guard > .target", true, 2, 3),- (".guard .target", true, 1, 3),- (".guard + .target", false, 1, 2),- (".guard ~ .target", false, 1, 3),- ] {- let (mut engine, nodes) = if nested { nested_document() } else { linear_document() };- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- let program = engine- .programs- .add(test_selector_program(selector, &[("guard", guard), ("target", target)]));- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);- add_feature(&mut engine, nodes[guard_index], LocalFeatureKey::Class(guard));- add_feature(&mut engine, nodes[target_index], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);- let (dispatch, mut relation) = test_prefix_relation(&mut engine, nodes[0]);- let mut states = PrefixStates::new();- relation.install_answers(&mut states);- assert_eq!(- states.retained_matches_for(nodes[target_index]).unwrap().len(),- 1,- "{selector}"- );-- let old_facts = engine.facts.primary().clone();- remove_feature(&mut engine, nodes[guard_index], LocalFeatureKey::Class(guard));- discard_transaction(&mut engine);- update_test_prefix_relation(- &engine,- &dispatch,- &mut relation,- &old_facts,- &[nodes[guard_index]],- None,- );- assert_eq!(relation.changed_answers.len(), 1, "{selector}");- assert_eq!(relation.changed_answers[0].0, nodes[target_index]);- assert_eq!(relation.changed_answers[0].1.len(), 1);- assert!(relation.changed_answers[0].2.is_empty());- relation.install_answers(&mut states);- assert!(states.retained_matches_for(nodes[target_index]).unwrap().is_empty());-- let old_facts = engine.facts.primary().clone();- add_feature(&mut engine, nodes[guard_index], LocalFeatureKey::Class(guard));- discard_transaction(&mut engine);- update_test_prefix_relation(- &engine,- &dispatch,- &mut relation,- &old_facts,- &[nodes[guard_index]],- None,- );- assert_eq!(relation.changed_answers.len(), 1, "{selector}");- assert!(relation.changed_answers[0].1.is_empty());- assert_eq!(relation.changed_answers[0].2.len(), 1);-- // Both ends of the dependency change in one batch, with the target delivered first.- // The terminal must observe the new predecessor even if it was independently scheduled.- for present in [false, true] {- let old_facts = engine.facts.primary().clone();- for (node, class) in [(nodes[target_index], target), (nodes[guard_index], guard)] {- if present {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- } else {- remove_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- }- discard_transaction(&mut engine);- update_test_prefix_relation(- &engine,- &dispatch,- &mut relation,- &old_facts,- &[nodes[target_index], nodes[guard_index]],- None,- );- assert_eq!(relation.changed_answers.len(), 1, "{selector}");- assert_eq!(relation.changed_answers[0].0, nodes[target_index]);- assert_eq!(relation.changed_answers[0].2.len(), usize::from(present));- }- }-}--#[test]-fn prefix_relation_deltas_preserve_an_alternate_ancestor_witness() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_target_rule(&mut engine, guard, target);- for node in [nodes[1], nodes[2]] {- add_feature(&mut engine, node, LocalFeatureKey::Class(guard));- }- add_feature(&mut engine, nodes[3], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);- let (dispatch, mut relation) = test_prefix_relation(&mut engine, nodes[0]);-- let old_facts = engine.facts.primary().clone();- remove_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- discard_transaction(&mut engine);- update_test_prefix_relation(&engine, &dispatch, &mut relation, &old_facts, &[nodes[1]], None);- assert!(relation.changed_answers.is_empty());-- let old_facts = engine.facts.primary().clone();- remove_feature(&mut engine, nodes[2], LocalFeatureKey::Class(guard));- discard_transaction(&mut engine);- update_test_prefix_relation(&engine, &dispatch, &mut relation, &old_facts, &[nodes[2]], None);- assert_eq!(relation.changed_answers.len(), 1);- assert_eq!(relation.changed_answers[0].0, nodes[3]);- assert!(relation.changed_answers[0].2.is_empty());-}--#[test]-fn prefix_relation_removal_preserves_a_surviving_sibling_witness() {- for selector in [".guard ~ .target", ".parent .guard ~ .target"] {- for removed_index in [1, 2] {- for change_survivor in [false, true] {- let (mut engine, nodes) = linear_document();- let parent = StyleAtomID(200);- let guard = StyleAtomID(201);- let target = StyleAtomID(202);- let program = engine.programs.add(test_selector_program(- selector,- &[("parent", parent), ("guard", guard), ("target", target)],- ));- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);- add_feature(&mut engine, nodes[0], LocalFeatureKey::Class(parent));- for index in [1, 2] {- add_feature(&mut engine, nodes[index], LocalFeatureKey::Class(guard));- }- add_feature(&mut engine, nodes[3], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);- let (dispatch, mut relation) = test_prefix_relation(&mut engine, nodes[0]);-- let old_facts = engine.facts.primary().clone();- let survivor = nodes[3 - removed_index];- if change_survivor {- remove_feature(&mut engine, survivor, LocalFeatureKey::Class(guard));- }- engine.record_tree_delta(- nodes[removed_index],- Some(relations(- Some(nodes[0].raw()),- (removed_index == 2).then_some(nodes[1].raw()),- Some(nodes[removed_index + 1].raw()),- )),- None,- );- discard_transaction(&mut engine);- update_test_prefix_relation(- &engine,- &dispatch,- &mut relation,- &old_facts,- &[survivor],- Some(nodes[0]),- );- assert_eq!(relation.changed_answers.len(), usize::from(change_survivor));- if change_survivor {- assert_eq!(relation.changed_answers[0].0, nodes[3]);- assert!(relation.changed_answers[0].2.is_empty());- } else {- let old_facts = engine.facts.primary().clone();- engine.record_tree_delta(- survivor,- Some(relations(Some(nodes[0].raw()), None, Some(nodes[3].raw()))),- None,- );- discard_transaction(&mut engine);- update_test_prefix_relation(&engine, &dispatch, &mut relation, &old_facts, &[], Some(nodes[0]));- assert_eq!(relation.changed_answers.len(), 1);- assert_eq!(relation.changed_answers[0].0, nodes[3]);- assert!(relation.changed_answers[0].2.is_empty());- }- }- }- }-}--#[test]-fn prefix_relation_reused_slots_do_not_determine_sibling_order() {- let (mut engine, nodes) = linear_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- let program = engine.programs.add(test_selector_program(- ".guard ~ .target",- &[("guard", guard), ("target", target)],- ));- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- add_feature(&mut engine, nodes[2], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);- let (dispatch, mut relation) = test_prefix_relation(&mut engine, nodes[0]);-- let old_facts = engine.facts.primary().clone();- engine.record_tree_delta(- nodes[1],- Some(relations(Some(nodes[0].raw()), None, Some(nodes[2].raw()))),- None,- );- discard_transaction(&mut engine);- update_test_prefix_relation(&engine, &dispatch, &mut relation, &old_facts, &[], Some(nodes[0]));- assert_eq!(relation.changed_answers.len(), 1);- assert!(relation.changed_answers[0].2.is_empty());-- // A new node reuses the earlier guard's slot but follows the target in the actual tree.- let old_facts = engine.facts.primary().clone();- let mut raw = [0];- engine.allocate_style_nodes(&mut raw);- let replacement = StyleNodeID::from_raw(raw[0]).unwrap();- add_feature(&mut engine, replacement, LocalFeatureKey::Class(guard));- engine.record_tree_delta(- replacement,- None,- Some(relations(Some(nodes[0].raw()), Some(nodes[3].raw()), None)),- );- discard_transaction(&mut engine);- update_test_prefix_relation(&engine, &dispatch, &mut relation, &old_facts, &[], Some(nodes[0]));- assert!(relation.changed_answers.is_empty());-- let old_facts = engine.facts.primary().clone();- engine.record_tree_delta(- replacement,- Some(relations(Some(nodes[0].raw()), Some(nodes[3].raw()), None)),- Some(relations(Some(nodes[0].raw()), None, Some(nodes[2].raw()))),- );- discard_transaction(&mut engine);- update_test_prefix_relation(&engine, &dispatch, &mut relation, &old_facts, &[], Some(nodes[0]));- assert_eq!(relation.changed_answers.len(), 1);- assert_eq!(relation.changed_answers[0].0, nodes[2]);- assert_eq!(relation.changed_answers[0].2.len(), 1);-- let old_facts = engine.facts.primary().clone();- remove_feature(&mut engine, replacement, LocalFeatureKey::Class(guard));- discard_transaction(&mut engine);- update_test_prefix_relation(&engine, &dispatch, &mut relation, &old_facts, &[replacement], None);- assert_eq!(relation.changed_answers.len(), 1);- assert!(relation.changed_answers[0].2.is_empty());-}--#[test]-fn prefix_relations_update_adjacency_and_positions_after_sibling_removal() {- let (mut engine, nodes) = linear_document();- let guard = StyleAtomID(200);- let also = StyleAtomID(201);- let target = StyleAtomID(202);- add_two_class_adjacent_target_rule(&mut engine, guard, also, target);- add_nth_target_rule(&mut engine, target, 0, 2);- for class in [guard, also] {- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(class));- }- add_feature(&mut engine, nodes[3], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);- let (dispatch, mut relation) = test_prefix_relation(&mut engine, nodes[0]);- let mut states = PrefixStates::new();- relation.install_answers(&mut states);- assert!(states.retained_matches_for(nodes[3]).unwrap().is_empty());-- let old_facts = engine.facts.primary().clone();- engine.record_tree_delta(- nodes[2],- Some(relations(- Some(nodes[0].raw()),- Some(nodes[1].raw()),- Some(nodes[3].raw()),- )),- None,- );- discard_transaction(&mut engine);- update_test_prefix_relation(&engine, &dispatch, &mut relation, &old_facts, &[], Some(nodes[0]));- assert_eq!(relation.changed_answers.len(), 1);- assert_eq!(relation.changed_answers[0].0, nodes[3]);- assert!(relation.changed_answers[0].1.is_empty());- assert_eq!(relation.changed_answers[0].2.len(), 2);-- let old_facts = engine.facts.primary().clone();- engine.record_tree_delta(- nodes[1],- Some(relations(Some(nodes[0].raw()), None, Some(nodes[3].raw()))),- None,- );- discard_transaction(&mut engine);- update_test_prefix_relation(&engine, &dispatch, &mut relation, &old_facts, &[], Some(nodes[0]));- assert_eq!(relation.changed_answers.len(), 1);- assert_eq!(relation.changed_answers[0].0, nodes[3]);- assert_eq!(relation.changed_answers[0].1.len(), 2);- assert!(relation.changed_answers[0].2.is_empty());-}--#[test]-fn an_empty_sparse_route_does_not_compile_its_region() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_target_rule(&mut engine, guard, target);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- discard_transaction(&mut engine);-- remove_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert!(planned.is_empty());-}--#[test]-fn overlapping_prefix_changes_are_evaluated_once() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_target_rule(&mut engine, guard, target);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- add_feature(&mut engine, nodes[3], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- assert!(engine.begin_cold_matching_batch(nodes[0]));- for &node in &nodes {- engine.match_element(node).unwrap();- }- engine.end_cold_matching_batch();-- remove_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- add_feature(&mut engine, nodes[2], LocalFeatureKey::Class(target));- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes[3].raw()]);- assert_eq!(engine.counters().get(Counter::PrefixConvergencePasses), 1);- assert_eq!(engine.counters().get(Counter::PrefixConvergenceNodes), 3);-}--#[test]-fn retained_prefix_transitions_supply_invalidation_and_matching() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_target_rule(&mut engine, guard, target);- for (node, class) in [(nodes[1], guard), (nodes[3], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- assert!(engine.begin_cold_matching_batch(nodes[0]));- for &node in &nodes {- engine.match_element(node).unwrap();- }- engine.end_cold_matching_batch();-- remove_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes[3].raw()]);- assert!(engine.begin_cold_matching_batch(nodes[0]));- assert!(engine.match_element(nodes[3]).unwrap().is_empty());- engine.end_cold_matching_batch();-- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- planned.clear();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes[3].raw()]);-}--#[test]-fn a_foreign_scope_input_keeps_the_document_prefix_relation() {- let (mut engine, nodes) = nested_document();- let scope = TreeScopeID(1);- let shadow_child = attach_shadow_tree(&mut engine, nodes[3], scope, 1)[1];- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_target_rule(&mut engine, guard, target);- for (node, class) in [(nodes[1], guard), (nodes[3], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- let adopted_program = engine- .programs- .add(test_class_selector_program(".target", &[("target", target)], None));- let adopted_sheet = engine.add_sheet(StyleSheetObjectID(2), CascadeOrigin::Author);- let adopted_rule = engine.append_rule(adopted_sheet, None, RuleKind::Style);- engine.add_routing_rule(adopted_rule, adopted_program);- let mut version = engine.program.rule_version(adopted_rule);- version.selector_program = Some(adopted_program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(adopted_rule, version);- discard_transaction(&mut engine);-- engine.begin_published_match_answer_completion_batch(nodes[0], true);- assert_eq!(engine.match_element(nodes[3]).unwrap().len(), 1);- engine.end_published_match_answer_completion_batch();- assert_eq!(engine.counters().get(Counter::PrefixRelationBuilds), 1);-- add_feature(&mut engine, shadow_child, LocalFeatureKey::Class(guard));- remove_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes[3].raw()]);- assert_eq!(engine.counters().get(Counter::PrefixRelationUpdates), 1);- assert_eq!(engine.counters().get(Counter::PrefixRelationBuilds), 1);-- engine.begin_published_match_answer_completion_batch(nodes[0], true);- assert!(engine.match_element(nodes[3]).unwrap().is_empty());- engine.end_published_match_answer_completion_batch();- assert_eq!(engine.counters().get(Counter::PrefixRelationBuilds), 1);-- engine.attach_sheet(adopted_sheet, scope);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- planned.clear();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert!(planned.contains(&nodes[3].raw()));- assert_eq!(engine.counters().get(Counter::PrefixRelationUpdates), 2);- assert_eq!(engine.counters().get(Counter::PrefixRelationBuilds), 1);-- engine.begin_published_match_answer_completion_batch(nodes[0], true);- assert_eq!(engine.match_element(nodes[3]).unwrap().len(), 1);- engine.end_published_match_answer_completion_batch();- assert_eq!(engine.counters().get(Counter::PrefixRelationBuilds), 1);-}--#[test]-fn a_maintained_relation_leaves_shadow_scope_routes_to_their_own_program() {- let (mut engine, nodes) = nested_document();- let scope = TreeScopeID(1);- let shadow = attach_shadow_tree(&mut engine, nodes[3], scope, 2);- let (shadow_outer, shadow_inner) = (shadow[1], shadow[2]);- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- let inner = StyleAtomID(202);- add_guard_target_rule(&mut engine, guard, target);- let shadow_program = engine.programs.add(test_selector_program_with_metadata(- ".guard .inner",- &[("guard", guard), ("inner", inner)],- Some(Specificity {- classes: 2,- ..Specificity::default()- }),- None,- ));- let shadow_sheet = engine.add_sheet(StyleSheetObjectID(2), CascadeOrigin::Author);- engine.attach_sheet(shadow_sheet, scope);- let shadow_rule = engine.append_rule(shadow_sheet, None, RuleKind::Style);- engine.add_routing_rule(shadow_rule, shadow_program);- let mut version = engine.program.rule_version(shadow_rule);- version.selector_program = Some(shadow_program);- version.declaration_block = Some(DeclarationBlockID(2));- engine.replace_rule_version(shadow_rule, version);- for (node, class) in [(nodes[1], guard), (nodes[3], target), (shadow_inner, inner)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- // NB: A prepared shadow program may reach retention without any matching ask.- // Its row allocation must already be charged before retention trims it.- engine.begin_published_match_answer_completion_batch(nodes[0], true);- engine.end_published_match_answer_completion_batch();-- engine.begin_published_match_answer_completion_batch(nodes[0], true);- assert_eq!(engine.match_element(nodes[3]).unwrap().len(), 1);- assert!(engine.match_element(shadow_inner).unwrap().is_empty());- engine.end_published_match_answer_completion_batch();- assert_eq!(engine.counters().get(Counter::PrefixRelationBuilds), 1);-- add_feature(&mut engine, shadow_outer, LocalFeatureKey::Class(guard));- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![shadow_inner.raw()]);- assert_eq!(engine.counters().get(Counter::PrefixRelationBuilds), 1);-- engine.begin_published_match_answer_completion_batch(nodes[0], true);- assert_eq!(engine.match_element(shadow_inner).unwrap().len(), 1);- engine.end_published_match_answer_completion_batch();- assert_eq!(engine.counters().get(Counter::PrefixRelationBuilds), 1);-}--#[test]-fn a_maintained_relation_leaves_shared_selector_shadow_routes_to_their_own_program() {- let (mut engine, nodes) = nested_document();- let scope = TreeScopeID(1);- let shadow = attach_shadow_tree(&mut engine, nodes[3], scope, 2);- let (shadow_outer, shadow_inner) = (shadow[1], shadow[2]);- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_target_rule(&mut engine, guard, target);- let program = engine.programs.add(test_selector_program_with_metadata(- ".guard .target",- &[("guard", guard), ("target", target)],- Some(Specificity {- classes: 2,- ..Specificity::default()- }),- None,- ));- let shadow_sheet = engine.add_sheet(StyleSheetObjectID(2), CascadeOrigin::Author);- engine.attach_sheet(shadow_sheet, scope);- let shadow_rule = engine.append_rule(shadow_sheet, None, RuleKind::Style);- engine.add_routing_rule(shadow_rule, program);- let mut version = engine.program.rule_version(shadow_rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(2));- engine.replace_rule_version(shadow_rule, version);- for (node, class) in [(nodes[1], guard), (nodes[3], target), (shadow_inner, target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- engine.begin_published_match_answer_completion_batch(nodes[0], true);- assert_eq!(engine.match_element(nodes[3]).unwrap().len(), 1);- assert!(engine.match_element(shadow_inner).unwrap().is_empty());- engine.end_published_match_answer_completion_batch();- assert_eq!(engine.counters().get(Counter::PrefixRelationBuilds), 1);-- add_feature(&mut engine, shadow_outer, LocalFeatureKey::Class(guard));- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![shadow_inner.raw()]);- assert_eq!(engine.counters().get(Counter::PrefixRelationBuilds), 1);-- engine.begin_published_match_answer_completion_batch(nodes[0], true);- assert_eq!(engine.match_element(shadow_inner).unwrap().len(), 1);- engine.end_published_match_answer_completion_batch();- assert_eq!(engine.counters().get(Counter::PrefixRelationBuilds), 1);-}--#[test]-fn covered_prefix_changes_forget_only_the_covered_subtree() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- let rule = add_guard_target_rule(&mut engine, guard, target);- engine.set_rule_declared_properties(rule, &[(property_id::COLOR, false)]);- for (node, class) in [(nodes[1], guard), (nodes[3], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- assert!(engine.begin_cold_matching_batch(nodes[0]));- assert_eq!(engine.match_element_for_cascade(nodes[3]).unwrap().len(), 1);- engine.end_cold_matching_batch();-- remove_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- let mut transaction = engine.take_transaction();- let mut regions = ImpactRegions::new();- engine.transaction_fact_view = Some(engine.transaction_fact_view_for(&mut transaction, nodes[0], ®ions));-- regions.add(ImpactRegion::Subtree(nodes[1]));-- let route = engine.routing.routes_for(RoutingKey::Class(guard))[0];- let mut pending = PendingRoutes::new();- pending- .regions_for(PendingRoute {- route,- exact_tree_evaluation: None,- })- .push(ImpactRegion::Subtree(nodes[1]));- pending.finish();-- let outcome = engine.add_prefix_convergence_regions(- &mut pending,- &mut regions,- false,- &transaction,- &SequenceChanges::new(),- &[],- );- assert!(engine.prefix_caches.borrow().states.is_current());- assert!(!outcome.sibling_routes_are_covered);- assert!(pending.is_empty());- // The walk skips the covered subtree but keeps the cache warm: only the transitions- // that depend on the skipped node are forgotten.- let (scope_program, _) = engine.prepare_scope_program(TreeScopeID::DOCUMENT);- let prefix_caches = std::sync::Arc::clone(&engine.prefix_caches);- let mut caches = prefix_caches.borrow_mut();- let Lookup::Known(states) = caches.states.lookup_mut(scope_program) else {- panic!("the document program's states survive a covered skip");- };- assert!(states.has_transition(nodes[0]));- assert!(!states.has_transition(nodes[1]));- assert!(!states.has_transition(nodes[3]));- let _ = states;- drop(caches);-- engine.transaction_fact_view = None;-- engine.release_transaction(transaction);-- assert!(engine.begin_cold_matching_batch(nodes[0]));- assert!(engine.match_element_for_cascade(nodes[3]).unwrap().is_empty());- engine.end_cold_matching_batch();-}--#[test]-fn selective_matching_completes_a_bounded_prefix_transition_window() {- let mut engine = StyleEngine::new();- let mut raw = vec![0_u32; PREFIX_TRANSITION_CACHE_COMPLETION_BUDGET + 3];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- for index in 1..nodes.len() {- engine.record_tree_delta(- nodes[index],- None,- Some(relations(Some(nodes[index - 1].raw()), None, None)),- );- }- for &node in &nodes {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, StyleAtomID(100));- }-- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_target_rule(&mut engine, guard, target);- for (node, class) in [(nodes[0], guard), (*nodes.last().unwrap(), target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- engine.force_bounded_prefix_completion = true;- assert!(engine.begin_cold_matching_batch(nodes[0]));- engine.match_element(nodes[0]).unwrap();- engine.end_cold_matching_batch();- assert!(engine.begin_cold_matching_batch(nodes[0]));- assert_eq!(engine.match_element(*nodes.last().unwrap()).unwrap().len(), 1);- engine.end_cold_matching_batch();-- remove_feature(&mut engine, *nodes.last().unwrap(), LocalFeatureKey::Class(target));- let cache_hits_before = engine.counters().get(Counter::PrefixTransitionCacheHits);- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes.last().unwrap().raw()]);- assert_eq!(- engine.counters().get(Counter::PrefixTransitionCacheHits) - cache_hits_before,- 1,- "invalidation reuses the retained partial prefix transition cache"- );-}--#[test]-fn a_prefix_upquery_retains_every_transition_on_its_ancestor_chain() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_target_rule(&mut engine, guard, target);- for (node, class) in [(nodes[1], guard), (nodes[3], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- assert!(engine.begin_cold_matching_batch(nodes[0]));- assert_eq!(engine.match_element(nodes[3]).unwrap().len(), 1);- let (scope_program, _) = engine.prepare_scope_program(TreeScopeID::DOCUMENT);- let prefix_caches = std::sync::Arc::clone(&engine.batch_matching_traversal.as_ref().unwrap().prefix_caches);- let mut caches = prefix_caches.borrow_mut();- let states = match caches.states.lookup_mut(scope_program) {- Lookup::Known(states) => states,- Lookup::KnownAbsent | Lookup::Missing(_) => panic!("expected a retained prefix program"),- };- assert!(nodes.iter().all(|&node| !states.has_transition(node)));- let _ = states;- drop(caches);- assert_eq!(engine.match_element(nodes[3]).unwrap().len(), 1);- engine.end_cold_matching_batch();- {- let caches = prefix_caches.borrow();- let states = caches.states.lookup(scope_program).sparse().unwrap();- assert!(nodes.iter().all(|&node| states.has_transition(node)));- }-- let mut caches = engine.retained.prefix_caches.borrow_mut();- caches.states.make_scratch();- assert!(matches!(caches.states.lookup_mut(scope_program), Lookup::Known(_)));- caches.states.release();- assert!(matches!(- caches.states.lookup_mut(scope_program),- Lookup::Missing(prefix::PrefixStateCacheGap::MissingProgram(gap)) if gap == scope_program- ));-}--#[test]-fn partial_match_answer_completion_shares_prefix_states_between_nodes() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- let rule = add_guard_target_rule(&mut engine, guard, target);- engine.set_rule_declared_properties(rule, &[(1, false)]);- for &node in &nodes {- for kind in ElementDeclarationKind::ALL {- engine.set_element_declared_properties(node, kind, Vec::new(), Vec::new());- }- }- for (node, class) in [(nodes[1], guard), (nodes[2], target), (nodes[3], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- engine.begin_published_match_answer_completion_batch(nodes[0], false);- assert!(engine.batch_matching_traversal.as_ref().unwrap().batch.is_none());- let answer = engine.complete_published_match_answer(nodes[2], None).unwrap();- assert!(answer.cascade_winners_are_complete);- assert_eq!(engine.match_element(nodes[3]).unwrap().len(), 1);- engine.end_published_match_answer_completion_batch();-}--#[test]-fn a_cached_prefix_answer_is_returned_in_cascade_order() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- let specific = add_guard_target_rule(&mut engine, guard, target);- let general = add_target_rule(&mut engine, StyleSheetObjectID(2), target);- engine.set_rule_declared_properties(specific, &[(1, false)]);- engine.set_rule_declared_properties(general, &[(2, false)]);- for &node in &nodes {- for kind in ElementDeclarationKind::ALL {- engine.set_element_declared_properties(node, kind, Vec::new(), Vec::new());- }- }- for (node, class) in [(nodes[1], guard), (nodes[2], target), (nodes[3], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- assert!(engine.begin_cold_matching_batch(nodes[0]));- let first = engine.match_element_for_cascade(nodes[2]).unwrap();- let second = engine.match_element_for_cascade(nodes[3]).unwrap();- engine.end_cold_matching_batch();-- for matches in [first, second] {- assert_eq!(- matches.iter().map(|matched| matched.rule).collect::<Vec<_>>(),- [general, specific]- );- }- assert_eq!(engine.counters().get(Counter::PrefixAnswerCacheMisses), 1);- assert_eq!(engine.counters().get(Counter::PrefixAnswerCacheHits), 1);-}--#[test]-fn shared_retained_answer_completion_reuses_compact_cascade_state() {- for declarations_overlap in [true, false] {- let (mut engine, nodes) = nested_document();- let target = StyleAtomID(200);- for index in 0..10 {- let rule = add_target_rule(&mut engine, StyleSheetObjectID(index + 1), target);- let property = if declarations_overlap { 1 } else { (index + 1) as u16 };- engine.set_rule_declared_properties(rule, &[(property, false)]);- }- for &node in &nodes {- for kind in ElementDeclarationKind::ALL {- engine.set_element_declared_properties(node, kind, Vec::new(), Vec::new());- }- }- for node in [nodes[2], nodes[3]] {- add_feature(&mut engine, node, LocalFeatureKey::Class(target));- }- discard_transaction(&mut engine);-- let first_matches = engine.match_element(nodes[2]).unwrap();- let second_matches = engine.match_element(nodes[3]).unwrap();- assert_eq!(first_matches.len(), 10);- assert_eq!(second_matches.len(), 10);- engine.remember_retained_match_answer(nodes[2], &first_matches);- engine.remember_retained_match_answer(nodes[3], &second_matches);- let first_identity = engine.retained_match_answers.answer_identity(nodes[2]).unwrap();- assert_eq!(- engine.retained_match_answers.answer_identity(nodes[3]),- Some(first_identity)- );-- let (_, dispatch) = engine.prepare_scope_program(TreeScopeID::DOCUMENT);- let first = engine- .complete_published_match_answer(nodes[2], Some(&dispatch))- .unwrap();- let cascade_input = first.cascade_input.unwrap();- assert!(engine.shared_cascade_completion_is_profitable(first_identity));- let compaction_rows = engine.counters().get(Counter::CascadeMatchesBeforeCompaction);-- let second = engine- .complete_published_match_answer_from_cascade_input(- nodes[3],- nodes[2],- cascade_input,- first.cascade_winners_are_complete,- )- .unwrap();-- assert_eq!(second.cascade_input, Some(cascade_input));- assert!(second.matches.is_none());- engine- .retained- .published_match_answers- .push(second, &engine.retained.counters);- engine.published_match_answers.sort();- let materialized = engine.consume_published_match_answer(nodes[3]).unwrap();- assert_eq!(materialized.len(), if declarations_overlap { 1 } else { 10 });- assert_eq!(materialized[0].node, nodes[3]);- assert_eq!(- engine.counters().get(Counter::CascadeMatchesBeforeCompaction),- compaction_rows- );- let program_version = engine.program.version();- assert_eq!(- engine- .winner_groups- .token_for(WinnerGroupKey::current(nodes[2], program_version)),- engine- .winner_groups- .token_for(WinnerGroupKey::current(nodes[3], program_version))- );- }-}--#[test]-fn closure_identity_stop_declines_stale_pseudo_rows() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- let pseudo = PseudoElementTarget::new(PseudoElementKind(1));- let rule = add_guard_target_rule(&mut engine, guard, target);- let pseudo_rule = add_pseudo_target_rule(&mut engine, StyleSheetObjectID(2), target, pseudo);- engine.set_rule_declared_properties(rule, &[(1, false)]);- engine.set_rule_declared_properties(pseudo_rule, &[(1, false)]);- for &node in &nodes {- for kind in ElementDeclarationKind::ALL {- engine.set_element_declared_properties(node, kind, Vec::new(), Vec::new());- }- }- for (node, class) in [(nodes[1], guard), (nodes[2], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- engine.begin_published_match_answer_completion_batch(nodes[0], false);- let answer = engine.complete_published_match_answer(nodes[2], None).unwrap();- let cascade_input = answer.cascade_input.unwrap();- assert_eq!(engine.retained_closure_cascade_input(nodes[2]), Some(cascade_input));-- // The node's pseudo-element row goes stale while its element row stays current: the retained- // answer no longer vouches for the node's rows, so the closure completes it instead.- engine- .retained- .batch_matching_traversal- .as_mut()- .unwrap()- .answer_effects- .winners- .mark_pseudo_inventory_incomplete(nodes[2], pseudo);- assert_eq!(engine.retained_closure_cascade_input(nodes[2]), None);-}--#[test]-fn closure_identity_stop_verification_is_observer_only() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- let rule = add_guard_target_rule(&mut engine, guard, target);- engine.set_rule_declared_properties(rule, &[(1, false)]);- for &node in &nodes {- for kind in ElementDeclarationKind::ALL {- engine.set_element_declared_properties(node, kind, Vec::new(), Vec::new());- }- }- for (node, class) in [(nodes[1], guard), (nodes[2], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- engine.begin_published_match_answer_completion_batch(nodes[0], false);- let answer = engine.complete_published_match_answer(nodes[2], None).unwrap();- let cascade_input = answer.cascade_input.unwrap();- let counters_before: Vec<_> = engine.counters.iter().collect();-- let winner_groups_before = engine.winner_groups.verification_copy();- let catalog_entry_count_before = engine.match_answers.answers.live_len();- let retained_answer_column_before = engine.retained_match_answers.column.clone();- let retained_cascade_column_before = engine.retained_match_answers.cascade_input_column.clone();-- engine.verify_retained_cascade_input(nodes[2], cascade_input);-- assert_eq!(engine.counters.iter().collect::<Vec<_>>(), counters_before);-- assert!(- super::cascade::WinnerView::retained(&engine.winner_groups).node_rows_are_semantically_equal(- &winner_groups_before,- nodes[2],- engine.program.version()- )- );- assert_eq!(engine.match_answers.answers.live_len(), catalog_entry_count_before);- assert_eq!(engine.retained_match_answers.column, retained_answer_column_before);- assert_eq!(- engine.retained_match_answers.cascade_input_column,- retained_cascade_column_before- );- engine.end_published_match_answer_completion_batch();-}--#[test]-fn gated_prefix_answers_publish_complete_node_specific_winners() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 4];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- engine.record_tree_delta(nodes[1], None, Some(relations(Some(nodes[0].raw()), None, None)));- engine.record_tree_delta(- nodes[2],- None,- Some(relations(Some(nodes[1].raw()), None, Some(nodes[3].raw()))),- );- engine.record_tree_delta(- nodes[3],- None,- Some(relations(Some(nodes[1].raw()), Some(nodes[2].raw()), None)),- );- for &node in &nodes {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, StyleAtomID(100));- }- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- let rule = add_guard_target_rule(&mut engine, guard, target);- engine.set_rule_declared_properties(rule, &[(1, false)]);- engine.set_rule_gated_by_container_query(rule);- for (node, class) in [(nodes[1], guard), (nodes[2], target), (nodes[3], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- assert!(engine.begin_cold_matching_batch(nodes[0]));- let mut first_compact = None;- let mut first_complete = false;- engine- .match_element_for_purpose_with_compact_answer(- nodes[2],- true,- CompletionExactness::AllowPruning,- Some(&mut first_compact),- Some(&mut first_complete),- )- .unwrap();- let mut second_compact = None;- let mut second_complete = false;- engine- .match_element_for_purpose_with_compact_answer(- nodes[3],- true,- CompletionExactness::AllowPruning,- Some(&mut second_compact),- Some(&mut second_complete),- )- .unwrap();- // A gated rule's verdict belongs to the node, so neither sibling may reuse the other's- // compacted prefix winners. Both exact answers must still publish complete winners.- assert!(first_complete);- assert!(second_complete);- assert_eq!(engine.counters().get(Counter::PrefixAnswerCacheMisses), 2);- assert_eq!(engine.counters().get(Counter::PrefixAnswerCacheHits), 0);- engine.end_cold_matching_batch();-}--#[test]-fn an_undecided_container_verdict_has_not_moved() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 3];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().filter_map(|&raw| StyleNodeID::from_raw(raw)).collect();- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- engine.record_tree_delta(nodes[1], None, Some(relations(Some(nodes[0].raw()), None, None)));- engine.record_tree_delta(nodes[2], None, Some(relations(Some(nodes[1].raw()), None, None)));- for &node in &nodes {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, StyleAtomID(100));- }- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- // The rule holds no native conditions for the engine to read, so it cannot decide them, as for- // a container whose record it holds no view of.- let rule = add_guard_target_rule(&mut engine, guard, target);- engine.set_rule_declared_properties(rule, &[(1, false)]);- engine.set_rule_gated_by_container_query(rule);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- add_feature(&mut engine, nodes[2], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- assert!(engine.begin_cold_matching_batch(nodes[0]));- let mut compact = None;- let mut complete = false;- let matched = engine.match_element_for_purpose_with_compact_answer(- nodes[2],- true,- CompletionExactness::AllowPruning,- Some(&mut compact),- Some(&mut complete),- );- assert!(matched.is_ok());- assert!(complete);- engine.end_cold_matching_batch();-- // The verdict is published undecided, which keeps the node the host's, not as one that- // failed; a flush that still cannot decide it keeps the winners it was published with.- let undecided = vec![PublishedContainerVerdict {- rule,- pseudo: false,- held: None,- }];- assert_eq!(engine.published_container_verdicts.get(&nodes[2]), Some(&undecided));- engine.refresh_winners_whose_container_verdicts_moved(false, publication::WinnerRepublication::for_flush());- assert_eq!(engine.published_container_verdicts.get(&nodes[2]), Some(&undecided));-}--#[test]-fn retained_prefix_convergence_amortizes_missing_subtrees() {- let mut engine = StyleEngine::new();- let node_count = 2 * PREFIX_TRANSITION_CACHE_COMPLETION_BUDGET + 4;- let mut raw = vec![0_u32; node_count];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- for index in 1..nodes.len() {- engine.record_tree_delta(- nodes[index],- None,- Some(relations(Some(nodes[index - 1].raw()), None, None)),- );- }- for &node in &nodes {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, StyleAtomID(100));- }-- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_target_rule(&mut engine, guard, target);- for (node, class) in [(nodes[0], guard), (*nodes.last().unwrap(), target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- engine.force_bounded_prefix_completion = true;- assert!(engine.begin_cold_matching_batch(nodes[0]));- engine.match_element(nodes[0]).unwrap();- engine.end_cold_matching_batch();-- remove_feature(&mut engine, nodes[0], LocalFeatureKey::Class(guard));- let upqueries_before = engine.counters().get(Counter::PrefixConvergenceUpqueries);- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert!(!planned.is_empty());- assert_eq!(- engine.counters().get(Counter::PrefixConvergenceUpqueries) - upqueries_before,- PREFIX_TRANSITION_CACHE_COMPLETION_BUDGET as u64- );-- add_feature(&mut engine, nodes[0], LocalFeatureKey::Class(guard));- let upqueries_before = engine.counters().get(Counter::PrefixConvergenceUpqueries);- planned.clear();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(- engine.counters().get(Counter::PrefixConvergenceUpqueries) - upqueries_before,- 0,- "publishing the first plan completes the retained prefix workspace"- );-}--#[test]-fn equivalent_prefix_contributions_share_a_cascade_answer() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- let rule = add_guard_target_rule(&mut engine, guard, target);- engine.set_rule_declared_properties(rule, &[(1, false)]);- for (node, class) in [(nodes[1], guard), (nodes[2], target), (nodes[3], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- assert!(engine.begin_cold_matching_batch(nodes[0]));- let first = engine.match_element_for_cascade(nodes[2]).unwrap();- let first_signature = engine.match_element_signature(nodes[2]).unwrap();- let second = engine.match_element_for_cascade(nodes[3]).unwrap();- let second_signature = engine.match_element_signature(nodes[3]).unwrap();- assert_eq!(first.len(), 1);- assert_eq!(first[0].rule, rule);- assert_eq!(second.len(), 1);- assert_eq!(second[0].rule, rule);- assert_eq!(engine.counters().get(Counter::PrefixAnswerCacheMisses), 1);- assert_eq!(engine.counters().get(Counter::PrefixAnswerCacheHits), 1);- assert_eq!(first_signature, second_signature);- assert_eq!(engine.counters().get(Counter::MatchAnswerSignatures), 1);- assert_eq!(engine.counters().get(Counter::MatchAnswerSignatureReuses), 1);- engine.end_cold_matching_batch();-}--#[test]-fn element_declarations_refuse_selector_only_prefix_answer_reuse() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- let rule = add_guard_target_rule(&mut engine, guard, target);- engine.set_rule_declared_properties(rule, &[(1, false)]);- for (node, class) in [(nodes[1], guard), (nodes[2], target), (nodes[3], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- for (node, value) in [(nodes[2], SpecifiedValueID(102)), (nodes[3], SpecifiedValueID(103))] {- engine.set_element_declared_properties(- node,- ElementDeclarationKind::InlineStyle,- unwritten_declarations(&[DeclaredProperty {- property: 2,- important: false,- operator: CascadeOperator::Declared,- value,- }]),- Vec::new(),- );- }- discard_transaction(&mut engine);-- assert!(engine.begin_cold_matching_batch(nodes[0]));- engine.match_element_for_cascade(nodes[2]).unwrap();- engine.match_element_for_cascade(nodes[3]).unwrap();-- for (node, value) in [(nodes[2], SpecifiedValueID(102)), (nodes[3], SpecifiedValueID(103))] {- let key = WinnerGroupKey::current(node, engine.program.version());- assert!(- matches!(engine.current_winner_groups().winner(key, 2), Lookup::Known(winner) if winner.source == WinnerSource::Element(ElementDeclarationKind::InlineStyle) && winner.key.value == value)- );- }- assert_eq!(engine.counters().get(Counter::PrefixAnswerCacheMisses), 0);- assert_eq!(engine.counters().get(Counter::PrefixAnswerCacheHits), 0);- engine.end_cold_matching_batch();-}--#[test]-fn program_changes_discard_retained_prefix_transitions() {- let (mut engine, nodes) = nested_document();- add_guard_target_rule(&mut engine, StyleAtomID(200), StyleAtomID(201));- discard_transaction(&mut engine);-- assert!(engine.begin_cold_matching_batch(nodes[0]));- for &node in &nodes {- engine.match_element_for_cascade(node).unwrap();- }- engine.end_cold_matching_batch();-- // A program change keeps the outgoing program's prefix work interned for one invalidation- // generation, so a scope whose effective sheet set is unchanged re-adopts it without a rebuild.- let sheet = engine.add_sheet(StyleSheetObjectID(2), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);-- // A second generation in which no scope re-adopts the program discards it and its caches.- // What stays is the shared dispatch template's prefix machinery: its shape names only live- // immutable selector programs, and the selector-program sweep drops it before an identity- // it references could ever be recycled.- let another = engine.add_sheet(StyleSheetObjectID(3), CascadeOrigin::Author);- engine.attach_sheet(another, TreeScopeID::DOCUMENT);- assert_eq!(engine.scope_programs.iter().flatten().count(), 0);-- assert_eq!(engine.scope_dispatch_templates.len(), 1);-}--#[test]-fn reused_element_identity_does_not_inherit_a_prefix_transition() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_target_rule(&mut engine, guard, target);- for (node, class) in [(nodes[1], guard), (nodes[3], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- assert!(engine.begin_cold_matching_batch(nodes[0]));- for &node in &nodes {- engine.match_element(node).unwrap();- }- engine.end_cold_matching_batch();-- let old_relations = relations(Some(nodes[2].raw()), None, None);- engine.record_tree_delta(nodes[3], Some(old_relations), None);- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));-- let mut reused_raw = [0_u32; 1];- engine.allocate_style_nodes(&mut reused_raw);- assert_eq!(reused_raw[0], nodes[3].raw());- let reused = StyleNodeID::from_raw(reused_raw[0]).unwrap();- engine.record_tree_delta(reused, None, Some(old_relations));- add_feature(&mut engine, reused, LocalFeatureKey::Class(target));-- planned.clear();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![reused.raw()]);-}--#[test]-fn unobserved_inputs_do_not_seed_prefix_convergence() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_target_rule(&mut engine, guard, target);- discard_transaction(&mut engine);-- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- add_feature(&mut engine, nodes[2], LocalFeatureKey::Class(StyleAtomID(202)));- let mut transaction = engine.take_transaction();- let view = engine.transaction_fact_view_for(&mut transaction, nodes[0], &ImpactRegions::new());- assert_eq!(view.before.as_ref().unwrap().row_count(), 2);- let transition = view.prefix.unwrap();- assert_eq!(transition.roots, vec![nodes[1]]);- engine.release_transaction(transaction);-}--#[test]-fn cold_answer_verification_uses_committed_facts_with_pending_inputs() {- let (mut engine, nodes) = linear_document();- for &node in &nodes {- engine.facts.ensure_row(node);- }- let target = StyleAtomID(200);- add_target_rule(&mut engine, StyleSheetObjectID(1), target);- discard_transaction(&mut engine);-- let before = engine.exact_match_answer_for_verification(nodes[1]).unwrap();- assert!(before.is_empty());- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(target));- assert!(engine.facts.has_dirty_staging());- assert_eq!(engine.exact_match_answer_for_verification(nodes[1]).unwrap(), before);- assert!(- engine- .exact_cascade_answer_for_verification(nodes[1])- .unwrap()- .0- .is_empty()- );- assert!(engine.facts.has_dirty_staging());-- discard_transaction(&mut engine);- assert_eq!(engine.exact_match_answer_for_verification(nodes[1]).unwrap().len(), 1);-}--#[test]-fn a_batched_state_that_moves_nothing_is_no_input() {- let (mut engine, nodes) = linear_document();- discard_transaction(&mut engine);-- assert!(!engine.record_batched_state(nodes[1], StateFact::PlaceholderShown, false, false));- assert!(!engine.facts.has_dirty_staging());- assert!(engine.host.journal.is_empty());-- assert!(engine.record_batched_state(nodes[1], StateFact::PlaceholderShown, true, false));- assert!(engine.facts.has_dirty_staging());- assert!(!engine.host.journal.is_empty());-}--#[test]-fn state_input_commits_after_its_old_row_is_snapshotted() {- let (mut engine, nodes) = linear_document();- let class = StyleAtomID(200);- discard_transaction(&mut engine);-- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(class));- engine.record_input(- InputKey::State(nodes[1], StateFact::Hover),- InputValue::State(false),- InputValue::State(true),- );- assert!(engine.facts.states_of_node(nodes[1]).contains(StateFact::Hover));- let committed = engine.facts.staged_before_facts();- let committed_row = committed.row_of(nodes[1]).unwrap();- assert!(!committed.states_of(committed_row).contains(StateFact::Hover));- assert!(!committed.carries_dispatch_key(committed_row, DispatchKey::Class(class), false));-- let mut transaction = engine.take_transaction();- assert!(engine.facts.states_of_node(nodes[1]).contains(StateFact::Hover));- let view = engine.transaction_fact_view_for(&mut transaction, nodes[0], &ImpactRegions::new());- engine.transaction_fact_view = Some(view);- let before = engine.transaction_fact_view.as_ref().unwrap().before.as_ref().unwrap();- let row = before.row_of(nodes[1]).unwrap();- assert!(!before.states_of(row).contains(StateFact::Hover));- assert!(!before.carries_dispatch_key(row, DispatchKey::Class(class), false));- engine.release_transaction(transaction);-}--#[test]-fn prefix_transition_uses_arrival_region_coverage() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_target_rule(&mut engine, guard, target);- discard_transaction(&mut engine);-- let mut raw = [0_u32; 2];- engine.allocate_style_nodes(&mut raw);- let arrival = StyleNodeID::from_raw(raw[0]).unwrap();- let nested_arrival = StyleNodeID::from_raw(raw[1]).unwrap();- engine.record_tree_delta(- arrival,- None,- Some(relations(Some(nodes[2].raw()), Some(nodes[3].raw()), None)),- );- engine.record_tree_delta(nested_arrival, None, Some(relations(Some(arrival.raw()), None, None)));- add_feature(&mut engine, nested_arrival, LocalFeatureKey::Class(guard));- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));-- let transaction = engine.take_transaction();- let mut regions = ImpactRegions::with_topology(&engine.tree, nodes[0]);- regions.add(ImpactRegion::Subtree(arrival));- let transition = engine- .classify_transaction_facts(&transaction, ®ions)- .prefix- .unwrap();- assert_eq!(transition.roots, vec![nodes[1]]);- engine.release_transaction(transaction);-}--#[test]-fn prefix_convergence_skips_an_already_dirty_arrival() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_target_rule(&mut engine, guard, target);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- add_feature(&mut engine, nodes[3], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- assert!(engine.begin_cold_matching_batch(nodes[0]));- for &node in &nodes {- engine.match_element(node).unwrap();- }- engine.end_cold_matching_batch();-- let mut raw = [0_u32; 1];- engine.allocate_style_nodes(&mut raw);- let arrival = StyleNodeID::from_raw(raw[0]).unwrap();- engine.record_tree_delta(- arrival,- None,- Some(relations(Some(nodes[2].raw()), Some(nodes[3].raw()), None)),- );- add_feature(&mut engine, arrival, LocalFeatureKey::ArrivingFacts);- remove_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes[3].raw(), arrival.raw()]);- assert_eq!(engine.counters().get(Counter::PrefixConvergencePasses), 1);- assert_eq!(engine.counters().get(Counter::PrefixConvergenceNodes), 3);-}--#[test]-fn a_parent_change_has_no_prefix_fact_transition() {- let (mut engine, nodes) = nested_document();- discard_transaction(&mut engine);-- engine.record_tree_delta(- nodes[3],- Some(relations(Some(nodes[2].raw()), None, None)),- Some(relations(Some(nodes[0].raw()), Some(nodes[1].raw()), None)),- );- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(StyleAtomID(200)));- let transaction = engine.take_transaction();- assert!(- engine- .classify_transaction_facts(&transaction, &ImpactRegions::new())- .prefix- .is_none()- );- engine.release_transaction(transaction);-}--#[test]-fn an_alternate_preceding_sibling_keeps_a_candidate_out_of_the_plan() {- let (mut engine, nodes) = linear_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_sibling_target_rule(&mut engine, guard, target);- for node in [nodes[1], nodes[2]] {- add_feature(&mut engine, node, LocalFeatureKey::Class(guard));- }- add_feature(&mut engine, nodes[3], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- engine.record_tree_delta(- nodes[2],- Some(relations(- Some(nodes[0].raw()),- Some(nodes[1].raw()),- Some(nodes[3].raw()),- )),- None,- );- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert!(planned.is_empty());-}--#[test]-fn an_adjacent_replacement_that_preserves_truth_stays_out_of_the_plan() {- let (mut engine, nodes) = linear_document();- let guard = StyleAtomID(200);- let also = StyleAtomID(201);- let target = StyleAtomID(202);- add_two_class_adjacent_target_rule(&mut engine, guard, also, target);- for node in [nodes[1], nodes[2]] {- for class in [guard, also] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- }- add_feature(&mut engine, nodes[3], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- engine.record_tree_delta(- nodes[2],- Some(relations(- Some(nodes[0].raw()),- Some(nodes[1].raw()),- Some(nodes[3].raw()),- )),- None,- );- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert!(planned.is_empty());-}--#[test]-fn an_old_adjacent_chain_is_compared_with_its_replacement_chain() {- let (mut engine, nodes) = linear_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_double_guard_adjacent_target_rule(&mut engine, guard, target);- for node in [nodes[1], nodes[2]] {- add_feature(&mut engine, node, LocalFeatureKey::Class(guard));- }- add_feature(&mut engine, nodes[3], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- engine.record_tree_delta(- nodes[2],- Some(relations(- Some(nodes[0].raw()),- Some(nodes[1].raw()),- Some(nodes[3].raw()),- )),- None,- );- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes[3].raw()]);-}--/// Admitted plain an+b entries answer through the prefix automaton, whose positional truth-/// bits must stay honest across every structural mutation shape: a trailing arrival flips-/// from-end answers of untouched preceding siblings, a leading arrival flips forward parity-/// of untouched following siblings, and removals and same-parent moves shift both.-#[test]-fn positional_answers_stay_cold_equivalent_across_sequence_mutations() {- let tag_a = StyleAtomID(100);- let tag_b = StyleAtomID(101);- let class_item = StyleAtomID(200);- let class_theme = StyleAtomID(201);-- let mut engine = StyleEngine::new();- let mut raw = vec![0_u32; 11];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let root = nodes[0];- let container = nodes[1];-- let add_position_rule = |engine: &mut StyleEngine,- index: usize,- step: i32,- offset: i32,- from_end: bool,- chained: bool,- of_type: bool| {- {- let mut builder = selector::SelectorProgramBuilder::new();- let item = builder.push_feature(selector::FeatureTest::Class(class_item));- let position = builder.push(selector::SelectorOp::NthPosition(selector::NthPosition {- step,- offset,- from_end,- of_selector: None,- of_type,- }));- let selector = match chained {- true => {- let theme = builder.push_feature(selector::FeatureTest::Class(class_theme));- let ancestor = builder.push_ancestor(theme);- builder.push_compound(&[item, position, ancestor])- }- false => builder.push_compound(&[item, position]),- };- builder.push_entry(selector);- let program = engine.programs.add(builder.finish());- let sheet = engine.add_sheet(StyleSheetObjectID(1000 + index as u32), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1000 + index as u32));- engine.replace_rule_version(rule, version);- }- };- add_position_rule(&mut engine, 0, 2, 1, false, false, false); // .item:nth-child(odd)- add_position_rule(&mut engine, 1, 0, 1, true, false, false); // .item:last-child- add_position_rule(&mut engine, 2, 0, 2, true, false, false); // .item:nth-last-child(2)- add_position_rule(&mut engine, 3, 0, 2, false, true, false); // .theme .item:nth-child(2)- add_position_rule(&mut engine, 4, 2, 0, false, false, true); // .item:nth-of-type(2n)- {- // .item:empty- let mut builder = selector::SelectorProgramBuilder::new();- let item = builder.push_feature(selector::FeatureTest::Class(class_item));- let empty = builder.push(selector::SelectorOp::Empty);- let selector = builder.push_compound(&[item, empty]);- builder.push_entry(selector);- let program = engine.programs.add(builder.finish());- let sheet = engine.add_sheet(StyleSheetObjectID(1005), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1005));- engine.replace_rule_version(rule, version);- }-- let mut model: Vec<StyleNodeID> = nodes[2..8].to_vec();- engine.record_tree_delta(root, None, Some(relations(None, None, None)));- engine.record_tree_delta(container, None, Some(relations(Some(root.raw()), None, None)));- for (index, &child) in model.iter().enumerate() {- let previous = (index > 0).then(|| model[index - 1].raw());- let next = model.get(index + 1).map(|node| node.raw());- engine.record_tree_delta(child, None, Some(relations(Some(container.raw()), previous, next)));- }- // Tags alternate by identity so the of-type sequences decorrelate from the child- // sequence as mutations shuffle positions.- let record_facts = |engine: &mut StyleEngine, node: StyleNodeID, class: StyleAtomID| {- let tag = match node.raw() % 2 {- 0 => tag_a,- _ => tag_b,- };- set_atom_feature(engine, node, LocalFeatureKey::TagName, tag);- add_feature(engine, node, LocalFeatureKey::Class(class));- };- record_facts(&mut engine, root, class_theme);- record_facts(&mut engine, container, class_theme);- for &child in &model {- record_facts(&mut engine, child, class_item);- }-- let flush_and_check = |engine: &mut StyleEngine, model: &[StyleNodeID], stage: &str| {- let mut planned: Vec<StyleNodeID> = Vec::new();- let scoped = engine.take_style_transaction(root, |_, _, reactions| {- planned.extend(- reactions- .iter()- .map(|reaction| StyleNodeID::from_raw(reaction.style_node).unwrap()),- );- });- let mut live: Vec<StyleNodeID> = vec![root, container];- live.extend_from_slice(model);- let targets: &[StyleNodeID] = match scoped {- true => &planned,- false => &live,- };- for &node in targets {- let _ = engine.match_element_for_purpose(node, true);- }- let (_, dispatch) = engine.prepare_scope_program(TreeScopeID::DOCUMENT);- let mut orders: Vec<(RuleID, SelectorProgramID, u32, u32)> = (0..dispatch.entry_count())- .map(|index| dispatch.entry_at(index))- .map(|entry| (entry.rule, entry.program, entry.entry, entry.cascade_order))- .collect();- orders.sort_unstable_by_key(|&(rule, program, entry, _)| (rule, program, entry));- orders.dedup_by(|left, right| (left.0, left.1, left.2) == (right.0, right.1, right.2));- for &node in &live {- let Some(retained) = engine.retained_match_answer(node).sparse().ok().map(Arc::clone) else {- continue;- };- if !matches!(- engine.retained_match_answers.cascade_input_lookup(node),- Lookup::Known(_)- ) || !engine.match_answer_is_comparable_across_elements(node)- {- continue;- }- let materialized: Option<Vec<RuleMatch>> = retained- .iter()- .copied()- .map(|entry| {- let index = orders- .binary_search_by_key(&(entry.rule, entry.program, entry.entry), |&(rule, program, e, _)| {- (rule, program, e)- })- .ok()?;- entry.materialize(node, &engine.programs, orders[index].3)- })- .collect();- let Some(materialized) = materialized else {- continue;- };- let expected = engine.in_cascade_order(materialized, false);- let counters = engine.counters.clone();- let cold = engine.match_element_for_purpose(node, false);- engine.counters = counters;- let cold = cold.expect("cold matching must answer for a resident node");- assert_eq!(- expected, cold,- "retained answer diverged from cold matching for {node:?} after {stage}"- );- }- };- flush_and_check(&mut engine, &model, "the initial build");- let (_, dispatch) = engine.prepare_scope_program(TreeScopeID::DOCUMENT);- assert_eq!(- dispatch.prefixes().positional_tests().len(),- 6,- "every an+b test without an of-selector is admitted, stepped or not"- );-- // A trailing arrival: the previously last child keeps its facts but loses- // `:last-child`, and the previous `:nth-last-child(2)` holder loses that too.- let trailing = nodes[8];- let old_last = *model.last().unwrap();- model.push(trailing);- engine.record_tree_delta(- trailing,- None,- Some(relations(Some(container.raw()), Some(old_last.raw()), None)),- );- record_facts(&mut engine, trailing, class_item);- flush_and_check(&mut engine, &model, "a trailing arrival");-- // A middle removal: forward parity flips for every following sibling.- let removed_index = 2;- let removed = model[removed_index];- let before = model.clone();- model.remove(removed_index);- engine.record_tree_delta(- removed,- Some(relations(- Some(container.raw()),- Some(before[removed_index - 1].raw()),- Some(before[removed_index + 1].raw()),- )),- None,- );- flush_and_check(&mut engine, &model, "a middle removal");-- // A leading arrival: forward parity flips for the whole sequence while no existing- // child records any input of its own.- let leading = nodes[9];- let old_first = model[0];- model.insert(0, leading);- engine.record_tree_delta(- leading,- None,- Some(relations(Some(container.raw()), None, Some(old_first.raw()))),- );- record_facts(&mut engine, leading, class_item);- flush_and_check(&mut engine, &model, "a leading arrival");-- // A same-parent move of the first child to the end shifts every position at once.- let moved = model[0];- let before = model.clone();- model.remove(0);- model.push(moved);- let new_last_index = model.len() - 1;- engine.record_tree_delta(- moved,- Some(relations(Some(container.raw()), None, Some(before[1].raw()))),- Some(relations(- Some(container.raw()),- Some(model[new_last_index - 1].raw()),- None,- )),- );- flush_and_check(&mut engine, &model, "a same-parent move");-- // A pure fact flush for good measure: dropping `.item` changes the node's own answers- // without moving any position.- remove_feature(&mut engine, model[1], LocalFeatureKey::Class(class_item));- flush_and_check(&mut engine, &model, "a class removal");-- // A grandchild arrival flips its parent's `:empty` while the parent records no input- // of its own; the removal flips it back.- let grandchild = nodes[10];- let child = model[2];- engine.record_tree_delta(grandchild, None, Some(relations(Some(child.raw()), None, None)));- record_facts(&mut engine, grandchild, class_item);- flush_and_check(&mut engine, &model, "a grandchild arrival");- engine.record_tree_delta(grandchild, Some(relations(Some(child.raw()), None, None)), None);- flush_and_check(&mut engine, &model, "a grandchild departure");-}--/// An automaton refuses chains whose positional tests would overflow its 32 truth bits;-/// the refused entries stay with the exact evaluator and keep answering correctly.-#[test]-fn positional_test_overflow_refuses_admission_without_erasing_answers() {- const CHILDREN: usize = 40;- let tag = StyleAtomID(100);- let class_item = StyleAtomID(200);-- let mut engine = StyleEngine::new();- let mut raw = vec![0_u32; 2 + CHILDREN];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let root = nodes[0];- let container = nodes[1];- let children = &nodes[2..];-- for position in 1..=CHILDREN {- let mut builder = selector::SelectorProgramBuilder::new();- let item = builder.push_feature(selector::FeatureTest::Class(class_item));- let exact = builder.push(selector::SelectorOp::NthPosition(selector::NthPosition {- step: 0,- offset: i32::try_from(position).unwrap(),- from_end: false,- of_selector: None,- of_type: false,- }));- let selector = builder.push_compound(&[item, exact]);- builder.push_entry(selector);- let program = engine.programs.add(builder.finish());- let sheet = engine.add_sheet(StyleSheetObjectID(1000 + position as u32), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1000 + position as u32));- engine.replace_rule_version(rule, version);- }-- engine.record_tree_delta(root, None, Some(relations(None, None, None)));- engine.record_tree_delta(container, None, Some(relations(Some(root.raw()), None, None)));- for (index, &child) in children.iter().enumerate() {- let previous = (index > 0).then(|| children[index - 1].raw());- let next = children.get(index + 1).map(|node| node.raw());- engine.record_tree_delta(child, None, Some(relations(Some(container.raw()), previous, next)));- }- for &node in &nodes {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, tag);- }- for &child in children {- add_feature(&mut engine, child, LocalFeatureKey::Class(class_item));- }- discard_transaction(&mut engine);-- let (_, dispatch) = engine.prepare_scope_program(TreeScopeID::DOCUMENT);- assert_eq!(- dispatch.prefixes().positional_tests().len(),- 32,- "the automaton fills its bit space and refuses the rest"- );- for (index, &child) in children.iter().enumerate() {- let matches = engine.match_element(child).unwrap();- assert_eq!(- matches.len(),- 1,- "child {index} matches exactly its own exact-position rule"- );- }-}--#[test]-fn consecutive_departures_reconstruct_one_old_sibling_sequence() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 5];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_double_guard_adjacent_target_rule(&mut engine, guard, target);-- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- for index in 1..nodes.len() {- engine.record_tree_delta(- nodes[index],- None,- Some(relations(- Some(nodes[0].raw()),- (index > 1).then(|| nodes[index - 1].raw()),- None,- )),- );- }- for node in &nodes[1..4] {- add_feature(&mut engine, *node, LocalFeatureKey::Class(guard));- }- add_feature(&mut engine, nodes[4], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- engine.record_tree_delta(- nodes[2],- Some(relations(- Some(nodes[0].raw()),- Some(nodes[1].raw()),- Some(nodes[3].raw()),- )),- None,- );- engine.record_tree_delta(- nodes[3],- Some(relations(- Some(nodes[0].raw()),- Some(nodes[1].raw()),- Some(nodes[4].raw()),- )),- None,- );- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes[4].raw()]);-}--#[test]-fn converging_departure_routes_are_folded_before_exact_tree_evaluation() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 5];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_sibling_target_rule(&mut engine, guard, target);-- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- for index in 1..nodes.len() {- engine.record_tree_delta(- nodes[index],- None,- Some(relations(- Some(nodes[0].raw()),- (index > 1).then(|| nodes[index - 1].raw()),- None,- )),- );- }- for node in &nodes[1..4] {- add_feature(&mut engine, *node, LocalFeatureKey::Class(guard));- }- add_feature(&mut engine, nodes[4], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- engine.record_tree_delta(- nodes[1],- Some(relations(Some(nodes[0].raw()), None, Some(nodes[2].raw()))),- None,- );- engine.record_tree_delta(- nodes[2],- Some(relations(Some(nodes[0].raw()), None, Some(nodes[3].raw()))),- None,- );- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert!(planned.is_empty());-}--#[test]-fn a_departed_sibling_reaches_only_the_following_sibling_forest() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 8];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let guard = StyleAtomID(200);- let container = StyleAtomID(201);- let target = StyleAtomID(202);- add_nested_sibling_target_rule(&mut engine, StyleSheetObjectID(1), guard, container, target);-- // root -> [before -> before_target, guard, after -> after_target,- // later -> later_target]- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- for (node, previous) in [- (nodes[1], None),- (nodes[3], Some(nodes[1])),- (nodes[4], Some(nodes[3])),- (nodes[6], Some(nodes[4])),- ] {- engine.record_tree_delta(- node,- None,- Some(relations(Some(nodes[0].raw()), previous.map(StyleNodeID::raw), None)),- );- }- for (target_node, parent) in [(nodes[2], nodes[1]), (nodes[5], nodes[4]), (nodes[7], nodes[6])] {- engine.record_tree_delta(target_node, None, Some(relations(Some(parent.raw()), None, None)));- }- for node in [nodes[1], nodes[4], nodes[6]] {- add_feature(&mut engine, node, LocalFeatureKey::Class(container));- }- for node in [nodes[2], nodes[5], nodes[7]] {- add_feature(&mut engine, node, LocalFeatureKey::Class(target));- }- add_feature(&mut engine, nodes[3], LocalFeatureKey::Class(guard));- discard_transaction(&mut engine);-- engine.record_tree_delta(- nodes[3],- Some(relations(- Some(nodes[0].raw()),- Some(nodes[1].raw()),- Some(nodes[4].raw()),- )),- None,- );- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes[5].raw(), nodes[7].raw()]);-}--#[test]-fn a_stationary_general_sibling_ignores_its_new_immediate_neighbour() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 3];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<_> = raw.into_iter().map(|raw| StyleNodeID::from_raw(raw).unwrap()).collect();- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- engine.record_tree_delta(- nodes[1],- None,- Some(relations(Some(nodes[0].raw()), None, Some(nodes[2].raw()))),- );- engine.record_tree_delta(- nodes[2],- None,- Some(relations(Some(nodes[0].raw()), Some(nodes[1].raw()), None)),- );- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_sibling_target_rule(&mut engine, guard, target);- for (node, class) in [(nodes[1], guard), (nodes[2], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- // The unrelated middle node arrives immediately before the target. The guard remains in- // its preceding-sibling set, so `guard ~ target` has exactly the same answer.- let mut raw = [0_u32; 1];- engine.allocate_style_nodes(&mut raw);- let inserted = StyleNodeID::from_raw(raw[0]).unwrap();- engine.record_tree_delta(- inserted,- None,- Some(relations(- Some(nodes[0].raw()),- Some(nodes[1].raw()),- Some(nodes[2].raw()),- )),- );- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![inserted.raw()]);-}--#[test]-fn a_stationary_predecessor_is_not_a_moved_place() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 3];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<_> = raw.into_iter().map(|raw| StyleNodeID::from_raw(raw).unwrap()).collect();- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- engine.record_tree_delta(- nodes[1],- None,- Some(relations(Some(nodes[0].raw()), None, Some(nodes[2].raw()))),- );- engine.record_tree_delta(- nodes[2],- None,- Some(relations(Some(nodes[0].raw()), Some(nodes[1].raw()), None)),- );- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_sibling_target_rule(&mut engine, guard, target);- for (node, class) in [(nodes[1], guard), (nodes[2], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- let mut raw = [0_u32; 1];- engine.allocate_style_nodes(&mut raw);- let inserted = StyleNodeID::from_raw(raw[0]).unwrap();- engine.record_tree_delta(- inserted,- None,- Some(relations(- Some(nodes[0].raw()),- Some(nodes[1].raw()),- Some(nodes[2].raw()),- )),- );- set_atom_feature(&mut engine, inserted, LocalFeatureKey::TagName, StyleAtomID(100));- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![inserted.raw()]);-}--#[test]-fn an_arriving_adjacent_sibling_that_fails_its_compound_changes_nothing() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 3];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<_> = raw.into_iter().map(|raw| StyleNodeID::from_raw(raw).unwrap()).collect();- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- engine.record_tree_delta(- nodes[1],- None,- Some(relations(Some(nodes[0].raw()), None, Some(nodes[2].raw()))),- );- engine.record_tree_delta(- nodes[2],- None,- Some(relations(Some(nodes[0].raw()), Some(nodes[1].raw()), None)),- );- let guard = StyleAtomID(200);- let also = StyleAtomID(201);- let target = StyleAtomID(202);- add_two_class_adjacent_target_rule(&mut engine, guard, also, target);- // The arriving predecessor carries the class the entry dispatches on and not the one it- // also requires, so it cannot satisfy the compound and the target's answer cannot move.- add_feature(&mut engine, nodes[2], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- let mut raw = [0_u32; 1];- engine.allocate_style_nodes(&mut raw);- let inserted = StyleNodeID::from_raw(raw[0]).unwrap();- engine.record_tree_delta(- inserted,- None,- Some(relations(- Some(nodes[0].raw()),- Some(nodes[1].raw()),- Some(nodes[2].raw()),- )),- );- add_feature(&mut engine, inserted, LocalFeatureKey::Class(guard));- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![inserted.raw()]);-}--#[test]-fn an_arriving_sibling_with_an_existing_witness_restyles_only_itself() {- let (mut engine, nodes) = linear_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_sibling_target_rule(&mut engine, guard, target);- for (node, class) in [(nodes[1], guard), (nodes[3], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- let mut raw = [0_u32; 1];- engine.allocate_style_nodes(&mut raw);- let inserted = StyleNodeID::from_raw(raw[0]).unwrap();- add_feature(&mut engine, inserted, LocalFeatureKey::Class(guard));- discard_transaction(&mut engine);-- engine.record_tree_delta(- inserted,- None,- Some(relations(- Some(nodes[0].raw()),- Some(nodes[2].raw()),- Some(nodes[3].raw()),- )),- );- add_feature(&mut engine, inserted, LocalFeatureKey::ArrivingFacts);-- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![inserted.raw()]);-}--#[test]-fn exact_candidate_checks_restore_every_old_fact_in_the_transaction() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_target_rule(&mut engine, guard, target);- for node in [nodes[1], nodes[2]] {- add_feature(&mut engine, node, LocalFeatureKey::Class(guard));- }- add_feature(&mut engine, nodes[3], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- for node in [nodes[1], nodes[2]] {- remove_feature(&mut engine, node, LocalFeatureKey::Class(guard));- }- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes[3].raw()]);-}--#[test]-fn a_sibling_entry_ask_seeds_its_left_context() {- let (mut engine, nodes) = linear_document();- let tag = StyleAtomID(100);- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_sibling_target_rule(&mut engine, guard, target);- for &node in &nodes {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, tag);- }- for (node, class) in [(nodes[2], guard), (nodes[3], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- let evaluations_before = engine.counters().get(Counter::ColdNodesEvaluated);- let checks_before = engine.counters().get(Counter::CandidateChecks);- assert_eq!(engine.match_element(nodes[3]).unwrap().len(), 1);- assert_eq!(- engine.counters().get(Counter::ColdNodesEvaluated) - evaluations_before,- 1,- "a seeded left context lets the automaton answer in one pass"- );- assert_eq!(- engine.counters().get(Counter::CandidateChecks) - checks_before,- 0,- "the sibling entry is answered by the automaton, not the fallback"- );-}--#[test]-fn a_general_sibling_fact_miss_is_batched_before_matching_restarts() {- let (mut engine, nodes) = linear_document();- let tag = StyleAtomID(100);- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_sibling_target_fallback_rule(&mut engine, guard, target);- for &node in &nodes {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, tag);- }- for (node, class) in [(nodes[2], guard), (nodes[3], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- let evaluations_before = engine.counters().get(Counter::ColdNodesEvaluated);- assert_eq!(engine.match_element(nodes[3]).unwrap().len(), 1);- assert_eq!(- engine.counters().get(Counter::ColdNodesEvaluated) - evaluations_before,- 2,- "the first pass requests the sequence and the second completes"- );-}--#[test]-fn a_descendant_fact_miss_is_batched_before_matching_restarts() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 65];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let tag = StyleAtomID(100);- let anchor = StyleAtomID(200);- let absent_witness = StyleAtomID(201);- add_has_descendant_rule(&mut engine, anchor, absent_witness);-- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- for index in 1..nodes.len() {- let previous = (index > 1).then(|| nodes[index - 1].raw());- engine.record_tree_delta(- nodes[index],- None,- Some(relations(Some(nodes[0].raw()), previous, None)),- );- }- for &node in &nodes {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, tag);- }- add_feature(&mut engine, nodes[0], LocalFeatureKey::Class(anchor));- discard_transaction(&mut engine);-- let evaluations_before = engine.counters().get(Counter::ColdNodesEvaluated);- let feature_tests_before = engine.counters().get(Counter::LocalFeatureTests);- assert!(engine.match_element(nodes[0]).unwrap().is_empty());- assert_eq!(- engine.counters().get(Counter::ColdNodesEvaluated) - evaluations_before,- 5,- "doubling windows cover 64 descendants in four retries"- );- assert!(- engine.counters().get(Counter::LocalFeatureTests) - feature_tests_before < 200,- "restarts do linear rather than triangular feature-test work"- );-}--#[test]-fn a_broad_matching_batch_shares_facts_between_element_asks() {- let (mut engine, nodes) = linear_document();- let tag = StyleAtomID(100);- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_sibling_target_rule(&mut engine, guard, target);- for &node in &nodes {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, tag);- }- for (node, class) in [(nodes[2], guard), (nodes[3], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- let ordinary = engine.match_element(nodes[3]).unwrap();- assert!(engine.begin_cold_matching_batch(nodes[0]));-- assert_eq!(engine.counters().get(Counter::ColdMatchingBatchRows), 4);-- let evaluations_before = engine.counters().get(Counter::ColdNodesEvaluated);- let batched = engine.match_element(nodes[3]).unwrap();- assert_eq!(batched, ordinary);- assert_eq!(- engine.counters().get(Counter::ColdNodesEvaluated) - evaluations_before,- 1,- "the shared batch already holds the preceding sibling's facts"- );-- assert!(engine.begin_cold_matching_batch(nodes[0]));-- engine.end_cold_matching_batch();-}--#[test]-fn an_empty_shadow_tree_prepares_rules_for_its_host() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 3];- engine.allocate_style_nodes(&mut raw);- let [root, host, shadow_root] = raw.map(|raw| StyleNodeID::from_raw(raw).unwrap());- let scope = TreeScopeID(1);- engine.record_tree_delta(root, None, Some(relations(None, None, None)));- engine.record_tree_delta(host, None, Some(relations(Some(root.raw()), None, None)));- // Empty shadow trees can be registered before any element needs a non-document scope row.- engine.record_tree_delta(shadow_root, None, Some(relations(None, None, None)));- engine.set_shadow_root(host, shadow_root);- engine.set_tree_scope_root(scope, shadow_root);- for node in [root, host] {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, StyleAtomID(100));- }- let mut builder = selector::SelectorProgramBuilder::new();- let any = builder.push_feature(selector::FeatureTest::AnyElement);- let selector = builder.push(selector::SelectorOp::Host(any));- builder.push_entry(selector);- let program = engine.programs.add(builder.finish());- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, scope);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- engine.replace_rule_version(rule, version);- discard_transaction(&mut engine);- assert!(!engine.tree.has_tree_scopes());-- let local = engine.match_element(host).unwrap();- assert_eq!(local.len(), 1);- assert_eq!(local[0].rule, rule);- assert!(engine.begin_cold_matching_batch(root));- assert_eq!(engine.match_element(host).unwrap(), local);- engine.end_cold_matching_batch();-}--#[test]-fn a_broad_matching_batch_includes_shadow_scope_roots() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 4];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let [document_root, host, shadow_root, child] = nodes.as_slice() else {- unreachable!()- };- let scope = TreeScopeID(1);-- engine.record_tree_delta(*document_root, None, Some(relations(None, None, None)));- engine.record_tree_delta(*host, None, Some(relations(Some(document_root.raw()), None, None)));- engine.record_tree_delta(*shadow_root, None, Some(TreeRelations::detached(scope)));- engine.record_tree_delta(- *child,- None,- Some(TreeRelations {- parent: Some(*shadow_root),- tree_scope: scope,- ..TreeRelations::detached(scope)- }),- );- engine.set_shadow_root(*host, *shadow_root);- engine.set_tree_scope_root(scope, *shadow_root);- for node in [*document_root, *host, *child] {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, StyleAtomID(100));- }- discard_transaction(&mut engine);-- let batch = engine.materialize_cold_matching_batch(*document_root, None).unwrap();- assert_eq!(batch.row_count(), 4);- assert!(batch.row_of(*shadow_root).is_some());-}--#[test]-fn departing_scope_roots_are_removed_from_the_reverse_scope_index() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 2];- engine.allocate_style_nodes(&mut raw);- let first_root = StyleNodeID::from_raw(raw[0]).unwrap();- let second_root = StyleNodeID::from_raw(raw[1]).unwrap();- let scope = TreeScopeID(1);-- engine.record_tree_delta(first_root, None, Some(TreeRelations::detached(scope)));- engine.set_tree_scope_root(scope, first_root);- assert_eq!(engine.scope_by_root.get(first_root), Some(scope));-- engine.record_tree_delta(second_root, None, Some(TreeRelations::detached(scope)));- engine.set_tree_scope_root(scope, second_root);- assert_eq!(engine.scope_by_root.get(first_root), None);- assert_eq!(engine.scope_by_root.get(second_root), Some(scope));- discard_transaction(&mut engine);-- engine.record_tree_delta(second_root, Some(TreeRelations::detached(scope)), None);- discard_transaction(&mut engine);- assert_eq!(engine.scope_by_root.get(second_root), None);- assert_eq!(engine.scope_roots[scope.0 as usize], None);-}--#[test]-fn an_element_arriving_and_departing_in_one_transaction_is_forgotten() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 1];- engine.allocate_style_nodes(&mut raw);- let node = StyleNodeID::from_raw(raw[0]).unwrap();- let scope = TreeScopeID(1);- let class = StyleAtomID(100);-- engine.record_tree_delta(node, None, Some(TreeRelations::detached(scope)));- engine.set_tree_scope_root(scope, node);- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- engine.record_tree_delta(node, Some(TreeRelations::detached(scope)), None);- discard_transaction(&mut engine);-- assert!(engine.facts.is_empty());- assert!(matches!(- engine.facts.postings().lookup(SelectorPostingKey::Class(class)),- Lookup::KnownAbsent- ));- assert_eq!(engine.scope_by_root.get(node), None);- assert_eq!(engine.scope_roots[scope.0 as usize], None);-}--#[test]-fn independent_sibling_paths_request_their_fact_ranges_together() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 5];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let tag = StyleAtomID(100);- let outer_guard = StyleAtomID(200);- let container = StyleAtomID(201);- let inner_guard = StyleAtomID(202);- let target = StyleAtomID(203);- add_guard_sibling_target_fallback_rule(&mut engine, inner_guard, target);- add_nested_sibling_target_fallback_rule(&mut engine, StyleSheetObjectID(2), outer_guard, container, target);-- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- engine.record_tree_delta(nodes[1], None, Some(relations(Some(nodes[0].raw()), None, None)));- engine.record_tree_delta(- nodes[2],- None,- Some(relations(Some(nodes[0].raw()), Some(nodes[1].raw()), None)),- );- engine.record_tree_delta(nodes[3], None, Some(relations(Some(nodes[2].raw()), None, None)));- engine.record_tree_delta(- nodes[4],- None,- Some(relations(Some(nodes[2].raw()), Some(nodes[3].raw()), None)),- );- for &node in &nodes {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, tag);- }- for (node, class) in [- (nodes[1], outer_guard),- (nodes[2], container),- (nodes[3], inner_guard),- (nodes[4], target),- ] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- let evaluations_before = engine.counters().get(Counter::ColdNodesEvaluated);- let checks_before = engine.counters().get(Counter::CandidateChecks);- assert_eq!(engine.match_element(nodes[4]).unwrap().len(), 2);- assert_eq!(- engine.counters().get(Counter::ColdNodesEvaluated) - evaluations_before,- 2,- "both sibling sequences are requested by the first pass"- );- assert_eq!(engine.counters().get(Counter::CandidateChecks) - checks_before, 4);-}--#[test]-fn completed_cold_candidates_are_not_replayed_after_a_fact_miss() {- let (mut engine, nodes) = linear_document();- let tag = StyleAtomID(100);- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- let missing = StyleAtomID(202);- add_target_rule(&mut engine, StyleSheetObjectID(2), target);- add_two_class_target_rule(&mut engine, StyleSheetObjectID(3), target, missing);- add_guard_sibling_target_fallback_rule(&mut engine, guard, target);- for &node in &nodes {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, tag);- }- for (node, class) in [(nodes[2], guard), (nodes[3], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- let checks_before = engine.counters().get(Counter::CandidateChecks);- let matches_before = engine.counters().get(Counter::RuleMatchesEmitted);- assert_eq!(engine.match_element(nodes[3]).unwrap().len(), 2);- assert_eq!(- engine.counters().get(Counter::CandidateChecks) - checks_before,- 2,- "prefix matching settles the local rule and completed rules are skipped on retry"- );- assert_eq!(- engine.counters().get(Counter::RuleMatchesEmitted) - matches_before,- 2,- "a retained match is emitted once"- );-}--#[test]-fn a_selector_list_merges_matches_retained_across_retries() {- let (mut engine, nodes) = linear_document();- let tag = StyleAtomID(100);- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- let extra = StyleAtomID(202);- add_retrying_selector_list_rule(&mut engine, guard, target, extra);- for &node in &nodes {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, tag);- }- for (node, class) in [(nodes[2], guard), (nodes[3], target), (nodes[3], extra)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- let checks_before = engine.counters().get(Counter::CandidateChecks);- let emitted_before = engine.counters().get(Counter::RuleMatchesEmitted);- let matches = engine.match_element(nodes[3]).unwrap();- assert_eq!(matches.len(), 1);- assert_eq!(matches[0].entry, 1, "the more specific selector-list entry wins");- assert_eq!(engine.counters().get(Counter::CandidateChecks) - checks_before, 2);- assert_eq!(- engine.counters().get(Counter::RuleMatchesEmitted) - emitted_before,- 1,- "the retained lower-specificity match is updated rather than emitted again"- );-}--#[test]-fn a_positional_fact_miss_is_batched_before_matching_restarts() {- let (mut engine, nodes) = linear_document();- let tag = StyleAtomID(100);- let target = StyleAtomID(201);- add_nth_of_type_target_rule(&mut engine, target, 0, 2);- for &node in &nodes {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, tag);- }- add_feature(&mut engine, nodes[2], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- let evaluations_before = engine.counters().get(Counter::ColdNodesEvaluated);- assert_eq!(engine.match_element(nodes[2]).unwrap().len(), 1);- assert_eq!(- engine.counters().get(Counter::ColdNodesEvaluated) - evaluations_before,- 2,- "the first pass requests the sequence and the second completes"- );-}--/// A sibling request names the whole rest of a sequence, but taking all of it at once costs a-/// row per preceding sibling, which is quadratic over a long list. The window bounds what one-/// retry takes and doubles so a scan that really reads its whole sequence still converges.-#[test]-fn a_sibling_fact_request_is_taken_a_doubling_window_at_a_time() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 65];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- for index in 1..nodes.len() {- let previous = (index > 1).then(|| nodes[index - 1].raw());- engine.record_tree_delta(- nodes[index],- None,- Some(relations(Some(nodes[0].raw()), previous, None)),- );- }- discard_transaction(&mut engine);-- // Each retry resumes at the first sibling the previous window did not reach, so the batch- // grows by 8, then 16, then 32 rather than taking all 64 at the first miss.- let mut covered: Vec<StyleNodeID> = Vec::new();- let mut window = INITIAL_SIBLING_FACT_WINDOW;- for expected in [8, 24, 56] {- let first_uncovered = *nodes[1..].iter().find(|node| !covered.contains(*node)).unwrap();- let request = Incomplete::MissingSiblingFacts {- first: first_uncovered,- last_exclusive: None,- };- assert!(engine.widen_fact_coverage(&mut covered, request, &mut window).is_ok());- assert_eq!(covered.len(), expected);- }-- // A row the store cannot supply is asked for once and then reported, so a retry that cannot- // make progress ends rather than looping.- let repeated = Incomplete::MissingSiblingFacts {- first: nodes[1],- last_exclusive: None,- };- assert_eq!(- engine.widen_fact_coverage(&mut covered, repeated, &mut window),- Err(nodes[1])- );-}--#[test]-fn duplicate_fact_requests_share_one_window_per_matching_pass() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 65];- engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- for index in 1..nodes.len() {- engine.record_tree_delta(- nodes[index],- None,- Some(relations(- Some(nodes[0].raw()),- (index > 1).then(|| nodes[index - 1].raw()),- None,- )),- );- }- discard_transaction(&mut engine);-- for request in [- Incomplete::MissingFacts(nodes[1]),- Incomplete::MissingSiblingFacts {- first: nodes[1],- last_exclusive: None,- },- Incomplete::MissingDescendantFacts {- root: nodes[0],- first: nodes[1],- },- ] {- let mut covered = Vec::new();- let mut window = INITIAL_SIBLING_FACT_WINDOW;- let requests = vec![request; 64];- engine- .widen_fact_coverage_for_requests(&mut covered, &requests, &mut window)- .unwrap();- let expected = if matches!(request, Incomplete::MissingFacts(_)) {- 1- } else {- INITIAL_SIBLING_FACT_WINDOW- };- assert_eq!(covered, nodes[1..=expected]);-- assert_eq!(- engine.widen_fact_coverage_for_requests(&mut covered, &requests, &mut window),- Err(nodes[1]),- "a row requested again after materialization still reports failure to make progress"- );- }-- let mut covered = vec![nodes[0]];- let mut window = INITIAL_SIBLING_FACT_WINDOW;- let requests = [- Incomplete::MissingFacts(nodes[1]),- Incomplete::MissingSiblingFacts {- first: nodes[1],- last_exclusive: Some(nodes[9]),- },- Incomplete::MissingFacts(nodes[2]),- ];- engine- .widen_fact_coverage_for_requests(&mut covered, &requests, &mut window)- .unwrap();- assert_eq!(- covered,- nodes[..9],- "overlapping requests retain discovery order without duplicates"- );-}--fn typed_nth_of_type_document() -> (StyleEngine, Vec<StyleNodeID>) {- let (mut engine, nodes) = linear_document();- let tag = StyleAtomID(100);- let first_namespace = StyleAtomID(300);- let other_namespace = StyleAtomID(301);- let target = StyleAtomID(201);- add_nth_of_type_target_rule(&mut engine, target, 0, 2);-- for (node, namespace) in [- (nodes[1], first_namespace),- (nodes[2], other_namespace),- (nodes[3], first_namespace),- ] {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, tag);- engine.set_element_namespace(node, namespace);- }- add_feature(&mut engine, nodes[3], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);- (engine, nodes)-}--#[test]-fn another_type_leaving_does_not_route_an_of_type_position() {- let (mut engine, nodes) = typed_nth_of_type_document();- engine.record_tree_delta(- nodes[2],- Some(relations(- Some(nodes[0].raw()),- Some(nodes[1].raw()),- Some(nodes[3].raw()),- )),- None,- );-- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert!(planned.is_empty());-}--#[test]-fn the_same_type_leaving_routes_an_of_type_position() {- let (mut engine, nodes) = typed_nth_of_type_document();- engine.record_tree_delta(- nodes[1],- Some(relations(Some(nodes[0].raw()), None, Some(nodes[2].raw()))),- None,- );-- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes[3].raw()]);-}--fn insert_typed_child(engine: &mut StyleEngine, nodes: &[StyleNodeID], namespace: StyleAtomID) -> StyleNodeID {- let mut raw = [0_u32; 1];- engine.allocate_style_nodes(&mut raw);- let inserted = StyleNodeID::from_raw(raw[0]).unwrap();- engine.record_tree_delta(- inserted,- None,- Some(relations(- Some(nodes[0].raw()),- Some(nodes[2].raw()),- Some(nodes[3].raw()),- )),- );- set_atom_feature(engine, inserted, LocalFeatureKey::TagName, StyleAtomID(100));- engine.set_element_namespace(inserted, namespace);- inserted-}--#[test]-fn another_type_arriving_does_not_route_an_of_type_position() {- let (mut engine, nodes) = typed_nth_of_type_document();- let inserted = insert_typed_child(&mut engine, &nodes, StyleAtomID(301));-- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![inserted.raw()]);-}--#[test]-fn the_same_type_arriving_routes_an_of_type_position() {- let (mut engine, nodes) = typed_nth_of_type_document();- let inserted = insert_typed_child(&mut engine, &nodes, StyleAtomID(300));-- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![inserted.raw(), nodes[3].raw()]);-}--#[test]-fn an_arrival_rejects_an_unchanged_of_type_position() {- let (mut engine, nodes) = linear_document();- let tag = StyleAtomID(100);- let namespace = StyleAtomID(300);- let target = StyleAtomID(201);- add_nth_of_type_target_rule(&mut engine, target, 4, 0);- for &(node, node_tag) in &[(nodes[1], tag), (nodes[2], StyleAtomID(101)), (nodes[3], tag)] {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, node_tag);- engine.set_element_namespace(node, namespace);- }- add_feature(&mut engine, nodes[3], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- let mut raw = [0_u32; 1];- engine.allocate_style_nodes(&mut raw);- let inserted = StyleNodeID::from_raw(raw[0]).unwrap();- set_atom_feature(&mut engine, inserted, LocalFeatureKey::TagName, tag);- engine.set_element_namespace(inserted, namespace);- discard_transaction(&mut engine);-- engine.record_tree_delta(- inserted,- None,- Some(relations(- Some(nodes[0].raw()),- Some(nodes[2].raw()),- Some(nodes[3].raw()),- )),- );- add_feature(&mut engine, inserted, LocalFeatureKey::ArrivingFacts);- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![inserted.raw()]);-}--#[test]-fn an_arrival_with_no_type_facts_keeps_of_type_routing_conservative() {- let (mut engine, nodes) = typed_nth_of_type_document();- let mut raw = [0_u32; 1];- engine.allocate_style_nodes(&mut raw);- let inserted = StyleNodeID::from_raw(raw[0]).unwrap();- engine.record_tree_delta(- inserted,- None,- Some(relations(- Some(nodes[0].raw()),- Some(nodes[2].raw()),- Some(nodes[3].raw()),- )),- );-- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![inserted.raw(), nodes[3].raw()]);-}--fn nth_target_document() -> (StyleEngine, Vec<StyleNodeID>) {- let (mut engine, nodes) = linear_document();- let target = StyleAtomID(201);- add_nth_target_rule(&mut engine, target, 3, 0);- for &node in &nodes[1..] {- add_feature(&mut engine, node, LocalFeatureKey::Class(target));- }- discard_transaction(&mut engine);- (engine, nodes)-}--#[test]-fn a_departure_routes_only_an_plus_b_positions_that_can_flip() {- let (mut engine, nodes) = nth_target_document();- engine.record_tree_delta(- nodes[1],- Some(relations(Some(nodes[0].raw()), None, Some(nodes[2].raw()))),- None,- );-- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes[3].raw()]);-}--#[test]-fn an_arrival_routes_only_an_plus_b_positions_that_can_flip() {- let (mut engine, nodes) = nth_target_document();- let mut raw = [0_u32; 1];- engine.allocate_style_nodes(&mut raw);- let inserted = StyleNodeID::from_raw(raw[0]).unwrap();- engine.record_tree_delta(- inserted,- None,- Some(relations(Some(nodes[0].raw()), None, Some(nodes[1].raw()))),- );-- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![inserted.raw(), nodes[2].raw(), nodes[3].raw()]);-}--#[test]-fn cancelling_mutations_route_only_an_plus_b_positions_that_flipped() {- let (mut engine, nodes) = nth_target_document();- let mut raw = [0_u32; 1];- engine.allocate_style_nodes(&mut raw);- let inserted = StyleNodeID::from_raw(raw[0]).unwrap();- // The new head arrives while the old head departs, so every following sibling keeps- // its position. The aggregate arrival-and-departure range cannot prove that, but the- // retained before-side positions can, and only the arrival itself is planned.- engine.record_tree_delta(- inserted,- None,- Some(relations(Some(nodes[0].raw()), None, Some(nodes[1].raw()))),- );- engine.record_tree_delta(- nodes[1],- Some(relations(- Some(nodes[0].raw()),- Some(inserted.raw()),- Some(nodes[2].raw()),- )),- None,- );- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![inserted.raw()]);-}--#[test]-fn exact_planning_shares_current_relation_indexes_with_matching() {- let (mut engine, nodes) = nth_target_document();- let mut raw = [0_u32; 1];- engine.allocate_style_nodes(&mut raw);- let inserted = StyleNodeID::from_raw(raw[0]).unwrap();- engine.record_tree_delta(- inserted,- None,- Some(relations(Some(nodes[0].raw()), None, Some(nodes[1].raw()))),- );- set_atom_feature(&mut engine, inserted, LocalFeatureKey::TagName, StyleAtomID(100));-- assert!(engine.take_style_transaction(nodes[0], |_, _, _| {}));- engine.begin_adaptive_cold_matching_batch(nodes[0]);- assert_eq!(engine.match_element(nodes[2]).unwrap().len(), 1);- engine.end_cold_matching_batch();-}--#[test]-fn scoped_planning_does_not_prepare_a_complete_matching_batch() {- let (mut engine, nodes) = linear_document();- let target = StyleAtomID(201);- add_target_rule(&mut engine, StyleSheetObjectID(1), target);- discard_transaction(&mut engine);-- add_feature(&mut engine, nodes[2], LocalFeatureKey::Class(target));-- let inspected_before = engine- .counters()- .get(Counter::PreparedMatchingBatchCompletenessRowsInspected);- let cloned_before = engine.counters().get(Counter::PreparedMatchingBatchRowsCloned);- let mut planned = Vec::new();- assert!(engine.take_style_transaction(nodes[0], |_, _, reactions| {- planned.extend(reactions.iter().map(|reaction| reaction.style_node));- }));- assert_eq!(planned, vec![nodes[2].raw()]);- assert_eq!(- engine- .counters()- .get(Counter::PreparedMatchingBatchCompletenessRowsInspected),- inspected_before- );- assert_eq!(- engine.counters().get(Counter::PreparedMatchingBatchRowsCloned),- cloned_before- );-}--#[test]-fn a_prepared_fact_batch_falls_back_for_an_unprepared_node() {- let (mut engine, nodes) = nested_document();- let target = StyleAtomID(201);- add_target_rule(&mut engine, StyleSheetObjectID(1), target);- add_feature(&mut engine, nodes[2], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);-- let mut facts = StyleNodeFacts::new();- engine.facts.materialize([nodes[1]].into_iter(), &mut facts);- let batch: MatchingFactBatch = facts.into();-- let mut prepared = PreparedBatchMatchingTraversal::new(nodes[0]);- prepared.batch = Some(batch);- engine.prepared_batch_matching_traversal = Some(prepared);-- engine.begin_adaptive_cold_matching_batch(nodes[0]);- assert_eq!(engine.match_element(nodes[2]).unwrap().len(), 1);- engine.end_cold_matching_batch();-}--#[test]-fn a_published_local_reaction_names_its_semantic_provenance() {- let (mut engine, nodes) = nested_document();- let target = StyleAtomID(201);- let rule = add_target_rule(&mut engine, StyleSheetObjectID(1), target);- engine.set_rule_declared_properties(rule, &[(property_id::COLOR, false)]);- add_feature(&mut engine, nodes[2], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);- engine.begin_adaptive_cold_matching_batch(nodes[0]);- assert_eq!(engine.match_element_for_cascade(nodes[2]).unwrap().len(), 1);- engine.end_cold_matching_batch();-- remove_feature(&mut engine, nodes[2], LocalFeatureKey::Class(target));-- let direct_before = engine.counters().get(Counter::PlannedNodesWithDirectAction);- let signed_before = engine.counters().get(Counter::PlannedNodesWithSignedDelta);- let output_before = engine.counters().get(Counter::PlannedNodesWithOutputChange);- let upquery_before = engine.counters().get(Counter::PlannedNodesWithUpquery);- let unattributed_before = engine.counters().get(Counter::PlannedNodesUnattributed);- let mut planned = Vec::new();- assert!(engine.take_style_transaction(nodes[0], |_, _, reactions| {- planned.extend(reactions.iter().map(|reaction| reaction.style_node));- }));- assert_eq!(planned, vec![nodes[2].raw()]);- assert_eq!(- engine.counters().get(Counter::PlannedNodesWithDirectAction),- direct_before + 1- );- assert_eq!(- engine.counters().get(Counter::PlannedNodesWithSignedDelta),- signed_before + 1- );- assert_eq!(- engine.counters().get(Counter::PlannedNodesWithOutputChange),- output_before + 1- );- assert_eq!(engine.counters().get(Counter::PlannedNodesWithUpquery), upquery_before);- assert_eq!(- engine.counters().get(Counter::PlannedNodesUnattributed),- unattributed_before- );-}--#[test]-fn element_inputs_force_only_their_own_retained_answer_reactions() {- for declaration_input in [false, true] {- let (mut engine, nodes) = nested_document();- discard_transaction(&mut engine);- for &node in &nodes {- let matches = engine.match_element(node).unwrap();- let compact = engine.matches_for_cascade(matches.clone(), false, None);- engine.remember_retained_match_answer(node, &matches);- engine.remember_cascade_input(node, &compact);- }- if declaration_input {- engine.record_input(- InputKey::ElementDeclaration(nodes[2], ElementDeclarationKind::InlineStyle),- InputValue::ElementDeclaration(None),- InputValue::ElementDeclaration(Some(DeclarationBlockID(1))),- );- } else {- engine.record_input(- InputKey::ElementStyleInput(nodes[2]),- InputValue::ElementStyleInput {- reaction: 0,- inherited_style_groups: 0,- },- InputValue::ElementStyleInput {- reaction: transaction::STYLE_REACTION_RECOMPUTE_STYLE,- inherited_style_groups: 0,- },- );- }- let transaction = engine.take_transaction();- let selection = engine.rules_for_retained_answer_patch(&transaction).unwrap();- let mut patch = engine.prepare_retained_answer_patch(selection);- for &node in &nodes {- let outcome = engine- .patch_retained_match_answer(node, &mut patch, SelectorTruthPatch::Direct(&[]))- .unwrap();- assert_eq!(outcome.emit, node == nodes[2]);- assert!(outcome.identity_preserved);- }- engine.release_transaction(transaction);- }-}--#[test]-fn keyframes_force_only_their_named_consumers_retained_answer_reactions() {- let (mut engine, nodes) = nested_document();- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let name = StyleAtomID(101);- engine.set_element_animation_names(nodes[2], &[name]);- discard_transaction(&mut engine);- for &node in &nodes {- let matches = engine.match_element(node).unwrap();- engine.remember_retained_match_answer(node, &matches);- engine.remember_cascade_input(node, &matches);- }- engine.add_keyframes_rule(sheet, None, name);- let transaction = engine.take_transaction();- let selection = engine.rules_for_retained_answer_patch(&transaction).unwrap();- let mut patch = engine.prepare_retained_answer_patch(selection);- for &node in &nodes {- let outcome = engine- .patch_retained_match_answer(node, &mut patch, SelectorTruthPatch::Direct(&[]))- .unwrap();- assert_eq!(outcome.emit, node == nodes[2]);- assert!(outcome.identity_preserved);- }- engine.release_transaction(transaction);-}--#[test]-fn an_element_style_input_publishes_an_exact_reaction_without_matching() {- let (mut engine, nodes) = nested_document();- discard_transaction(&mut engine);- engine.begin_adaptive_cold_matching_batch(nodes[0]);- assert!(engine.match_element_for_cascade(nodes[2]).unwrap().is_empty());- engine.end_cold_matching_batch();-- engine.record_input(- InputKey::ElementStyleInput(nodes[2]),- InputValue::ElementStyleInput {- reaction: 0,- inherited_style_groups: 0,- },- InputValue::ElementStyleInput {- reaction: transaction::STYLE_REACTION_RECOMPUTE_STYLE,- inherited_style_groups: 0b101,- },- );-- let match_calls_before = engine- .counters()- .get(Counter::MatchElementCallsDuringPublishedStyleTransaction);- let upqueries_before = engine.counters().get(Counter::PlannedNodesWithUpquery);- let mut planned = Vec::new();- assert!(engine.take_style_transaction(nodes[0], |_, _, reactions| {- planned.extend(- reactions- .iter()- .map(|reaction| (reaction.style_node, reaction.inherited_style_groups)),- );- }));- assert_eq!(planned, vec![(nodes[2].raw(), 0b101)]);- assert_eq!(- engine- .counters()- .get(Counter::MatchElementCallsDuringPublishedStyleTransaction),- match_calls_before- );- assert_eq!(- engine.counters().get(Counter::PlannedNodesWithUpquery),- upqueries_before- );-}--#[test]-fn a_rootless_flush_preserves_element_style_inputs() {- let (mut engine, nodes) = nested_document();- let target = StyleAtomID(200);- let rule = add_target_rule(&mut engine, StyleSheetObjectID(1), target);- engine.set_rule_declared_properties(rule, &[(property_id::COLOR, false)]);- discard_transaction(&mut engine);-- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(target));- engine.record_input(- InputKey::ElementStyleInput(nodes[2]),- InputValue::ElementStyleInput {- reaction: 0,- inherited_style_groups: 0,- },- InputValue::ElementStyleInput {- reaction: transaction::STYLE_REACTION_RECOMPUTE_STYLE,- inherited_style_groups: 0b101,- },- );-- engine.flush_without_document_root();- assert!(!engine.has_pending_transaction());- engine.begin_adaptive_cold_matching_batch(nodes[0]);- assert_eq!(engine.match_element_for_cascade(nodes[1]).unwrap().len(), 1);- engine.end_cold_matching_batch();-- engine.record_input(- InputKey::ElementStyleInput(nodes[2]),- InputValue::ElementStyleInput {- reaction: 0,- inherited_style_groups: 0,- },- InputValue::ElementStyleInput {- reaction: transaction::STYLE_REACTION_INHERITED_STYLE,- inherited_style_groups: 0b010,- },- );- engine.flush_without_document_root();- assert!(!engine.has_pending_transaction());-- let deferred_reactions = transaction::STYLE_REACTION_RECOMPUTE_STYLE | transaction::STYLE_REACTION_INHERITED_STYLE;- let mut planned = Vec::new();- assert!(engine.take_style_transaction(nodes[0], |_, _, reactions| {- planned.extend(reactions.iter().map(|reaction| {- (- reaction.style_node,- reaction.reaction & deferred_reactions,- reaction.inherited_style_groups,- )- }));- }));- assert_eq!(planned, vec![(nodes[2].raw(), deferred_reactions, 0b111)]);-}--#[test]-fn a_rootless_flush_drops_the_prefix_relation_after_a_move() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_target_rule(&mut engine, guard, target);- for (node, class) in [(nodes[1], guard), (nodes[3], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);- engine.begin_published_match_answer_completion_batch(nodes[0], true);- assert_eq!(engine.match_element(nodes[3]).unwrap().len(), 1);- engine.end_published_match_answer_completion_batch();-- engine.record_tree_delta(- nodes[3],- Some(relations(Some(nodes[2].raw()), None, None)),- Some(relations(Some(nodes[0].raw()), None, None)),- );- engine.flush_without_document_root();-- engine.begin_published_match_answer_completion_batch(nodes[0], true);- assert!(engine.match_element(nodes[3]).unwrap().is_empty());- engine.end_published_match_answer_completion_batch();-}--#[test]-fn a_rootless_flush_drops_the_prefix_relation_its_departures_leave() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_target_rule(&mut engine, guard, target);- for (node, class) in [(nodes[1], guard), (nodes[3], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);- engine.begin_published_match_answer_completion_batch(nodes[0], true);- assert_eq!(engine.match_element(nodes[3]).unwrap().len(), 1);- engine.end_published_match_answer_completion_batch();-- // The subtree leaves while there is no style root to plan a transaction for, so no routing- // walks the relation through the departures.- for index in (1..nodes.len()).rev() {- engine.record_tree_delta(- nodes[index],- Some(relations(Some(nodes[index - 1].raw()), None, None)),- None,- );- }- engine.flush_without_document_root();-- // It comes back under new identities.- let mut raw = [0_u32; 3];- engine.allocate_style_nodes(&mut raw);- let arrived: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let mut parent = nodes[0];- for &node in &arrived {- engine.record_tree_delta(node, None, Some(relations(Some(parent.raw()), None, None)));- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, StyleAtomID(100));- parent = node;- }- for (node, class) in [(arrived[0], guard), (arrived[2], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- // The relation verifies every node it holds against the current facts.- assert!(engine.take_style_transaction_nodes(nodes[0], |_| {}));- engine.begin_published_match_answer_completion_batch(nodes[0], true);- assert_eq!(engine.match_element(arrived[2]).unwrap().len(), 1);- engine.end_published_match_answer_completion_batch();-}--#[test]-fn published_match_answers_name_transaction_program_and_identity() {- let (mut engine, nodes) = linear_document();- let target = StyleAtomID(201);- let rule = add_target_rule(&mut engine, StyleSheetObjectID(1), target);- engine.set_rule_declared_properties(rule, &[(1, false)]);- discard_transaction(&mut engine);-- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(target));-- let expected_program_version = engine.program.version();- let mut published = Vec::new();- assert!(- engine.take_style_transaction(nodes[0], |transaction_version, program_version, reactions| {- assert_eq!(transaction_version, StyleTransactionVersion(1));- assert_eq!(program_version, expected_program_version);- published.extend_from_slice(reactions);- },)- );- assert_eq!(published.len(), 1);- assert_eq!(published[0].style_node, nodes[1].raw());- assert_ne!(published[0].match_answer, 0);- assert_eq!(engine.counters().get(Counter::PublishedMatchAnswerRecords), 1);-- engine.begin_adaptive_cold_matching_batch(nodes[0]);- assert_eq!(engine.match_element_for_cascade(nodes[1]).unwrap().len(), 1);- assert_eq!(- engine.match_element_signature(nodes[1]),- Some(published[0].match_answer)- );- engine.end_cold_matching_batch();-- engine.record_input(- InputKey::ElementStyleInput(nodes[1]),- InputValue::ElementStyleInput {- reaction: 0,- inherited_style_groups: 0,- },- InputValue::ElementStyleInput {- reaction: transaction::STYLE_REACTION_RECOMPUTE_STYLE,- inherited_style_groups: 0,- },- );- let mut next_transaction_version = None;- assert!(- engine.take_style_transaction(nodes[0], |transaction_version, program_version, reactions| {- next_transaction_version = Some(transaction_version);- assert_eq!(program_version, expected_program_version);- assert_eq!(reactions.len(), 1);- assert_ne!(reactions[0].match_answer, 0);- },)- );- assert_eq!(next_transaction_version, Some(StyleTransactionVersion(2)));- assert_eq!(engine.counters().get(Counter::PublishedMatchAnswerRecords), 2);- assert_eq!(- engine- .counters()- .get(Counter::PublishedMatchAnswerRetainedIdentityComparisons),- 1- );- assert_eq!(- engine- .counters()- .get(Counter::PublishedMatchAnswerRetainedIdentityMatches),- 1- );-}--#[test]-fn a_departed_node_routes_from_retained_facts_without_being_published() {- let (mut engine, nodes) = nested_document();- discard_transaction(&mut engine);-- engine.record_input(- InputKey::ElementStyleInput(nodes[3]),- InputValue::ElementStyleInput {- reaction: 0,- inherited_style_groups: 0,- },- InputValue::ElementStyleInput {- reaction: transaction::STYLE_REACTION_RECOMPUTE_STYLE,- inherited_style_groups: 0,- },- );- engine.record_tree_delta(nodes[3], Some(relations(Some(nodes[2].raw()), None, None)), None);-- let mut published = Vec::new();- assert!(engine.take_style_transaction(nodes[0], |_, _, reactions| {- published.extend(reactions.iter().map(|reaction| reaction.style_node));- }));- assert!(!published.contains(&nodes[3].raw()));-}--#[test]-fn a_shadow_root_routes_without_being_published_as_a_style_output() {- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 2];- engine.allocate_style_nodes(&mut raw);- let host = StyleNodeID::from_raw(raw[0]).unwrap();- let shadow_root = StyleNodeID::from_raw(raw[1]).unwrap();- engine.record_tree_delta(host, None, Some(relations(None, None, None)));- engine.record_tree_delta(shadow_root, None, Some(relations(Some(host.raw()), None, None)));- engine.set_tree_scope_root(TreeScopeID(1), shadow_root);- for node in [host, shadow_root] {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, StyleAtomID(100));- }- discard_transaction(&mut engine);-- engine.record_input(- InputKey::ElementStyleInput(shadow_root),- InputValue::ElementStyleInput {- reaction: 0,- inherited_style_groups: 0,- },- InputValue::ElementStyleInput {- reaction: transaction::STYLE_REACTION_RECOMPUTE_STYLE,- inherited_style_groups: 0,- },- );-- let mut published = Vec::new();- assert!(engine.take_style_transaction(host, |_, _, reactions| {- published.extend(reactions.iter().map(|reaction| reaction.style_node));- }));- assert!(!published.contains(&shadow_root.raw()));-}--#[test]-fn exact_planning_carries_preorder_topology_into_matching() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_target_rule(&mut engine, guard, target);- for (node, class) in [(nodes[1], guard), (nodes[3], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }- discard_transaction(&mut engine);-- remove_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- for offset in 0..31 {- add_feature(- &mut engine,- nodes[0],- LocalFeatureKey::Attribute(StyleAtomID(300 + offset)),- );- }- let mut planned = Vec::new();- assert!(engine.take_style_transaction(nodes[0], |_, _, reactions| {- planned.extend(reactions.iter().map(|reaction| reaction.style_node));- }));- assert_eq!(planned, vec![nodes[3].raw()]);-- assert!(engine.begin_cold_matching_batch(nodes[0]));- assert!(engine.match_element(nodes[3]).unwrap().is_empty());- engine.end_cold_matching_batch();-}--#[test]-fn sequence_routing_rejects_children_outside_the_positional_compound() {+fn reparenting_between_equal_depth_parents_still_visits_the_subtree() {let mut engine = StyleEngine::new();- let mut raw = [0_u32; 8];+ let mut raw = [0_u32; 5];engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let guard = StyleAtomID(200);- let also = StyleAtomID(201);- let target = StyleAtomID(202);- add_guarded_nth_target_rule(&mut engine, guard, also, target);-+ let nodes: Vec<_> = raw.into_iter().map(|raw| StyleNodeID::from_raw(raw).unwrap()).collect();engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- engine.record_tree_delta(nodes[1], None, Some(relations(Some(nodes[0].raw()), None, None)));- for (container, previous, descendant) in [- (nodes[2], nodes[1], nodes[3]),- (nodes[4], nodes[2], nodes[5]),- (nodes[6], nodes[4], nodes[7]),- ] {- engine.record_tree_delta(- container,- None,- Some(relations(Some(nodes[0].raw()), Some(previous.raw()), None)),- );- engine.record_tree_delta(descendant, None, Some(relations(Some(container.raw()), None, None)));- add_feature(&mut engine, descendant, LocalFeatureKey::Class(target));- }- for class in [guard, also] {- add_feature(&mut engine, nodes[2], LocalFeatureKey::Class(class));- }- add_feature(&mut engine, nodes[4], LocalFeatureKey::Class(guard));+ engine.record_tree_delta(nodes[1], None, Some(relations(Some(raw[0]), None, Some(raw[2]))));+ engine.record_tree_delta(nodes[2], None, Some(relations(Some(raw[0]), Some(raw[1]), None)));+ engine.record_tree_delta(nodes[3], None, Some(relations(Some(raw[1]), None, None)));+ engine.record_tree_delta(nodes[4], None, Some(relations(Some(raw[3]), None, None)));discard_transaction(&mut engine);+ engine.tree.take_depth_recompute_visits();engine.record_tree_delta(- nodes[1],- Some(relations(Some(nodes[0].raw()), None, Some(nodes[2].raw()))),- None,+ nodes[3],+ Some(relations(Some(raw[1]), None, None)),+ Some(relations(Some(raw[2]), None, None)),);- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes[3].raw()]);-}--#[test]-fn an_exact_batch_filters_a_featureless_subject() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- add_guard_universal_rule(&mut engine, guard);- for node in [nodes[1], nodes[2]] {- add_feature(&mut engine, node, LocalFeatureKey::Class(guard));- }- discard_transaction(&mut engine);-- remove_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes[2].raw()]);-}--#[test]-fn ancestor_requirement_scratch_is_released_after_document_matching() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- add_guard_target_rule(&mut engine, guard, target);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- add_feature(&mut engine, nodes[3], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);+ engine.settle_tree_at_barrier();- assert_eq!(engine.match_document(nodes[0]), Ok(1));+ assert_eq!(engine.tree.take_depth_recompute_visits(), 2);+ assert_eq!(engine.element_depth(nodes[3]), 2);+ assert_eq!(engine.element_depth(nodes[4]), 3);}#[test]-fn identical_sheet_sets_share_a_scope_program() {+fn reparenting_below_a_sibling_only_staged_parent_recomputes_depth() {let mut engine = StyleEngine::new();let mut raw = [0_u32; 7];engine.allocate_style_nodes(&mut raw);- let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let [- document_root,- first_host,- second_host,- first_shadow_root,- first_child,- second_shadow_root,- second_child,- ] = nodes.as_slice()- else {- unreachable!()+ let nodes: Vec<_> = raw.into_iter().map(|raw| StyleNodeID::from_raw(raw).unwrap()).collect();+ let [root, a, b, m, p, c, n] = nodes.as_slice() else {+ unreachable!();};- let first_scope = TreeScopeID(1);- let second_scope = TreeScopeID(2);+ engine.record_tree_delta(*root, None, Some(relations(None, None, None)));+ engine.record_tree_delta(*a, None, Some(relations(Some(root.raw()), None, Some(b.raw()))));+ engine.record_tree_delta(*b, None, Some(relations(Some(root.raw()), Some(a.raw()), None)));+ engine.record_tree_delta(*m, None, Some(relations(Some(a.raw()), None, None)));+ engine.record_tree_delta(*p, None, Some(relations(Some(m.raw()), None, None)));+ engine.record_tree_delta(*c, None, Some(relations(Some(p.raw()), None, None)));+ discard_transaction(&mut engine);- engine.record_tree_delta(*document_root, None, Some(relations(None, None, None)));engine.record_tree_delta(- *first_host,+ *n,None,- Some(relations(Some(document_root.raw()), None, Some(second_host.raw()))),+ Some(relations(Some(root.raw()), Some(a.raw()), Some(b.raw()))),);engine.record_tree_delta(- *second_host,- None,- Some(relations(Some(document_root.raw()), Some(first_host.raw()), None)),- );- for (host, root, child, scope) in [- (*first_host, *first_shadow_root, *first_child, first_scope),- (*second_host, *second_shadow_root, *second_child, second_scope),- ] {- engine.record_tree_delta(root, None, Some(TreeRelations::detached(scope)));- engine.record_tree_delta(- child,- None,- Some(TreeRelations {- parent: Some(root),- tree_scope: scope,- ..TreeRelations::detached(scope)- }),- );- engine.set_shadow_root(host, root);- engine.set_tree_scope_root(scope, root);- set_atom_feature(&mut engine, child, LocalFeatureKey::TagName, StyleAtomID(100));- add_feature(&mut engine, child, LocalFeatureKey::Class(StyleAtomID(200)));- }- for node in [*document_root, *first_host, *second_host] {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, StyleAtomID(100));- }-- let program = engine- .programs- .add(test_selector_program(".target", &[("target", StyleAtomID(200))]));- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, first_scope);- engine.attach_sheet(sheet, second_scope);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- engine.replace_rule_version(rule, version);- engine.set_rule_declared_properties(rule, &[(property_id::COLOR, false)]);- discard_transaction(&mut engine);-- assert!(engine.begin_cold_matching_batch(*document_root));- let first_cached = engine.match_element_for_cascade(*first_child).unwrap();- let second_cached = engine.match_element_for_cascade(*second_child).unwrap();- assert_eq!(first_cached.len(), 1);- assert_eq!(second_cached.len(), 1);- assert_eq!(first_cached[0].tree_scope, first_scope);- assert_eq!(second_cached[0].tree_scope, second_scope);- assert_eq!(engine.counters().get(Counter::PrefixAnswerCacheMisses), 1);- assert_eq!(engine.counters().get(Counter::PrefixAnswerCacheHits), 1);- engine.end_cold_matching_batch();-- let first = engine.match_element(*first_child).unwrap();- let second = engine.match_element(*second_child).unwrap();- assert_eq!(first.len(), 1);- assert_eq!(second.len(), 1);- assert_eq!(first[0].tree_scope, first_scope);- assert_eq!(second[0].tree_scope, second_scope);- engine.remember_retained_match_answer(*first_child, &first);- assert!(matches!(engine.retained_match_answer(*first_child), Lookup::Known(_)));- let reuses_before = engine.counters().get(Counter::RetainedMatchAnswerReuses);- engine.begin_published_match_answer_completion_batch(*document_root, false);- let published = engine.complete_published_match_answer(*first_child, None).unwrap();- engine.end_published_match_answer_completion_batch();- assert_eq!(- engine.counters().get(Counter::RetainedMatchAnswerReuses),- reuses_before + 1- );- assert_eq!(published.matches.as_deref(), Some(first.as_slice()));- assert_eq!(published.cascade_input, None);- assert_eq!(engine.match_element_signature(*first_child), None);- // The batch also ranks the document scope for the ancestor spine, so three concrete- // scopes retain programs while the two shadow scopes share one immutable program.- assert_eq!(engine.scope_program_by_scope.iter().flatten().count(), 3);- let shared_program = engine.scope_program_by_scope[first_scope.0 as usize].unwrap().1;- assert_eq!(- shared_program,- engine.scope_program_by_scope[second_scope.0 as usize].unwrap().1- );- assert_eq!(- engine.scope_programs.iter().flatten().count(),- 2,- "the concrete shadow scopes retain one shared immutable program beside the document's"- );-- let second_sheet = engine.add_sheet(StyleSheetObjectID(2), CascadeOrigin::Author);- engine.attach_sheet(second_sheet, second_scope);- let second_rule = engine.append_rule(second_sheet, None, RuleKind::Style);- engine.add_routing_rule(second_rule, program);- let mut second_version = engine.program.rule_version(second_rule);- second_version.selector_program = Some(program);- engine.replace_rule_version(second_rule, second_version);- discard_transaction(&mut engine);-- assert_eq!(engine.match_element(*first_child).unwrap().len(), 1);- assert_eq!(engine.match_element(*second_child).unwrap().len(), 2);- assert_ne!(- engine.scope_program_by_scope[first_scope.0 as usize].unwrap().1,- engine.scope_program_by_scope[second_scope.0 as usize].unwrap().1- );- assert_eq!(- engine.scope_programs.iter().flatten().count(),- 3,- "a scope that changes its effective sheet set gets a distinct program"- );-}--#[test]-fn equivalent_documents_share_only_semantically_identical_dispatch_topology() {- let make_engine = |atom| {- let mut engine = StyleEngine::new();- engine.programs = selector::SelectorPrograms::shared_across_documents();- let program = engine- .programs- .add(test_selector_program(".target", &[("target", atom)]));- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::User);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- engine.replace_rule_version(rule, version);- discard_transaction(&mut engine);- engine- };- let mut first_engine = make_engine(StyleAtomID(200));- let mut second_engine = make_engine(StyleAtomID(200));- let mut different_engine = make_engine(StyleAtomID(201));- let (_, first) = first_engine.prepare_scope_program(TreeScopeID::DOCUMENT);- let (_, second) = second_engine.prepare_scope_program(TreeScopeID::DOCUMENT);- let (_, different) = different_engine.prepare_scope_program(TreeScopeID::DOCUMENT);- assert!(first.shares_topology_with(&second));- assert!(first.shares_entries_with(&second));- assert!(!first.shares_topology_with(&different));-- // The last scope to publish a template can die while an earlier scope still owns its data.- drop(second);- drop(second_engine);- let mut second_engine = make_engine(StyleAtomID(200));- let (_, second) = second_engine.prepare_scope_program(TreeScopeID::DOCUMENT);- assert!(first.shares_topology_with(&second));-- drop(first);- drop(first_engine);- second_engine.invalidate_scope_programs();- let (_, rebuilt) = second_engine.prepare_scope_program(TreeScopeID::DOCUMENT);- assert!(second.shares_topology_with(&rebuilt));- assert_eq!(rebuilt.entry_at(0).program, second.entry_at(0).program);-}--#[test]-fn equivalent_sheet_programs_share_dispatch_topology() {- let mut engine = StyleEngine::new();- let selector_program = engine- .programs- .add(test_selector_program(".target", &[("target", StyleAtomID(200))]));- let mut rules = Vec::new();- for (scope, object) in [(TreeScopeID(1), 1), (TreeScopeID(2), 2)] {- let sheet = engine.add_sheet(StyleSheetObjectID(object), CascadeOrigin::Author);- engine.attach_sheet(sheet, scope);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(selector_program);- engine.replace_rule_version(rule, version);- rules.push(rule);- }- discard_transaction(&mut engine);-- let (_, first) = engine.prepare_scope_program(TreeScopeID(1));- let (_, second) = engine.prepare_scope_program(TreeScopeID(2));- assert!(!Arc::ptr_eq(&first, &second));- assert!(first.shares_topology_with(&second));- assert!(first.shares_entries_with(&second));- assert_eq!(engine.scope_cascade_templates.len(), 1);- assert_eq!(first.entry_at(0).cascade_order, second.entry_at(0).cascade_order);- assert_eq!(first.entry_at(0).rule, rules[0]);- assert_eq!(second.entry_at(0).rule, rules[1]);-- engine.invalidate_scope_programs();- let (_, rebuilt) = engine.prepare_scope_program(TreeScopeID(1));- assert!(first.shares_topology_with(&rebuilt));- assert!(first.shares_entries_with(&rebuilt));-- let replacement_program = engine- .programs- .add(test_selector_program(".other", &[("other", StyleAtomID(201))]));- engine.selector_programs_need_sweep = true;- for rule in rules {- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(replacement_program);- engine.replace_rule_version(rule, version);- }- discard_transaction(&mut engine);- assert!(- engine- .scope_dispatch_templates- .keys()- .all(|shape| shape.0.iter().all(|&(program, _)| program != selector_program))- );-}--#[test]-fn a_scope_template_stays_while_a_program_of_its_shape_lives() {- let mut engine = StyleEngine::new();- let shared = engine- .programs- .add(test_selector_program(".target", &[("target", StyleAtomID(200))]));- let other = engine- .programs- .add(test_selector_program(".other", &[("other", StyleAtomID(201))]));- for (scope, object, program) in [- (TreeScopeID(1), 1, shared),- (TreeScopeID(2), 2, shared),- (TreeScopeID(3), 3, other),- ] {- let sheet = engine.add_sheet(StyleSheetObjectID(object), CascadeOrigin::Author);- engine.attach_sheet(sheet, scope);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- engine.replace_rule_version(rule, version);- }- discard_transaction(&mut engine);-- // The first scope builds the template; the second rebinds it into a dispatch of its own.- let (_, first) = engine.prepare_scope_program(TreeScopeID(1));- let (_, second) = engine.prepare_scope_program(TreeScopeID(2));- assert!(!Arc::ptr_eq(&first, &second));- assert!(first.shares_topology_with(&second));- engine.prepare_scope_program(TreeScopeID(3));- drop(first);- engine.invalidate_scope_program(TreeScopeID(1));- engine.invalidate_scope_program(TreeScopeID(3));- discard_transaction(&mut engine);-- let (_, rebuilt) = engine.prepare_scope_program(TreeScopeID(1));- assert!(second.shares_topology_with(&rebuilt));-}--#[test]-fn a_selector_program_sweep_drops_scope_programs_that_name_swept_programs() {- let mut engine = StyleEngine::new();- let old = engine- .programs- .add(test_selector_program(".old", &[("old", StyleAtomID(200))]));- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(old);- engine.replace_rule_version(rule, version);- discard_transaction(&mut engine);- engine.prepare_scope_program(TreeScopeID::DOCUMENT);-- // The program stays interned for one generation with no scope resolving to it.- engine.invalidate_scope_programs();- let replacement = engine- .programs- .add(test_selector_program(".new", &[("new", StyleAtomID(201))]));- engine.selector_programs_need_sweep = true;- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(replacement);- engine.replace_rule_version(rule, version);- discard_transaction(&mut engine);-- assert!(engine.scope_programs.iter().flatten().all(|program| {- program- .shapes- .dispatch- .0- .iter()- .all(|&(selector_program, _)| selector_program != old)- }));-}--#[test]-fn switching_back_to_a_sheet_set_rebinds_its_template() {- let mut engine = StyleEngine::new();- let mut sheets = Vec::new();- for (object, name) in [(1, "first"), (2, "middle"), (3, "last")] {- let program = engine.programs.add(test_selector_program(- &format!(".{name}"),- &[(name, StyleAtomID(200 + object))],- ));- let sheet = engine.add_sheet(StyleSheetObjectID(object), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- engine.replace_rule_version(rule, version);- sheets.push(sheet);- }- discard_transaction(&mut engine);- let (_, all) = engine.prepare_scope_program(TreeScopeID::DOCUMENT);- assert_eq!(all.entry_count(), 3);-- // Each transaction prepares its scopes before it is released, as a style update does.- let change_and_prepare = |engine: &mut StyleEngine, change: &dyn Fn(&mut StyleEngine)| {- change(engine);- let transaction = engine.take_transaction();- let (_, dispatch) = engine.prepare_scope_program(TreeScopeID::DOCUMENT);- engine.release_transaction(transaction);- dispatch- };- let without_middle = change_and_prepare(&mut engine, &|engine| {- engine.detach_sheet(sheets[1], TreeScopeID::DOCUMENT)- });- assert_eq!(without_middle.entry_count(), 2);-- // An unrelated program change in between removes the program of the full sheet set.- let empty = engine.add_sheet(StyleSheetObjectID(4), CascadeOrigin::Author);- change_and_prepare(&mut engine, &|engine| engine.attach_sheet(empty, TreeScopeID::DOCUMENT));-- let again = change_and_prepare(&mut engine, &|engine| {- engine.attach_sheet_before_sheet(sheets[1], Some(sheets[2]), TreeScopeID::DOCUMENT)- });- assert_eq!(again.entry_count(), 3);- assert!(all.shares_topology_with(&again));-}--#[test]-fn extending_a_scope_dispatch_skips_empty_selector_programs() {- let mut engine = StyleEngine::new();- let base = engine- .programs- .add(test_selector_program(".base", &[("base", StyleAtomID(200))]));- let suffix = engine- .programs- .add(test_selector_program(".suffix", &[("suffix", StyleAtomID(201))]));- let empty = engine.programs.add(selector::SelectorProgramBuilder::new().finish());- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let base_rule = engine.append_rule(sheet, None, RuleKind::Style);- let mut version = engine.program.rule_version(base_rule);- version.selector_program = Some(base);- engine.replace_rule_version(base_rule, version);- discard_transaction(&mut engine);- let (_, template) = engine.prepare_scope_program(TreeScopeID::DOCUMENT);- assert_eq!(template.entry_count(), 1);-- let mut suffix_rules = Vec::new();- for program in [suffix, empty] {- let rule = engine.append_rule(sheet, None, RuleKind::Style);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- engine.replace_rule_version(rule, version);- suffix_rules.push(rule);- }- discard_transaction(&mut engine);- let (_, extended) = engine.prepare_scope_program(TreeScopeID::DOCUMENT);- assert_eq!(extended.entry_count(), 2);- assert_eq!(extended.entry_at(0).rule, base_rule);- assert_eq!(extended.entry_at(1).rule, suffix_rules[0]);-}--#[test]-fn a_scope_dispatch_can_extend_a_finished_prefix_template() {- let mut programs = SelectorPrograms::new();- let base = programs.add(test_selector_program(- ".base .target",- &[("base", StyleAtomID(200)), ("target", StyleAtomID(201))],- ));- let suffix = programs.add(test_selector_program(- ".extra .target",- &[("extra", StyleAtomID(202)), ("target", StyleAtomID(201))],- ));- let rules = [RuleID(1), RuleID(2)];-- let mut template = RuleDispatch::new();- insert_scope_rule(&mut template, &programs, rules[0], base, true);- template.finish_prefixes(&mut Default::default());- let mut extended = RuleDispatch::rebind_rules_for_extension(&template, &rules[..1]);- insert_scope_rule(&mut extended, &programs, rules[1], suffix, true);- extended.finish_prefixes(&mut Default::default());-- let mut cold = RuleDispatch::new();- insert_scope_rule(&mut cold, &programs, rules[0], base, true);- insert_scope_rule(&mut cold, &programs, rules[1], suffix, true);- cold.finish_prefixes(&mut Default::default());-- assert_eq!(extended.entry_count(), cold.entry_count());- for index in 0..extended.entry_count() {- assert_eq!(extended.entry_at(index), cold.entry_at(index));- }- assert_eq!(extended.ancestor_dispatch_shape(), cold.ancestor_dispatch_shape());- assert!(extended.prefixes().contains_entry(programs.entry_id(base, 0)));- assert!(extended.prefixes().contains_entry(programs.entry_id(suffix, 0)));-- let mut facts = StyleNodeFacts::new();- facts.push_row(- StyleNodeID::element(1),- StyleAtomID(1),- StyleAtomID::NONE,- StateSet::default(),- &[StyleAtomID(201)],- &[],- );- let candidate_rules = |dispatch: &RuleDispatch| {- dispatch- .candidates_for(- &facts,- 0,- false,- ParentDispatchFacts::Unknown,- None,- CandidateEntries::All,- false,- &mut DispatchCandidateWorkspace::default(),- )- .map(|entry| entry.rule)- .collect::<Vec<_>>()- };- assert_eq!(candidate_rules(&extended), candidate_rules(&cold));-}--#[test]-fn document_author_sheets_keep_independent_shadow_scope_programs() {- let mut engine = StyleEngine::new();- let independent_scope = TreeScopeID(1);- let document_style_scope = TreeScopeID(2);- engine.set_tree_scope_uses_document_sheets(document_style_scope);- let shadow_sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(shadow_sheet, independent_scope);- engine.attach_sheet(shadow_sheet, document_style_scope);- discard_transaction(&mut engine);-- let (independent_program, _) = engine.prepare_scope_program(independent_scope);- engine.prepare_scope_program(document_style_scope);- engine.prepare_scope_program(TreeScopeID::DOCUMENT);- let document_sheet = engine.add_sheet(StyleSheetObjectID(2), CascadeOrigin::Author);- engine.attach_sheet(document_sheet, TreeScopeID::DOCUMENT);-- assert_eq!(- engine.scope_program_by_scope[independent_scope.0 as usize].unwrap().1,- independent_program+ *p,+ Some(relations(Some(m.raw()), None, None)),+ Some(relations(Some(b.raw()), None, None)),);- assert!(engine.scope_program_by_scope[document_style_scope.0 as usize].is_none());- assert!(engine.scope_program_by_scope[TreeScopeID::DOCUMENT.0 as usize].is_none());-- let user_agent_sheet = engine.add_sheet(StyleSheetObjectID(3), CascadeOrigin::UserAgent);- engine.attach_sheet(user_agent_sheet, TreeScopeID::DOCUMENT);-- assert!(engine.scope_program_by_scope[independent_scope.0 as usize].is_none());-}--#[test]-fn changing_one_scope_keeps_an_equivalent_scopes_ranked_program() {- let mut engine = StyleEngine::new();- let selector_program = engine- .programs- .add(test_selector_program(".target", &[("target", StyleAtomID(200))]));- let shared_sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(shared_sheet, TreeScopeID(1));- engine.attach_sheet(shared_sheet, TreeScopeID(2));- let rule = engine.append_rule(shared_sheet, None, RuleKind::Style);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(selector_program);- engine.replace_rule_version(rule, version);- let additional_sheet = engine.add_sheet(StyleSheetObjectID(2), CascadeOrigin::Author);- discard_transaction(&mut engine);-- let (first_program, _) = engine.prepare_scope_program(TreeScopeID(1));- let (second_program, _) = engine.prepare_scope_program(TreeScopeID(2));- assert_eq!(first_program, second_program);+ engine.settle_tree_at_barrier();- engine.attach_sheet(additional_sheet, TreeScopeID(2));- assert_eq!(- engine.scope_program_by_scope[TreeScopeID(1).0 as usize].unwrap().1,- first_program- );- assert!(engine.scope_program_by_scope[TreeScopeID(2).0 as usize].is_none());- assert_eq!(engine.scope_program(first_program).scope_count, 1);+ assert_eq!(engine.element_depth(*p), 2);+ assert_eq!(engine.element_depth(*c), 3);}#[test]-fn a_scope_ranked_while_a_rule_is_staged_ranks_the_rule_once_committed() {+fn moving_back_after_an_intermediate_tree_apply_restores_depth() {let mut engine = StyleEngine::new();- let mut raw = [0_u32; 2];+ let mut raw = [0_u32; 5];engine.allocate_style_nodes(&mut raw);- let [document_root, child] = raw.map(|raw| StyleNodeID::from_raw(raw).unwrap());- engine.record_tree_delta(document_root, None, Some(relations(None, None, None)));- engine.record_tree_delta(child, None, Some(relations(Some(document_root.raw()), None, None)));- for node in [document_root, child] {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, StyleAtomID(100));- }- add_feature(&mut engine, child, LocalFeatureKey::Class(StyleAtomID(200)));-- let program = engine- .programs- .add(test_selector_program(".target", &[("target", StyleAtomID(200))]));- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let append_matching_rule = |engine: &mut StyleEngine| {- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- engine.replace_rule_version(rule, version);- engine.set_rule_declared_properties(rule, &[(property_id::COLOR, false)]);+ let nodes: Vec<_> = raw.into_iter().map(|raw| StyleNodeID::from_raw(raw).unwrap()).collect();+ let [root, x, q1, q2, p] = nodes.as_slice() else {+ unreachable!();};- append_matching_rule(&mut engine);- discard_transaction(&mut engine);- assert_eq!(engine.match_element(child).unwrap().len(), 1);-- // Staging a rule drops the ranked program of the scope, and a read before the transaction that commits the rule- // ranks the scope again from the program without it.- append_matching_rule(&mut engine);- assert_eq!(engine.match_element(child).unwrap().len(), 1);- discard_transaction(&mut engine);-- assert_eq!(engine.match_element(child).unwrap().len(), 2);- assert_eq!(engine.match_element_with_exact_matcher(child, false).unwrap().len(), 2);-}--#[test]-fn removing_a_middle_child_splices_the_child_sequence() {- let (mut engine, nodes) = linear_document();- engine.record_tree_delta(- nodes[2],- Some(relations(- Some(nodes[0].raw()),- Some(nodes[1].raw()),- Some(nodes[3].raw()),- )),- None,- );+ engine.record_tree_delta(*root, None, Some(relations(None, None, None)));+ engine.record_tree_delta(*x, None, Some(relations(Some(root.raw()), None, Some(q1.raw()))));+ engine.record_tree_delta(*q1, None, Some(relations(Some(root.raw()), Some(x.raw()), None)));+ engine.record_tree_delta(*q2, None, Some(relations(Some(q1.raw()), None, None)));+ engine.record_tree_delta(*p, None, Some(relations(Some(x.raw()), None, None)));discard_transaction(&mut engine);- assert_eq!(- engine.tree().children(nodes[0]).collect::<Vec<_>>(),- vec![nodes[1], nodes[3]]- );- assert!(!engine.tree().is_live(nodes[2]));- assert_eq!(engine.tree().connected_element_count(), 3);-}--#[test]-fn removing_the_first_child_moves_the_parents_head() {- let (mut engine, nodes) = linear_document();engine.record_tree_delta(- nodes[1],- Some(relations(Some(nodes[0].raw()), None, Some(nodes[2].raw()))),- None,+ *p,+ Some(relations(Some(x.raw()), None, None)),+ Some(relations(Some(q2.raw()), None, None)),);- discard_transaction(&mut engine);- assert_eq!(- engine.tree().children(nodes[0]).collect::<Vec<_>>(),- vec![nodes[2], nodes[3]]+ engine.settle_tree_at_barrier();+ assert_eq!(engine.element_depth(*p), 3);++ engine.record_tree_delta(+ *p,+ Some(relations(Some(q2.raw()), None, None)),+ Some(relations(Some(x.raw()), None, None)),);+ engine.settle_tree_at_barrier();++ assert_eq!(engine.element_depth(*p), 2);}#[test]-fn moving_a_node_unlinks_it_before_relinking() {+fn an_element_that_arrives_and_departs_in_one_transaction_retires_at_its_barrier() {let (mut engine, nodes) = linear_document();- // Move the last child to the front of the same parent.- engine.record_tree_delta(- nodes[3],- Some(relations(Some(nodes[0].raw()), Some(nodes[2].raw()), None)),- Some(relations(Some(nodes[0].raw()), None, Some(nodes[1].raw()))),- );discard_transaction(&mut engine);- assert_eq!(- engine.tree().children(nodes[0]).collect::<Vec<_>>(),- vec![nodes[3], nodes[1], nodes[2]]- );-}-#[test]-fn a_single_scope_document_allocates_no_tree_scope_column() {- let (engine, _) = linear_document();- assert!(!engine.tree().has_tree_scopes());+ let mut raw = [0_u32; 1];+ engine.allocate_style_nodes(&mut raw);+ let passing = StyleNodeID::from_raw(raw[0]).unwrap();+ let arrived = relations(Some(nodes[0].raw()), Some(nodes[3].raw()), None);+ engine.record_tree_delta(passing, None, Some(arrived));+ engine.record_tree_delta(passing, Some(arrived), None);+ assert!(engine.retained.projection.relations_were_written(passing));++ let transaction = engine.take_transaction();+ assert!(!engine.tree.is_live(passing));+ assert!(!engine.retained.projection.is_live(passing));+ assert_eq!(engine.projection.next_element_sibling(nodes[3]), None);+ assert_eq!(engine.retained.projection.next_element_sibling(nodes[3]), None);+ engine.release_transaction(transaction);+ assert!(!engine.retained.projection.has_written_links());}#[test]-fn rule_activation_reaches_only_current_selector_matches() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- let rule = add_guard_target_rule(&mut engine, guard, target);- engine.set_rule_declared_properties(rule, &[(property_id::COLOR, false)]);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- for node in [nodes[0], nodes[3]] {- add_feature(&mut engine, node, LocalFeatureKey::Class(target));- }+fn a_parent_whose_children_arrive_first_has_not_departed() {+ let (mut engine, nodes) = linear_document();discard_transaction(&mut engine);- for conditions_hold in [false, true] {- engine.set_rule_conditions_hold(rule, conditions_hold);- assert_ne!(engine.program.rule_conditions_hold(rule), conditions_hold);- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(engine.program.rule_conditions_hold(rule), conditions_hold);- assert_eq!(planned, vec![nodes[3].raw()]);- }+ let mut raw = [0_u32; 2];+ engine.allocate_style_nodes(&mut raw);+ let [parent, child] = raw.map(|raw| StyleNodeID::from_raw(raw).unwrap());+ engine.record_tree_delta(child, None, Some(relations(Some(parent.raw()), None, None)));+ assert!(!engine.retained.projection.relations_were_written(parent));+ discard_transaction(&mut engine);+ assert!(engine.tree.is_live(parent));+ assert!(engine.retained.projection.is_live(parent));++ engine.record_tree_delta(+ parent,+ None,+ Some(relations(Some(nodes[0].raw()), Some(nodes[3].raw()), None)),+ );+ discard_transaction(&mut engine);+ assert_eq!(engine.projection.first_element_child(parent), Some(child));+ assert_eq!(engine.element_depth(child), 2);}#[test]-fn shared_rule_deactivation_reaches_each_adopting_shadow_scope() {+fn an_element_the_host_takes_out_of_a_tree_retires_even_where_none_was_written() {let (mut engine, nodes) = linear_document();- let target = StyleAtomID(200);- let rule = add_target_rule(&mut engine, StyleSheetObjectID(1), target);- let sheet = engine.program.rule_sheet(rule);- engine.detach_sheet(sheet, TreeScopeID::DOCUMENT);- let mut targets = Vec::new();- for (host, scope) in [(nodes[1], TreeScopeID(1)), (nodes[2], TreeScopeID(2))] {- let shadow = attach_shadow_tree(&mut engine, host, scope, 1);- engine.attach_sheet(sheet, scope);- add_feature(&mut engine, shadow[1], LocalFeatureKey::Class(target));- targets.push(shadow[1]);- }- engine.set_rule_declared_properties(rule, &[(1, false)]);discard_transaction(&mut engine);- for &node in &targets {- let exact = engine.match_element(node).unwrap();- assert_eq!(exact.len(), 1);- let compact = engine.matches_for_cascade(exact.clone(), false, Some(node));- engine.remember_retained_match_answer(node, &exact);- engine.remember_cascade_input(node, &compact);- publish_current_cascade_as_computed(&mut engine, node);- }- engine.set_rule_conditions_hold(rule, false);- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, targets.iter().map(|node| node.raw()).collect::<Vec<_>>());++ let mut raw = [0_u32; 1];+ engine.allocate_style_nodes(&mut raw);+ let node = StyleNodeID::from_raw(raw[0]).unwrap();+ engine.record_tree_delta(node, Some(relations(Some(nodes[0].raw()), None, None)), None);+ assert!(engine.retained.projection.relations_were_written(node));+ discard_transaction(&mut engine);+ assert!(!engine.tree.is_live(node));}#[test]-fn rule_deactivation_reaches_only_nodes_where_the_rule_won() {+fn a_fork_counts_its_unsettled_link_rows_apart_from_the_host() {+ use std::sync::atomic::{AtomicU32, Ordering::Relaxed};let (mut engine, nodes) = linear_document();- let target = StyleAtomID(200);- let overriding = StyleAtomID(201);- let toggled = add_target_rule(&mut engine, StyleSheetObjectID(1), target);- engine.set_rule_declared_properties(toggled, &[(1, false)]);- let winner = add_target_rule(&mut engine, StyleSheetObjectID(2), overriding);- engine.set_rule_declared_properties(winner, &[(1, true)]);- for &node in &nodes {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, StyleAtomID(100));- }- for node in [nodes[1], nodes[2]] {- add_feature(&mut engine, node, LocalFeatureKey::Class(target));- }- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(overriding));discard_transaction(&mut engine);+ let unsettled = std::sync::Arc::new(AtomicU32::new(0));+ engine.share_tree_depth(std::sync::Arc::new(AtomicU32::new(0)), unsettled.clone());- for &node in &nodes {- let exact = engine.match_element(node).unwrap();- let compact = engine.matches_for_cascade(exact.clone(), false, Some(node));- engine.remember_retained_match_answer(node, &exact);- engine.remember_cascade_input(node, &compact);- publish_current_cascade_as_computed(&mut engine, node);- }- assert_eq!(- engine.winner_groups.winning_nodes(toggled).unwrap().collect::<Vec<_>>(),- vec![nodes[2]]+ // Moving the last child under the first writes its links, its previous sibling's and its new+ // parent's.+ engine.record_tree_delta(+ nodes[3],+ Some(relations(Some(nodes[0].raw()), Some(nodes[2].raw()), None)),+ Some(relations(Some(nodes[1].raw()), None, None)),);+ assert_eq!(unsettled.load(Relaxed), 3);- engine.set_rule_conditions_hold(toggled, false);- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(- planned,- vec![nodes[2].raw()],- "removing a matching loser cannot change the retained winner"- );-}+ let mut fork = engine.clone();+ fork.detach_tree_depth_for_fork();+ discard_transaction(&mut fork);+ assert_eq!(fork.element_depth(nodes[3]), 2);+ assert_eq!(unsettled.load(Relaxed), 3, "the fork settles its own rows");-#[test]-fn local_routes_for_one_exact_entry_are_compared_once() {- let (mut engine, nodes) = nested_document();- let first = StyleAtomID(200);- let second = StyleAtomID(201);- let target = StyleAtomID(202);- let program = engine.programs.add(test_selector_program(- ".first.second .target",- &[("first", first), ("second", second), ("target", target)],- ));- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::User);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);- engine.set_rule_declared_properties(rule, &[(1, false)]);- add_feature(&mut engine, nodes[3], LocalFeatureKey::Class(target));discard_transaction(&mut engine);+ assert_eq!(engine.element_depth(nodes[3]), 2);+ assert_eq!(unsettled.load(Relaxed), 0);+}- for &node in &nodes {- let exact = engine.match_element(node).unwrap();- let compact = engine.matches_for_cascade(exact.clone(), false, Some(node));- engine.remember_retained_match_answer(node, &exact);- engine.remember_cascade_input(node, &compact);- publish_current_cascade_as_computed(&mut engine, node);- }+/// Builds `root -> [a, b, c]` through the same delta path C++ drives.+pub(super) fn linear_document() -> (StyleEngine, Vec<StyleNodeID>) {+ let mut engine = StyleEngine::new();+ let mut raw = [0_u32; 4];+ engine.allocate_style_nodes(&mut raw);+ let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();- let grouped_before = engine.counters().get(Counter::GroupedExactSelectorRoutes);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(first));- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(second));- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes[3].raw()]);- assert_eq!(- engine.counters().get(Counter::GroupedExactSelectorRoutes) - grouped_before,- 0,- "routes consolidate before late exact-entry grouping"+ engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));+ engine.record_tree_delta(nodes[1], None, Some(relations(Some(nodes[0].raw()), None, None)));+ engine.record_tree_delta(+ nodes[2],+ None,+ Some(relations(Some(nodes[0].raw()), Some(nodes[1].raw()), None)),+ );+ engine.record_tree_delta(+ nodes[3],+ None,+ Some(relations(Some(nodes[0].raw()), Some(nodes[2].raw()), None)),);+ (engine, nodes)}-#[test]-fn rule_activation_exactly_matches_a_refused_prefix_chain() {+fn nested_document() -> (StyleEngine, Vec<StyleNodeID>) {let mut engine = StyleEngine::new();- let mut raw = vec![0_u32; 36];+ let mut raw = [0_u32; 4];engine.allocate_style_nodes(&mut raw);- let nodes: Vec<_> = raw.into_iter().map(|raw| StyleNodeID::from_raw(raw).unwrap()).collect();+ let nodes: Vec<StyleNodeID> = raw.iter().map(|&raw| StyleNodeID::from_raw(raw).unwrap()).collect();engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));- for index in 1..=34 {+ for index in 1..nodes.len() {engine.record_tree_delta(nodes[index],None,- Some(relations(- Some(nodes[0].raw()),- (index > 1).then(|| nodes[index - 1].raw()),- (index < 34).then(|| nodes[index + 1].raw()),- )),+ Some(relations(Some(nodes[index - 1].raw()), None, None)),);}- engine.record_tree_delta(nodes[35], None, Some(relations(Some(nodes[34].raw()), None, None)));for &node in &nodes {set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, StyleAtomID(100));}- let target = StyleAtomID(300);- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let mut refused_rule = None;- let mut refused_program = None;- for index in 0..34 {- let guard = StyleAtomID(200 + index);- let selector_text = format!(".guard:nth-child({}) .target", index + 1);- let program = engine.programs.add(test_selector_program(- &selector_text,- &[("guard", guard), ("target", target)],- ));- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(index + 1));- engine.replace_rule_version(rule, version);- engine.set_rule_declared_properties(rule, &[(index as u16 + 1, false)]);- add_feature(&mut engine, nodes[index as usize + 1], LocalFeatureKey::Class(guard));- refused_rule = Some(rule);- refused_program = Some(program);- }- add_feature(&mut engine, nodes[35], LocalFeatureKey::Class(target));- let refused_rule = refused_rule.unwrap();- let refused_program = refused_program.unwrap();- engine.set_rule_conditions_hold(refused_rule, false);- discard_transaction(&mut engine);-- let (_, dispatch) = engine.prepare_scope_program(TreeScopeID::DOCUMENT);- assert!(!dispatch.prefixes().is_empty());- assert!(- !dispatch- .prefixes()- .contains_entry(engine.programs.entry_id(refused_program, 0))- );- assert!(engine.begin_cold_matching_batch(nodes[0]));- for &node in &nodes {- engine.match_element(node).unwrap();- }- engine.end_cold_matching_batch();- let (scope_program, _) = engine.prepare_scope_program(TreeScopeID::DOCUMENT);- let caches = engine.prefix_caches.borrow();- let states = match caches.states.lookup(scope_program) {- Lookup::Known(states) => states,- Lookup::KnownAbsent | Lookup::Missing(_) => panic!("expected retained prefix states"),- };- assert!(states.retained_matches_for(nodes[35]).is_some());- drop(caches);- let incidences = engine.materialize_current_selector_incidence(refused_program).unwrap();- assert!(incidences.iter().any(|incidence| incidence.node == nodes[35]));-- engine.set_rule_conditions_hold(refused_rule, true);- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes[35].raw()]);+ (engine, nodes)}#[test]-fn rule_activation_uses_the_fact_side_where_the_rule_contributes() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- let rule = add_guard_target_rule(&mut engine, guard, target);- for (node, class) in [(nodes[1], guard), (nodes[3], target)] {- add_feature(&mut engine, node, LocalFeatureKey::Class(class));- }+fn structural_deltas_maintain_the_relation_columns() {+ let (mut engine, nodes) = linear_document();discard_transaction(&mut engine);-- engine.set_rule_conditions_hold(rule, false);- remove_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));assert_eq!(- planned,- vec![nodes[3].raw()],- "turning the rule off tests the old selector facts"+ engine.projection.children(nodes[0]).collect::<Vec<_>>(),+ vec![nodes[1], nodes[2], nodes[3]]);-- engine.set_rule_conditions_hold(rule, true);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- planned.clear();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));assert_eq!(- planned,- vec![nodes[3].raw()],- "turning the rule on tests the new selector facts"+ engine.projection.preorder(nodes[0]).collect::<Vec<_>>(),+ vec![nodes[0], nodes[1], nodes[2], nodes[3]]);+ assert_eq!(engine.tree().connected_element_count(), 4);}#[test]-fn a_sheet_transition_reaches_only_selector_matches() {- let (mut engine, nodes) = nested_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- let rule = add_guard_target_rule(&mut engine, guard, target);- engine.set_rule_declared_properties(rule, &[(property_id::COLOR, false)]);- let sheet = engine.program.rule_sheet(rule);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(guard));- for node in [nodes[0], nodes[3]] {- add_feature(&mut engine, node, LocalFeatureKey::Class(target));- }- discard_transaction(&mut engine);-- engine.detach_sheet(sheet, TreeScopeID::DOCUMENT);- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes[3].raw()], "detaching reads the old selector facts");- assert_eq!(- engine.counters().get(Counter::SheetChangeCandidatesRejected),- 1,- "the root carries the dispatch class but does not match the ancestor requirement"- );+fn container_conditions_evaluate_over_any_record_source() {+ use super::container_queries::ContainerRecords;+ use crate::css::container_conditions::{ContainerConditionData, ContainerConditionsData};+ use crate::css::css_string::CssString;- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- planned.clear();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes[3].raw()], "attaching reads the new selector facts");- assert_eq!(engine.counters().get(Counter::SheetChangeCandidatesRejected), 2);-}--#[test]-fn any_matching_selector_list_entry_keeps_an_activation_candidate() {- let (mut engine, nodes) = nested_document();- let matching_guard = StyleAtomID(200);- let absent_guard = StyleAtomID(201);- let target = StyleAtomID(202);- let rule = add_guard_target_selector_list_rule(&mut engine, matching_guard, absent_guard, target);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(matching_guard));- for node in [nodes[0], nodes[3]] {- add_feature(&mut engine, node, LocalFeatureKey::Class(target));+ /// Records naming one element a query container by a name, which the installed state does not.+ struct NamedContainer {+ container: StyleNodeID,+ /// The name, as a raw fly string, which `_name` keeps alive.+ raw_name: usize,+ _name: ak::Utf16FlyString,}- discard_transaction(&mut engine);-- engine.set_rule_conditions_hold(rule, false);- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes[3].raw()]);-}-#[test]-fn incomplete_selector_facts_keep_an_activation_candidate() {- let (mut engine, nodes) = linear_document();- let guard = StyleAtomID(200);- let target = StyleAtomID(201);- let rule = add_guard_sibling_target_rule(&mut engine, guard, target);- add_feature(&mut engine, nodes[2], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);+ impl ContainerRecords for NamedContainer {+ fn query_row(&self, node: StyleNodeID) -> Option<tree::ContainerQueryInputs<'_>> {+ (node == self.container).then(|| tree::ContainerQueryInputs {+ style_record: 0,+ size_queries_available: true,+ names: std::slice::from_ref(&self.raw_name),+ is_size_container: false,+ is_inline_size_container: false,+ is_scroll_state_container: false,+ writing_mode: crate::css::css_enums::writing_mode::HORIZONTAL_TB,+ direction: crate::css::css_enums::direction::LTR,+ })+ }- engine.set_rule_conditions_hold(rule, false);- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes[2].raw()]);-}+ fn any_element_row(&self, _: StyleNodeID) -> Option<tree::ContainerQueryInputs<'_>> {+ None+ }-// -- Stylesheet program deltas -----------------------------------------------------------+ fn record_view(+ &self,+ _: StyleNodeID,+ _: tree::ContainerQueryInputs<'_>,+ ) -> Option<computed::StyleRecordView<'_>> {+ None+ }-fn kinds_of(transaction: &StyleTransaction) -> Vec<InputKind> {- transaction.inputs.iter().map(|input| input.key.kind()).collect()-}+ fn custom_store(+ &self,+ _: StyleNodeID,+ _: tree::ContainerQueryInputs<'_>,+ ) -> Option<Option<&crate::css::custom_properties::CustomPropertyStore>> {+ Some(None)+ }+ }-fn authoring_engine() -> (StyleEngine, SheetID, RuleID) {let mut engine = StyleEngine::new();- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);- let mut contents = engine.program().rule_version(rule);- contents.selector_program = Some(SelectorProgramID(1));- contents.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, contents);+ let mut raw = [0_u32; 3];+ engine.allocate_style_nodes(&mut raw);+ let nodes: Vec<StyleNodeID> = raw.iter().filter_map(|&raw| StyleNodeID::from_raw(raw)).collect();+ engine.record_tree_delta(nodes[0], None, Some(relations(None, None, None)));+ engine.record_tree_delta(nodes[1], None, Some(relations(Some(nodes[0].raw()), None, None)));+ engine.record_tree_delta(nodes[2], None, Some(relations(Some(nodes[1].raw()), None, None)));discard_transaction(&mut engine);- (engine, sheet, rule)++ let name: Vec<u16> = "card".encode_utf16().collect();+ let fly_name = ak::Utf16FlyString::from_utf16(&name);+ let records = NamedContainer {+ container: nodes[1],+ raw_name: fly_name.raw_identity(),+ _name: fly_name,+ };+ // `@container card`, which holds wherever a container of that name is above the subject.+ let conditions = [std::sync::Arc::new(ContainerConditionsData {+ conditions: Box::new([ContainerConditionData {+ name: Some(CssString::from_utf16(&name)),+ query: None,+ }]),+ })];+ let installed = engine+ .retained+ .container_conditions_verdict(&conditions, nodes[2], false)+ .expect("a name-only condition is decided");+ assert!(!installed.matches);+ let over_records = engine+ .retained+ .container_conditions_verdict_with(&records, &conditions, nodes[2], false)+ .expect("a name-only condition is decided");+ assert!(over_records.matches);+ // The container itself is no container of its own.+ let for_container = engine+ .retained+ .container_conditions_verdict_with(&records, &conditions, nodes[1], false)+ .expect("a name-only condition is decided");+ assert!(!for_container.matches);}#[test]-fn repeated_selector_replacement_reuses_program_and_route_storage() {+fn departing_scope_roots_are_removed_from_the_reverse_scope_index() {let mut engine = StyleEngine::new();- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let rule = engine.append_rule(sheet, None, RuleKind::Style);+ let mut raw = [0_u32; 2];+ engine.allocate_style_nodes(&mut raw);+ let first_root = StyleNodeID::from_raw(raw[0]).unwrap();+ let second_root = StyleNodeID::from_raw(raw[1]).unwrap();+ let scope = TreeScopeID(1);- for index in 0..128_u32 {- let (program, inserted) = engine- .programs- .add_with_status(test_selector_program(".target", &[("target", StyleAtomID(index + 1))]));- engine.selector_programs_need_sweep |= inserted;+ engine.record_tree_delta(first_root, None, Some(TreeRelations::detached(scope)));+ engine.set_tree_scope_root(scope, first_root);+ assert_eq!(engine.scope_by_root.get(first_root), Some(scope));- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- engine.replace_rule_version(rule, version);+ engine.record_tree_delta(second_root, None, Some(TreeRelations::detached(scope)));+ engine.set_tree_scope_root(scope, second_root);+ assert_eq!(engine.scope_by_root.get(first_root), None);+ assert_eq!(engine.scope_by_root.get(second_root), Some(scope));+ discard_transaction(&mut engine);- discard_transaction(&mut engine);- assert!(engine.programs.len() <= 2);- assert_eq!(engine.routing.len(), 1);- }+ engine.record_tree_delta(second_root, Some(TreeRelations::detached(scope)), None);+ discard_transaction(&mut engine);+ assert_eq!(engine.scope_by_root.get(second_root), None);+ assert_eq!(engine.scope_roots[scope.0 as usize], None);}#[test]-fn adding_a_live_selector_program_keeps_existing_routing() {+fn an_element_arriving_and_departing_in_one_transaction_is_forgotten() {let mut engine = StyleEngine::new();- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);-- for index in 0..2_u32 {- let rule = engine.append_rule(sheet, None, RuleKind::Style);- let (program, inserted) = engine- .programs- .add_with_status(test_selector_program(".target", &[("target", StyleAtomID(index + 1))]));- engine.selector_programs_need_sweep |= inserted;+ let mut raw = [0_u32; 1];+ engine.allocate_style_nodes(&mut raw);+ let node = StyleNodeID::from_raw(raw[0]).unwrap();+ let scope = TreeScopeID(1);+ let class = StyleAtomID(100);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- engine.replace_rule_version(rule, version);+ engine.record_tree_delta(node, None, Some(TreeRelations::detached(scope)));+ engine.set_tree_scope_root(scope, node);+ add_feature(&mut engine, node, LocalFeatureKey::Class(class));+ engine.record_tree_delta(node, Some(TreeRelations::detached(scope)), None);+ discard_transaction(&mut engine);- let routing_before_sweep = Arc::clone(&engine.routing);- discard_transaction(&mut engine);- assert!(Arc::ptr_eq(&routing_before_sweep, &engine.routing));- }- assert_eq!(engine.routing.len(), 2);+ assert!(engine.projection.facts(node).is_none());+ assert_eq!(engine.scope_by_root.get(node), None);+ assert_eq!(engine.scope_roots[scope.0 as usize], None);}#[test]-fn detachment_routing_rebuild_excludes_retired_rules() {+fn a_local_feature_written_back_within_a_transaction_ends_as_written_back() {let mut engine = StyleEngine::new();- let retained_sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- let detached_sheet = engine.add_sheet(StyleSheetObjectID(2), CascadeOrigin::Author);- engine.attach_sheet(retained_sheet, TreeScopeID::DOCUMENT);- engine.attach_sheet(detached_sheet, TreeScopeID::DOCUMENT);- let program = engine- .programs- .add(test_selector_program(".target", &[("target", StyleAtomID(1))]));-- let retained_rule = engine.append_rule(retained_sheet, None, RuleKind::Style);- let group = engine.append_rule(retained_sheet, None, RuleKind::Media);- let retired_rule = engine.append_rule(retained_sheet, Some(group), RuleKind::Style);- let detached_rule = engine.append_rule(detached_sheet, None, RuleKind::Style);- for rule in [retained_rule, retired_rule, detached_rule] {- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- engine.replace_rule_version(rule, version);- }+ let mut raw = [0_u32; 1];+ engine.allocate_style_nodes(&mut raw);+ let node = StyleNodeID::from_raw(raw[0]).unwrap();+ engine.record_tree_delta(node, None, Some(relations(None, None, None)));+ let [first, second] = [engine.intern_atom(0x15000), engine.intern_atom(0x15001)];+ engine.set_element_language(node, first);+ engine.set_element_heading_level(node, 1);+ engine.set_element_part_exposure(node, first);discard_transaction(&mut engine);- assert_eq!(engine.routing.len(), 3);- engine.remove_rule(group);- engine.detach_sheet(detached_sheet, TreeScopeID::DOCUMENT);+ // Each setter compares against what was last written, not against what the last transaction+ // committed: moving a feature away and back within one transaction leaves it where it was.+ engine.set_element_language(node, second);+ engine.set_element_heading_level(node, 2);+ engine.set_element_part_exposure(node, second);+ engine.set_element_language(node, first);+ engine.set_element_heading_level(node, 1);+ engine.set_element_part_exposure(node, first);+ let written = engine.projection.written_facts(node).unwrap();+ assert_eq!(written.language(), first);+ assert_eq!(written.heading_level(), 1);+ assert_eq!(written.part_exposure(), first);+}++#[test]+fn a_departed_node_routes_from_retained_facts_without_being_published() {+ let (mut engine, nodes) = nested_document();discard_transaction(&mut engine);- assert_eq!(engine.routing.len(), 1);- assert_eq!(- engine- .routing- .rule_of(engine.routing.routes_for(RoutingKey::Class(StyleAtomID(1)))[0]),- retained_rule+ engine.record_input(+ InputKey::ElementStyleInput(nodes[3]),+ InputValue::ElementStyleInput {+ reaction: 0,+ inherited_style_groups: 0,+ },+ InputValue::ElementStyleInput {+ reaction: input_types::STYLE_REACTION_RECOMPUTE_STYLE,+ inherited_style_groups: 0,+ },);+ engine.record_tree_delta(nodes[3], Some(relations(Some(nodes[2].raw()), None, None)), None);++ let mut published = Vec::new();+ assert!(engine.run_style_update(nodes[0], |_, reactions| {+ published.extend(reactions.iter().map(|reaction| reaction.style_node));+ }));+ assert!(!published.contains(&nodes[3].raw()));}#[test]-fn a_sheet_kept_for_reattachment_keeps_its_routes_while_detached() {+fn a_shadow_root_routes_without_being_published_as_a_style_output() {let mut engine = StyleEngine::new();- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- let program = engine- .programs- .add(test_selector_program(".target", &[("target", StyleAtomID(1))]));- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- engine.replace_rule_version(rule, version);+ let mut raw = [0_u32; 2];+ engine.allocate_style_nodes(&mut raw);+ let host = StyleNodeID::from_raw(raw[0]).unwrap();+ let shadow_root = StyleNodeID::from_raw(raw[1]).unwrap();+ engine.record_tree_delta(host, None, Some(relations(None, None, None)));+ engine.record_tree_delta(shadow_root, None, Some(relations(Some(host.raw()), None, None)));+ engine.set_tree_scope_root(TreeScopeID(1), shadow_root);+ for node in [host, shadow_root] {+ set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, StyleAtomID(100));+ }discard_transaction(&mut engine);- engine.detach_sheet(sheet, TreeScopeID::DOCUMENT);- engine.set_sheet_kept_for_reattachment(sheet, true);- discard_transaction(&mut engine);- assert_eq!(engine.routing.len(), 1);- assert!(!engine.program.rule_can_decide(rule));+ engine.record_input(+ InputKey::ElementStyleInput(shadow_root),+ InputValue::ElementStyleInput {+ reaction: 0,+ inherited_style_groups: 0,+ },+ InputValue::ElementStyleInput {+ reaction: input_types::STYLE_REACTION_RECOMPUTE_STYLE,+ inherited_style_groups: 0,+ },+ );- let routing_before_reattachment = Arc::clone(&engine.routing);- engine.set_sheet_kept_for_reattachment(sheet, false);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- discard_transaction(&mut engine);- assert!(Arc::ptr_eq(&routing_before_reattachment, &engine.routing));+ let mut published = Vec::new();+ assert!(engine.run_style_update(host, |_, reactions| {+ published.extend(reactions.iter().map(|reaction| reaction.style_node));+ }));+ assert!(!published.contains(&shadow_root.raw()));+}- engine.detach_sheet(sheet, TreeScopeID::DOCUMENT);- engine.set_sheet_kept_for_reattachment(sheet, true);- discard_transaction(&mut engine);- engine.set_sheet_kept_for_reattachment(sheet, false);+#[test]+fn removing_a_middle_child_splices_the_child_sequence() {+ let (mut engine, nodes) = linear_document();+ engine.record_tree_delta(+ nodes[2],+ Some(relations(+ Some(nodes[0].raw()),+ Some(nodes[1].raw()),+ Some(nodes[3].raw()),+ )),+ None,+ );discard_transaction(&mut engine);- assert_eq!(engine.routing.len(), 0);-}--#[test]-fn a_declaration_edit_journals_only_the_declaration_field() {- let (mut engine, _, rule) = authoring_engine();- let mut contents = engine.program().rule_version(rule);- contents.declaration_block = Some(DeclarationBlockID(2));- engine.replace_rule_version(rule, contents);- let transaction = engine.take_transaction();assert_eq!(- transaction.inputs.iter().map(|input| input.key).collect::<Vec<_>>(),- vec![InputKey::RuleField(rule, RuleField::Declarations)],- "an edit that cannot change selector truth must not name the selector"+ engine.projection.children(nodes[0]).collect::<Vec<_>>(),+ vec![nodes[1], nodes[3]]);- engine.release_transaction(transaction);+ assert!(!engine.tree().is_live(nodes[2]));+ assert_eq!(engine.tree().connected_element_count(), 3);}#[test]-fn a_selector_edit_journals_the_selector_field() {- let (mut engine, _, rule) = authoring_engine();- let mut contents = engine.program().rule_version(rule);- contents.selector_program = Some(SelectorProgramID(2));- engine.replace_rule_version(rule, contents);- assert_eq!(- engine.program().rule_version(rule).selector_program,- Some(SelectorProgramID(1))+fn removing_the_first_child_moves_the_parents_head() {+ let (mut engine, nodes) = linear_document();+ engine.record_tree_delta(+ nodes[1],+ Some(relations(Some(nodes[0].raw()), None, Some(nodes[2].raw()))),+ None,);+ discard_transaction(&mut engine);assert_eq!(- engine.current_rule_version(rule).selector_program,- Some(SelectorProgramID(2))+ engine.projection.children(nodes[0]).collect::<Vec<_>>(),+ vec![nodes[2], nodes[3]]);+}- let transaction = engine.take_transaction();- assert_eq!(- engine.program().rule_version(rule).selector_program,- Some(SelectorProgramID(2))+#[test]+fn moving_a_node_unlinks_it_before_relinking() {+ let (mut engine, nodes) = linear_document();+ // Move the last child to the front of the same parent.+ engine.record_tree_delta(+ nodes[3],+ Some(relations(Some(nodes[0].raw()), Some(nodes[2].raw()), None)),+ Some(relations(Some(nodes[0].raw()), None, Some(nodes[1].raw()))),);+ discard_transaction(&mut engine);assert_eq!(- transaction.inputs.iter().map(|input| input.key).collect::<Vec<_>>(),- vec![InputKey::RuleField(rule, RuleField::Selector)]+ engine.projection.children(nodes[0]).collect::<Vec<_>>(),+ vec![nodes[3], nodes[1], nodes[2]]);- engine.release_transaction(transaction);}-#[test]-fn rule_metadata_commits_at_the_transaction_barrier() {- let (mut engine, _, rule) = authoring_engine();- engine.set_rule_gated_by_container_query(rule);- engine.set_rule_in_a_layer(rule);-- assert!(!engine.program.rule_is_gated_by_container_query(rule));- assert!(engine.current_rule_is_gated_by_container_query(rule));- assert!(- engine- .program- .rules_in_a_layer_in_scope(TreeScopeID::DOCUMENT)- .is_empty()- );- assert!(engine.has_pending_transaction());+// -- Stylesheet program deltas ------------------------------------------------------------ let transaction = engine.take_transaction();- assert!(engine.program.rule_is_gated_by_container_query(rule));- assert_eq!(engine.program.rules_in_a_layer_in_scope(TreeScopeID::DOCUMENT), [rule]);- engine.release_transaction(transaction);+/// The selectors `text` writes.+fn test_selectors(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 container_query_gating_invalidates_committed_scope_dispatch() {+fn authoring_engine() -> (StyleEngine, SheetID, RuleID) {let mut engine = StyleEngine::new();- let program = engine- .programs- .add(test_selector_program(".target", &[("target", StyleAtomID(200))]));- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);+ let sheet = engine.add_sheet(CascadeOrigin::Author);engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- engine.replace_rule_version(rule, version);+ let mut contents = engine.rules().rule_version(rule).clone();+ contents.selectors = engine.retained.rules.start_of_selectors(sheet, &test_selectors(".c"));+ contents.declaration_block = Some(DeclarationBlockID::new(1));+ engine.replace_rule_version(rule, contents);discard_transaction(&mut engine);-- // The held program is only ever set beside its scope's retained entry, and the sheet-scoped- // sweep reaches it through that entry.- let (scope_program, _) = engine.prepare_scope_program(TreeScopeID::DOCUMENT);- assert_eq!(engine.prepared_scope_program(TreeScopeID::DOCUMENT).0, scope_program);-- engine.set_rule_gated_by_container_query(rule);-- assert!(- engine- .scope_program_by_scope- .get(TreeScopeID::DOCUMENT.0 as usize)- .copied()- .flatten()- .is_none()- );+ (engine, sheet, rule)}#[test]-fn program_inputs_lower_to_one_join_delta_shape() {- let (mut engine, sheet, rule) = authoring_engine();- let first_program = SelectorProgramID(1);- let second_program = SelectorProgramID(2);-- let mut contents = engine.program().rule_version(rule);- contents.selector_program = Some(second_program);- engine.replace_rule_version(rule, contents);- let transaction = engine.take_transaction();- let input = transaction.inputs[0].key;- assert_eq!(- transaction.program_joins_for(input),- &[ProgramJoinDelta {- input,- rule,- before_program: Some(first_program),- after_program: Some(second_program),- before_contributes: true,- after_contributes: true,- kind: ProgramJoinDeltaKind::ActiveRuleMatch,- }]- );- let selection = engine.rules_for_retained_answer_patch(&transaction).unwrap();- assert_eq!(- selection- .affected- .iter()- .map(|affected| (affected.rule, affected.program, affected.evaluate))- .collect::<Vec<_>>(),- vec![(rule, first_program, false), (rule, second_program, true)]- );- engine.release_transaction(transaction);-- let mut contents = engine.program().rule_version(rule);- contents.declaration_block = Some(DeclarationBlockID(2));+fn a_declaration_edit_changes_only_its_rule() {+ let (mut engine, _, rule) = authoring_engine();+ let mut contents = engine.rules().rule_version(rule).clone();+ contents.declaration_block = Some(DeclarationBlockID::new(2));engine.replace_rule_version(rule, contents);- let transaction = engine.take_transaction();- assert_eq!(transaction.program_joins[0].kind, ProgramJoinDeltaKind::Declarations);- assert!(- engine- .rules_for_retained_answer_patch(&transaction)- .unwrap()- .always_emit- );- engine.release_transaction(transaction);-- engine.set_rule_layer(rule, CascadeLayerID(1));- let transaction = engine.take_transaction();- assert_eq!(transaction.program_joins[0].kind, ProgramJoinDeltaKind::Priority);- assert!(- engine- .rules_for_retained_answer_patch(&transaction)- .unwrap()- .orders_shifted- );- engine.release_transaction(transaction);- engine.set_sheet_enabled(sheet, false);let transaction = engine.take_transaction();- let input = transaction.inputs[0].key;- assert_eq!(- transaction.program_joins_for(input),- &[ProgramJoinDelta {- input,- rule,- before_program: Some(second_program),- after_program: Some(second_program),- before_contributes: true,- after_contributes: false,- kind: ProgramJoinDeltaKind::ActiveRuleMatch,- }]- );- let selection = engine.rules_for_retained_answer_patch(&transaction).unwrap();- assert_eq!(selection.affected.len(), 1);- assert_eq!(selection.affected[0].program, second_program);- assert!(selection.affected[0].evaluate);+ assert!(transaction.has_no_element_inputs());+ assert_eq!(transaction.rule_changes.rules, vec![rule]);+ assert!(transaction.rule_changes.sheets.is_empty());+ assert!(transaction.rule_changes.reordered_scopes.is_empty());engine.release_transaction(transaction);}#[test]-fn leaving_a_slot_refuses_document_scope_retained_answer_patching() {- for _ in 0..64 {- let (mut engine, nodes) = linear_document();- let unassigned = relations(Some(nodes[0].raw()), None, Some(nodes[2].raw()));- let mut assigned = unassigned;- assigned.assigned_slot = Some(nodes[3]);- engine.record_tree_delta(nodes[1], Some(unassigned), Some(assigned));- discard_transaction(&mut engine);+fn a_selector_edit_changes_its_rule() {+ let (mut engine, sheet, rule) = authoring_engine();+ let first = engine.rules().rule_version(rule).selectors;+ let second = engine.retained.rules.start_of_selectors(sheet, &test_selectors(".d"));+ assert_ne!(first, second);+ let mut contents = engine.rules().rule_version(rule).clone();+ contents.selectors = second;+ engine.replace_rule_version(rule, contents);+ assert_eq!(engine.rules().rule_version(rule).selectors, first);+ assert_eq!(engine.current_rule_version(rule).selectors, second);- engine.record_tree_delta(nodes[1], Some(assigned), Some(unassigned));- let transaction = engine.take_transaction();- assert!(- engine.rules_for_retained_answer_patch(&transaction).is_none(),- "a default-slot to missing-slot move needs cross-scope exact matching"- );- engine.release_transaction(transaction);- }+ let transaction = engine.take_transaction();+ assert_eq!(engine.rules().rule_version(rule).selectors, second);+ assert_eq!(transaction.rule_changes.rules, vec![rule]);+ engine.release_transaction(transaction);}#[test]-fn rewriting_a_rule_to_its_current_contents_journals_nothing() {+fn rule_metadata_commits_at_the_transaction_barrier() {let (mut engine, _, rule) = authoring_engine();- let contents = engine.program().rule_version(rule);- engine.replace_rule_version(rule, contents);+ engine.set_rule_gated_by_container_query(rule);+ engine.set_rule_in_a_layer(rule);++ assert!(!engine.rules.rule_is_gated_by_container_query(rule));+ assert!(engine.current_rule_is_gated_by_container_query(rule));+ assert!(engine.has_pending_transaction());let transaction = engine.take_transaction();- assert!(transaction.is_empty());+ assert!(engine.rules.rule_is_gated_by_container_query(rule));engine.release_transaction(transaction);}#[test]fn reordering_a_sheet_is_a_cascade_change_not_a_selector_change() {let mut engine = StyleEngine::new();- let first = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- let second = engine.add_sheet(StyleSheetObjectID(2), CascadeOrigin::Author);+ let first = engine.add_sheet(CascadeOrigin::Author);+ let second = engine.add_sheet(CascadeOrigin::Author);engine.attach_sheet(first, TreeScopeID::DOCUMENT);engine.attach_sheet(second, TreeScopeID::DOCUMENT);let rule = engine.append_rule(first, None, RuleKind::Style);@@ -10814,15 +788,20 @@ fn reordering_a_sheet_is_a_cascade_change_not_a_selector_change() {engine.detach_sheet(first, TreeScopeID::DOCUMENT);engine.attach_sheet_before_sheet(first, Some(second), TreeScopeID::DOCUMENT);let transaction = engine.take_transaction();- assert_eq!(- transaction.inputs.iter().map(|input| input.key).collect::<Vec<_>>(),- vec![InputKey::CascadeTopology(TopologyAxis::SheetOrder(- TreeScopeID::DOCUMENT- ))]+ assert!(+ transaction.rule_changes.is_empty(),+ "a sheet put back where it was moves nothing");- assert_eq!(- engine.program().rule_version(rule).selector_program,- None,+ engine.release_transaction(transaction);++ engine.detach_sheet(first, TreeScopeID::DOCUMENT);+ engine.attach_sheet_before_sheet(first, None, TreeScopeID::DOCUMENT);+ let transaction = engine.take_transaction();+ assert!(transaction.rule_changes.rules.is_empty());+ assert!(transaction.rule_changes.sheets.is_empty());+ assert_eq!(transaction.rule_changes.reordered_scopes, vec![TreeScopeID::DOCUMENT]);+ assert!(+ engine.rules().rule_version(rule).selectors == SheetListStart::NONE,"the sheet's rules were not rewritten");engine.release_transaction(transaction);@@ -10831,107 +810,46 @@ fn reordering_a_sheet_is_a_cascade_change_not_a_selector_change() {#[test]fn sheet_attachment_commits_at_the_transaction_barrier() {let mut engine = StyleEngine::new();- let first = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- let second = engine.add_sheet(StyleSheetObjectID(2), CascadeOrigin::Author);+ let first = engine.add_sheet(CascadeOrigin::Author);+ let second = engine.add_sheet(CascadeOrigin::Author);engine.attach_sheet(first, TreeScopeID::DOCUMENT);discard_transaction(&mut engine);engine.attach_sheet_before_sheet(second, Some(first), TreeScopeID::DOCUMENT);- assert_eq!(engine.program.sheets_in_scope(TreeScopeID::DOCUMENT), vec![first]);+ assert_eq!(engine.rules.sheets_in_scope(TreeScopeID::DOCUMENT), vec![first]);assert_eq!(engine.current_sheets_in_scope(TreeScopeID::DOCUMENT),vec![second, first]);let transaction = engine.take_transaction();- assert_eq!(- engine.program.sheets_in_scope(TreeScopeID::DOCUMENT),- vec![second, first]- );- engine.release_transaction(transaction);-}--#[test]-fn sheet_order_inputs_only_name_sheets_whose_position_changed() {- let mut engine = StyleEngine::new();- let user_agent = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::UserAgent);- let first = engine.add_sheet(StyleSheetObjectID(2), CascadeOrigin::Author);- let second = engine.add_sheet(StyleSheetObjectID(3), CascadeOrigin::Author);- for sheet in [user_agent, first, second] {- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- }- engine.append_rule(user_agent, None, RuleKind::Style);- let first_rule = engine.append_rule(first, None, RuleKind::Style);- let second_rule = engine.append_rule(second, None, RuleKind::Style);- discard_transaction(&mut engine);-- engine.attach_sheet(first, TreeScopeID::DOCUMENT);- let transaction = engine.take_transaction();- let mut rules: Vec<_> = transaction.program_joins.iter().map(|delta| delta.rule).collect();- rules.sort_unstable();- assert_eq!(rules, vec![first_rule, second_rule]);- engine.release_transaction(transaction);-- engine.attach_sheet(user_agent, TreeScopeID::DOCUMENT);- let transaction = engine.take_transaction();- assert!(transaction.program_joins.is_empty());- engine.release_transaction(transaction);-- engine.detach_sheet(first, TreeScopeID::DOCUMENT);- engine.attach_sheet(first, TreeScopeID::DOCUMENT);- let transaction = engine.take_transaction();- assert!(transaction.program_joins.is_empty());- engine.release_transaction(transaction);-}--#[test]-fn edits_to_a_temporarily_detached_sheet_keep_their_rule_inputs() {- let (mut engine, sheet, rule) = authoring_engine();- engine.detach_sheet(sheet, TreeScopeID::DOCUMENT);- let mut contents = engine.program.rule_version(rule);- contents.selector_program = Some(SelectorProgramID(2));- engine.replace_rule_version(rule, contents);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);-- let transaction = engine.take_transaction();- assert!(transaction.program_joins.iter().any(|delta| {- delta.rule == rule- && delta.kind == ProgramJoinDeltaKind::ActiveRuleMatch- && delta.before_program == Some(SelectorProgramID(1))- && delta.after_program == Some(SelectorProgramID(2))- }));+ assert_eq!(engine.rules.sheets_in_scope(TreeScopeID::DOCUMENT), vec![second, first]);engine.release_transaction(transaction);}#[test]-fn rule_changes_share_one_sheet_attachment_decision_per_transaction() {+fn rules_arriving_with_their_sheet_are_carried_by_it() {let mut engine = StyleEngine::new();- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);+ let sheet = engine.add_sheet(CascadeOrigin::Author);engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);-engine.append_rule(sheet, None, RuleKind::Style);engine.append_rule(sheet, None, RuleKind::Style);- assert_eq!(engine.host.program_staging.rule_change_is_carried_by_sheet.len(), 1);-- discard_transaction(&mut engine);- assert!(engine.host.program_staging.rule_change_is_carried_by_sheet.is_empty());+ let transaction = engine.take_transaction();+ assert!(transaction.rule_changes.rules.is_empty());+ assert_eq!(transaction.rule_changes.sheets, vec![sheet]);+ engine.release_transaction(transaction);- engine.append_rule(sheet, None, RuleKind::Style);- assert_eq!(engine.host.program_staging.rule_change_is_carried_by_sheet.len(), 1);+ let rule = engine.append_rule(sheet, None, RuleKind::Style);let transaction = engine.take_transaction();- assert!(- transaction- .inputs- .iter()- .any(|input| matches!(input.key, InputKey::RuleField(_, RuleField::Existence)))- );+ assert_eq!(transaction.rule_changes.rules, vec![rule]);+ assert!(transaction.rule_changes.sheets.is_empty());engine.release_transaction(transaction);}#[test]-fn deleting_a_group_rule_journals_every_identity_it_took_with_it() {+fn deleting_a_group_rule_changes_every_identity_it_took_with_it() {let mut engine = StyleEngine::new();- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);+ let sheet = engine.add_sheet(CascadeOrigin::Author);engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);let media = engine.append_rule(sheet, None, RuleKind::Media);let inner = engine.append_rule(sheet, Some(media), RuleKind::Style);@@ -10941,282 +859,84 @@ fn deleting_a_group_rule_journals_every_identity_it_took_with_it() {assert_eq!(removed, vec![media, inner]);let transaction = engine.take_transaction();- let keys: Vec<InputKey> = transaction.inputs.iter().map(|input| input.key).collect();- assert!(keys.contains(&InputKey::RuleField(media, RuleField::Existence)));- assert!(keys.contains(&InputKey::RuleField(inner, RuleField::Existence)));+ assert_eq!(transaction.rule_changes.rules, vec![media, inner]);engine.release_transaction(transaction);}#[test]fn rule_existence_commits_at_the_transaction_barrier() {let mut engine = StyleEngine::new();- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);+ let sheet = engine.add_sheet(CascadeOrigin::Author);engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);discard_transaction(&mut engine);let rule = engine.append_rule(sheet, None, RuleKind::Style);- assert!(!engine.program.rule_is_live(rule));+ assert!(!engine.rules.rule_is_live(rule));assert!(engine.current_rule_is_live(rule));let transaction = engine.take_transaction();- assert!(engine.program.rule_is_live(rule));+ assert!(engine.rules.rule_is_live(rule));engine.release_transaction(transaction);engine.remove_rule(rule);- assert!(engine.program.rule_is_live(rule));+ assert!(engine.rules.rule_is_live(rule));assert!(!engine.current_rule_is_live(rule));let transaction = engine.take_transaction();- assert!(!engine.program.rule_is_live(rule));- engine.release_transaction(transaction);-}--#[test]-fn inserting_and_deleting_an_unobserved_rule_cancels_out() {- let mut engine = StyleEngine::new();- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- discard_transaction(&mut engine);-- let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.remove_rule(rule);-- let transaction = engine.take_transaction();- assert!(- transaction.is_empty(),- "a rule inserted and removed before observation produces no selector or cascade work"- );- engine.release_transaction(transaction);-}--#[test]-fn publishing_an_implicit_layer_order_does_not_edit_the_program() {- let mut engine = StyleEngine::new();- let version = engine.program.version();-- engine.set_layer_order(TreeScopeID::DOCUMENT, &[CascadeLayerID::UNLAYERED]);-- assert_eq!(engine.program.version(), version);- assert!(engine.host.program_staging.base_version.is_none());- let transaction = engine.take_transaction();- assert!(transaction.is_empty());- engine.release_transaction(transaction);-}--#[test]-fn allocating_an_unattached_sheet_does_not_edit_the_program() {- let mut engine = StyleEngine::new();- let version = engine.program.version();-- engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);-- assert_eq!(engine.program.version(), version);- assert!(!engine.has_pending_transaction());- let transaction = engine.take_transaction();- assert!(transaction.is_empty());+ assert!(!engine.rules.rule_is_live(rule));engine.release_transaction(transaction);}#[test]-fn a_layer_topology_change_is_its_own_input_kind() {+fn a_layer_order_change_reorders_its_scope() {let (mut engine, _, _) = authoring_engine();let base = CascadeLayerID(1);let theme = CascadeLayerID(2);engine.set_layer_order(TreeScopeID::DOCUMENT, &[base, theme]);- engine.set_layer_order(TreeScopeID::DOCUMENT, &[theme, base]);- engine.set_tree_scope_uses_document_sheets(TreeScopeID(1));-- assert_eq!(engine.program.layer_index(TreeScopeID::DOCUMENT, base), 0);- assert_eq!(engine.layer_index(TreeScopeID::DOCUMENT, base), 1);- assert!(!engine.program.scope_uses_document_sheets(TreeScopeID(1)));-- let transaction = engine.take_transaction();- assert_eq!(engine.program.layer_index(TreeScopeID::DOCUMENT, base), 1);- assert!(engine.program.scope_uses_document_sheets(TreeScopeID(1)));- assert_eq!(kinds_of(&transaction), vec![InputKind::CascadeTopology]);- assert_eq!(engine.counters().get(Counter::CascadeTopologyDeltas), 1);- engine.release_transaction(transaction);-}--#[test]-fn disabling_a_sheet_is_an_activation_change() {- let (mut engine, sheet, _) = authoring_engine();- engine.set_sheet_enabled(sheet, false);- assert!(engine.program.sheet_is_enabled(sheet));-let transaction = engine.take_transaction();- assert!(!engine.program.sheet_is_enabled(sheet));- assert_eq!(- transaction.inputs.iter().map(|input| input.key).collect::<Vec<_>>(),- vec![InputKey::SheetActivation(sheet)]- );- engine.release_transaction(transaction);-}--#[test]-fn an_added_rule_that_loses_everywhere_confirms_without_cold_matching() {- let (mut engine, nodes) = linear_document();- let guard_class = StyleAtomID(200);- let target_class = StyleAtomID(201);- let important = add_target_rule(&mut engine, StyleSheetObjectID(1), target_class);- engine.set_rule_declared_properties(important, &[(1, true)]);- // A second matched rule with an incomplete declaration list keeps the winner inventory- // incomplete, so the whole-inventory proof cannot carry the stop; the transition proof must.- let incomplete = add_target_rule(&mut engine, StyleSheetObjectID(2), target_class);- set_rule_declared_properties_beside_a_custom_property(&mut engine, incomplete, &[(2, false)]);- // The addition arrives through an ancestor class toggle, so the confirmed node itself- // carries no direct transaction input and stays eligible for confirmation.- let loser = add_guard_target_rule_in_sheet(&mut engine, StyleSheetObjectID(3), guard_class, target_class);- engine.set_rule_declared_properties(loser, &[(1, false)]);- for &node in &nodes {- set_atom_feature(&mut engine, node, LocalFeatureKey::TagName, StyleAtomID(100));- }- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(target_class));- discard_transaction(&mut engine);-- let old_answer = engine.match_element_for_cascade(nodes[1]).unwrap();- assert!(old_answer.iter().any(|entry| entry.rule == important));- publish_current_cascade_as_computed(&mut engine, nodes[1]);-- add_feature(&mut engine, nodes[0], LocalFeatureKey::Class(guard_class));- let stops_before = engine.counters().get(Counter::PublishedExactCascadeStops);- let proofs_before = engine.counters().get(Counter::TransitionProofConfirmed);- let mut planned = Vec::new();- assert!(engine.take_style_transaction(nodes[0], |_, _, reactions| {- planned.extend(reactions.iter().map(|reaction| reaction.style_node));- }));-assert!(- !planned.contains(&nodes[1].raw()),- "an added rule that loses everywhere must not publish the losing node"- );- assert_eq!(- engine.counters().get(Counter::PublishedExactCascadeStops),- stops_before + 1- );- assert_eq!(- engine.counters().get(Counter::TransitionProofConfirmed),- proofs_before + 1+ transaction.rule_changes.reordered_scopes.is_empty(),+ "a scope's first layer order moves no rule");- let current = engine.match_element_for_cascade(nodes[1]).unwrap();- assert!(current.iter().any(|entry| entry.rule == loser));-}--#[test]-fn answer_transitions_refuse_equality_removals_and_winning_additions() {- let (mut engine, nodes) = linear_document();- let anchor_class = StyleAtomID(200);- let toggled_class = StyleAtomID(201);- let base = add_target_rule(&mut engine, StyleSheetObjectID(1), anchor_class);- engine.set_rule_declared_properties(base, &[(1, false)]);- let winner = add_target_rule(&mut engine, StyleSheetObjectID(2), toggled_class);- engine.set_rule_declared_properties(winner, &[(1, false)]);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(anchor_class));- discard_transaction(&mut engine);-- let exact = engine.match_element(nodes[1]).unwrap();- let before = engine.matches_for_cascade(exact.clone(), false, Some(nodes[1]));- engine.remember_retained_match_answer(nodes[1], &exact);- engine.remember_cascade_input(nodes[1], &before);- let Lookup::Known(&before_input) = engine.retained_match_answers.cascade_input_lookup(nodes[1]) else {- panic!("the anchored answer must intern a cascade input");- };- publish_current_cascade_as_computed(&mut engine, nodes[1]);-- // Equality is never a proof: a stale retained answer compares equal to itself.- assert!(!engine.answer_transition_cannot_change_cascade(nodes[1], before_input, before_input));-- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(toggled_class));- discard_transaction(&mut engine);- let exact = engine.match_element(nodes[1]).unwrap();- let with = engine.matches_for_cascade(exact.clone(), false, Some(nodes[1]));- engine.remember_retained_match_answer(nodes[1], &exact);- engine.remember_cascade_input(nodes[1], &with);- let Lookup::Known(&with_winner) = engine.retained_match_answers.cascade_input_lookup(nodes[1]) else {- panic!("the toggled answer must intern a cascade input");- };- assert_ne!(before_input, with_winner);-- // A later-sheet addition to the same property is not strictly weaker; the proof must refuse.- assert!(!engine.answer_transition_cannot_change_cascade(nodes[1], before_input, with_winner));+ engine.release_transaction(transaction);- // A removal can uncover a candidate provenance cannot always name; it must refuse too.- assert!(!engine.answer_transition_cannot_change_cascade(nodes[1], with_winner, before_input));-}+ engine.set_layer_order(TreeScopeID::DOCUMENT, &[theme, base]);+ engine.set_tree_scope_uses_document_sheets(TreeScopeID(1));-#[test]-fn native_atom_reclamation_does_not_claim_a_cpp_memo_reference() {- let mut engine = StyleEngine::new();- let native = engine.atoms.intern_raw(0x1000);- let shared = engine.atoms.intern_raw(0x1001);- assert_eq!(engine.intern_atom(0x1001), shared);- for raw in 0x2000..0x2100 {- engine.atoms.intern_raw(raw);- }- engine.sweep_style_atoms();- assert!(- engine- .host- .reclaimed_style_atoms- .iter()- .any(|entry| entry.atom == native && entry.raw == 0)- );- assert!(- engine- .host- .reclaimed_style_atoms- .iter()- .any(|entry| entry.atom == shared && entry.raw == 0x1001)- );+ assert_eq!(engine.rules.layer_index(TreeScopeID::DOCUMENT, base), 0);+ assert_eq!(engine.layer_index(TreeScopeID::DOCUMENT, base), 1);+ assert!(!engine.rules.scope_uses_document_sheets(TreeScopeID(1)));++ let transaction = engine.take_transaction();+ assert_eq!(engine.rules.layer_index(TreeScopeID::DOCUMENT, base), 1);+ assert!(engine.rules.scope_uses_document_sheets(TreeScopeID(1)));+ assert_eq!(transaction.rule_changes.reordered_scopes, vec![TreeScopeID::DOCUMENT]);+ assert_eq!(engine.counters().get(Counter::CascadeTopologyDeltas), 1);+ engine.release_transaction(transaction);}#[test]-fn releasing_a_flush_transaction_does_not_reclaim_atoms() {- let mut engine = StyleEngine::new();- for raw in 0x1000..0x1100 {- engine.intern_atom(raw);- }+fn disabling_a_sheet_is_an_activation_change() {+ let (mut engine, sheet, _) = authoring_engine();+ engine.set_sheet_enabled(sheet, false);+ assert!(engine.rules.sheet_is_enabled(sheet));let transaction = engine.take_transaction();+ assert!(!engine.rules.sheet_is_enabled(sheet));+ assert_eq!(transaction.rule_changes.sheets, vec![sheet]);engine.release_transaction(transaction);-- assert!(engine.host.reclaimed_style_atoms.is_empty());- assert_eq!(engine.counters().get(Counter::AtomSweeps), 0);}#[test]-fn atom_sweep_waits_for_an_active_matching_traversal() {- let (mut engine, nodes) = nested_document();- let target = StyleAtomID(200);- add_target_rule(&mut engine, StyleSheetObjectID(1), target);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(target));- // The broad initial publication prepares the traversal over the primary view itself, so the- // active traversal shares the fact rows exactly as a first style pass in the browser does.- assert!(!take_every_wave(&mut engine, nodes[0], |_, _, _| {}));- assert!(engine.begin_cold_matching_batch(nodes[0]));- assert!(engine.facts.primary_rows_are_shared());+fn releasing_a_flush_transaction_does_not_reclaim_atoms() {+ let mut engine = StyleEngine::new();for raw in 0x1000..0x1100 {engine.intern_atom(raw);}- engine.record_input(- InputKey::ElementStyleInput(nodes[1]),- InputValue::ElementStyleInput {- reaction: 0,- inherited_style_groups: 0,- },- InputValue::ElementStyleInput {- reaction: transaction::STYLE_REACTION_RECOMPUTE_STYLE,- inherited_style_groups: 0,- },- );- assert!(engine.take_style_transaction(nodes[0], |_, _, _| {}));- assert_eq!(engine.counters().get(Counter::AtomSweeps), 0);- assert_eq!(engine.counters().get(Counter::AtomSweepsDeferredForActiveTraversal), 1);- assert!(engine.host.reclaimed_style_atoms.is_empty());+ let transaction = engine.take_transaction();+ engine.release_transaction(transaction);- engine.end_cold_matching_batch();- assert!(engine.take_style_transaction(nodes[0], |_, _, _| {}));- assert_eq!(engine.counters().get(Counter::AtomSweeps), 1);- assert!(!engine.host.reclaimed_style_atoms.is_empty());+ assert!(engine.host.reclaimed_style_atoms.is_empty());+ assert_eq!(engine.counters().get(Counter::AtomSweeps), 0);}#[test]@@ -11255,292 +975,115 @@ fn attribute_names_keep_all_noted_forms_live() {}#[test]-fn qualified_attribute_programs_keep_local_name_forms_live() {+fn an_arena_keeps_the_qualified_attribute_names_it_tests_live_across_a_sweep() {let mut engine = StyleEngine::new();- let namespace = engine.intern_atom(0x1000);- let local_name = engine.intern_atom(0x1001);- let qualified_name = engine.intern_qualified_atom(namespace, local_name);- let any_namespace = engine.intern_qualified_atom(StyleAtomID::NONE, local_name);- engine.note_attribute_name_forms(- local_name,- index::AttributeNameForms {- local: any_namespace,- ..index::AttributeNameForms::default()- },- );- let mut builder = selector::SelectorProgramBuilder::new();- let attribute = builder.push_feature(selector::FeatureTest::Attribute(selector::AttributeTest {- name: qualified_name,- any_namespace: false,- folded: qualified_name,- fold_in_namespace: StyleAtomID::NONE,- operator: selector::AttributeOperator::Presence,- value_atom: StyleAtomID::NONE,- value_offset: 0,- value_length: 0,- case: selector::AttributeCase::Sensitive,- }));- builder.push_entry(attribute);- let program = engine.programs.add(builder.finish());- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);+ engine.share_the_process_style_for_test();+ let utf16 = |text: &str| text.encode_utf16().collect::<Vec<u16>>();+ let (prefix, uri) = (utf16("q"), utf16("urn:arena-keeps-qualified-names"));+ let parsed = crate::css::selector_parser::parse_selector_list(+ &utf16("[q|Data-Kept]")[..],+ &[crate::css::css_tokenizer::TokenizerInput::Utf16(&prefix)],+ crate::css::selector_parser::SelectorType::Standalone,+ crate::css::selector_parser::SelectorParsingMode::Standard,+ )+ .expect("a test writes valid selectors");+ let selectors = parsed+ .into_list_declaring(+ crate::css::ffi_support::StyleNestingParent::None,+ crate::css::selector_arena::NamespaceDeclarations::of_texts([(&prefix[..], &uri[..])]),+ )+ .selectors;+ let sheet = engine.add_sheet(CascadeOrigin::Author);engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);+ let mut contents = engine.rules().rule_version(rule).clone();+ contents.selectors = engine.retained.rules.start_of_selectors(sheet, &selectors);+ contents.declaration_block = Some(DeclarationBlockID::new(1));+ engine.replace_rule_version(rule, contents);discard_transaction(&mut engine);- for raw in 0x2000..0x2100 {- engine.intern_atom(raw);++ // The host publishes an element's attributes by their qualified names, which the document interns.+ let names: Vec<ak::Utf16FlyString> = ["urn:arena-keeps-qualified-names", "Data-Kept", "data-kept"]+ .into_iter()+ .map(|name| ak::Utf16FlyString::from_utf16(&utf16(name)))+ .collect();+ let [namespace, local, folded] = [0, 1, 2].map(|index| engine.intern_atom(names[index].raw_identity()));+ let qualified = engine.intern_qualified_atom(namespace, local);+ let folded_qualified = engine.intern_qualified_atom(namespace, folded);+ let fillers: Vec<ak::Utf16FlyString> = (0..300)+ .map(|index| ak::Utf16FlyString::from_utf16(&utf16(&format!("arena-sweep-filler-{index}"))))+ .collect();+ for filler in &fillers {+ engine.intern_atom(filler.raw_identity());}engine.sweep_style_atoms();+ assert_eq!(engine.counters().get(Counter::AtomSweeps), 1);let reclaimed = engine.host.reclaimed_style_atoms.iter().map(|reclaimed| reclaimed.atom).collect::<HashSet<_>>();- assert!(!reclaimed.contains(&namespace));- assert!(!reclaimed.contains(&local_name));- assert!(!reclaimed.contains(&qualified_name));- assert!(!reclaimed.contains(&any_namespace));-}--#[test]-fn engine_atom_sweeps_preserve_roots_and_purge_reused_identities() {- let (mut engine, nodes) = linear_document();- let old_class = engine.intern_atom(0x1000);- let old_rule = add_target_rule(&mut engine, StyleSheetObjectID(1), old_class);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(old_class));- discard_transaction(&mut engine);-- for raw in 0x2000..0x2100 {- engine.intern_atom(raw);- }- engine.sweep_style_atoms();- assert!(- engine- .host- .reclaimed_style_atoms- .iter()- .all(|reclaimed| reclaimed.atom != old_class)- );- engine.host.reclaimed_style_atoms.clear();-- remove_feature(&mut engine, nodes[1], LocalFeatureKey::Class(old_class));- discard_transaction(&mut engine);- assert!(engine.collect_live_style_atoms().0.contains(&old_class));- engine.remove_rule(old_rule);- discard_transaction(&mut engine);- for raw in 0x3000..0x3100 {- engine.intern_atom(raw);+ assert!(!reclaimed.is_empty());+ for kept in [qualified, folded_qualified, namespace, local, folded] {+ assert!(!reclaimed.contains(&kept));}- engine.sweep_style_atoms();- assert!(- engine- .host- .reclaimed_style_atoms- .iter()- .any(|reclaimed| reclaimed.atom == old_class)- );- engine.host.reclaimed_style_atoms.clear();-- let new_class = engine.intern_atom(0x4000);- assert_eq!(new_class, old_class);- assert!(engine.match_element(nodes[1]).unwrap().is_empty());- let new_rule = add_target_rule(&mut engine, StyleSheetObjectID(2), new_class);- add_feature(&mut engine, nodes[2], LocalFeatureKey::Class(new_class));- discard_transaction(&mut engine);- assert!(engine.match_element(nodes[1]).unwrap().is_empty());- assert!(- engine- .match_element(nodes[2])- .unwrap()- .iter()- .any(|matched| matched.rule == new_rule)- );-}--#[test]-fn engine_keeps_handed_attribute_value_text_only_where_a_selector_reads_the_name() {- let (mut engine, _) = linear_document();- let name = engine.intern_atom(0x1000);- let before_rule = engine.intern_atom(0x1001);- let after_rule = engine.intern_atom(0x1002);- engine.note_attribute_name_forms(name, index::AttributeNameForms::default());- let text = [u16::from(b'n'), u16::from(b'e'), u16::from(b'w')];- let hand_over = |engine: &mut StyleEngine, value| {- super::engine_calls::EngineWrite::AttributeValueText {- name,- value,- text: crate::css::retained_fly_string::RetainedUtf16FlyString::from_utf16(&text),- }- .apply(engine);- };-- // The host hands over the text where it does not know whether anything reads the name.- hand_over(&mut engine, before_rule);- assert!(!engine.has_attribute_value_text(before_rule));-- let mut builder = selector::SelectorProgramBuilder::new();- let (value_offset, value_length) = builder.push_literal(&text[..2]);- let prefix = builder.push_feature(selector::FeatureTest::Attribute(selector::AttributeTest {- name,- any_namespace: false,- folded: name,- fold_in_namespace: StyleAtomID::NONE,- operator: selector::AttributeOperator::Prefix,- value_atom: StyleAtomID::NONE,- value_offset,- value_length,- case: selector::AttributeCase::Sensitive,- }));- let compound = builder.push_compound(&[prefix]);- builder.push_entry(compound);- engine.note_selector_attribute_names(&builder.finish());- assert!(engine.attribute_name_requires_value_text(name));-- hand_over(&mut engine, after_rule);- assert!(engine.has_attribute_value_text(after_rule));}#[test]-fn engine_atom_reuse_replaces_catalog_text_and_name_forms() {- let (mut engine, nodes) = linear_document();- let old_name = engine.intern_atom(0x1000);- let old_any_namespace = engine.intern_qualified_atom(StyleAtomID::NONE, old_name);- let old_value = engine.intern_atom(0x1001);- let old_language = engine.intern_atom(0x1002);- engine.note_attribute_name_forms(- old_name,- index::AttributeNameForms {- local: old_any_namespace,- ..index::AttributeNameForms::default()- },- );- engine.set_attribute_value_text(old_value, &[u16::from(b'o'), u16::from(b'l'), u16::from(b'd')]);- engine.set_element_language_text(old_language, &[u16::from(b'e'), u16::from(b'n')]);- engine.record_input(- InputKey::LocalFeature(nodes[1], LocalFeatureKey::Attribute(old_name)),- InputValue::Feature(FeatureValue::Absent),- InputValue::Feature(FeatureValue::Atom(old_value)),- );- engine.set_element_language(nodes[1], old_language);- discard_transaction(&mut engine);- engine.record_input(- InputKey::LocalFeature(nodes[1], LocalFeatureKey::Attribute(old_name)),- InputValue::Feature(FeatureValue::Atom(old_value)),- InputValue::Feature(FeatureValue::Absent),- );- engine.set_element_language(nodes[1], StyleAtomID::NONE);- discard_transaction(&mut engine);- for raw in 0x2000..0x2100 {- engine.intern_atom(raw);- }- engine.sweep_style_atoms();- let reclaimed = engine- .host- .reclaimed_style_atoms- .iter()- .map(|reclaimed| reclaimed.atom)- .collect::<HashSet<_>>();- for atom in [old_name, old_any_namespace, old_value, old_language] {- assert!(reclaimed.contains(&atom));- }- engine.host.reclaimed_style_atoms.clear();-- let new_name = engine.intern_atom(0x3000);- let new_any_namespace = engine.intern_qualified_atom(StyleAtomID::NONE, new_name);- let new_value = engine.intern_atom(0x3001);- let new_language = engine.intern_atom(0x3002);- assert_eq!(- [new_name, new_any_namespace, new_value, new_language],- [old_name, old_any_namespace, old_value, old_language]- );- engine.note_attribute_name_forms(- new_name,- index::AttributeNameForms {- local: new_any_namespace,- ..index::AttributeNameForms::default()- },- );- engine.set_attribute_value_text(new_value, &[u16::from(b'n'), u16::from(b'e'), u16::from(b'w')]);- engine.set_element_language_text(new_language, &[u16::from(b's'), u16::from(b'v')]);-- let mut builder = selector::SelectorProgramBuilder::new();- let (value_offset, value_length) = builder.push_literal(&[u16::from(b'n'), u16::from(b'e')]);- let prefix = builder.push_feature(selector::FeatureTest::Attribute(selector::AttributeTest {- name: new_name,- any_namespace: false,- folded: new_name,- fold_in_namespace: StyleAtomID::NONE,- operator: selector::AttributeOperator::Prefix,- value_atom: StyleAtomID::NONE,- value_offset,- value_length,- case: selector::AttributeCase::Sensitive,- }));- let (first, count) = builder.push_language_ranges(&[&[u16::from(b's'), u16::from(b'v')]]);- let language = builder.push(selector::SelectorOp::Language { first, count });- let any_namespace = builder.push_feature(selector::FeatureTest::Attribute(selector::AttributeTest {- name: new_any_namespace,- any_namespace: true,- folded: new_any_namespace,- fold_in_namespace: StyleAtomID::NONE,- operator: selector::AttributeOperator::Presence,- value_atom: StyleAtomID::NONE,- value_offset: 0,- value_length: 0,- case: selector::AttributeCase::Sensitive,- }));- let compound = builder.push_compound(&[prefix, language, any_namespace]);- builder.push_entry(compound);- let program = engine.programs.add(builder.finish());- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::Author);+fn a_sweep_keeps_the_names_a_rule_tests_in_any_namespace() {+ let mut engine = StyleEngine::new();+ engine.share_the_process_style_for_test();+ let utf16 = |text: &str| text.encode_utf16().collect::<Vec<u16>>();+ let parsed = crate::css::selector_parser::parse_selector_list(+ &utf16("[*|Data-Any-Kept]")[..],+ &[],+ crate::css::selector_parser::SelectorType::Standalone,+ crate::css::selector_parser::SelectorParsingMode::Standard,+ )+ .expect("a test writes valid selectors");+ let selectors = parsed+ .into_list_declaring(+ crate::css::ffi_support::StyleNestingParent::None,+ crate::css::selector_arena::NamespaceDeclarations::of_texts([]),+ )+ .selectors;+ let sheet = engine.add_sheet(CascadeOrigin::Author);engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);let rule = engine.append_rule(sheet, None, RuleKind::Style);- engine.add_routing_rule(rule, program);- let mut version = engine.program.rule_version(rule);- version.selector_program = Some(program);- version.declaration_block = Some(DeclarationBlockID(1));- engine.replace_rule_version(rule, version);- engine.record_input(- InputKey::LocalFeature(nodes[1], LocalFeatureKey::Attribute(new_name)),- InputValue::Feature(FeatureValue::Absent),- InputValue::Feature(FeatureValue::Atom(new_value)),- );- engine.set_element_language(nodes[1], new_language);+ let mut contents = engine.rules().rule_version(rule).clone();+ contents.selectors = engine.retained.rules.start_of_selectors(sheet, &selectors);+ contents.declaration_block = Some(DeclarationBlockID::new(1));+ engine.replace_rule_version(rule, contents);+ engine.retained.note_selectors(&selectors, None);discard_transaction(&mut engine);+ let tested = engine.retained.selector_summary().tested_attribute_names;+ assert!(!tested.is_empty());- assert!(engine.has_attribute_value_text(new_value));- assert_eq!(engine.facts.attribute_name_forms(new_name).local, new_any_namespace);- let primary = engine.facts.primary();- let row = primary.row_of(nodes[1]).unwrap();- let attribute = primary.attribute_of(row, new_name).unwrap();- assert_eq!(- primary.text_of(attribute),- Some([u16::from(b'n'), u16::from(b'e'), u16::from(b'w')].as_slice())- );- assert_eq!(primary.attribute_name_forms(new_name).local, new_any_namespace);+ let fillers: Vec<ak::Utf16FlyString> = (0..300)+ .map(|index| ak::Utf16FlyString::from_utf16(&utf16(&format!("any-namespace-sweep-filler-{index}"))))+ .collect();+ for filler in &fillers {+ engine.intern_atom(filler.raw_identity());+ }+ engine.sweep_style_atoms();- assert!(- engine- .match_element(nodes[1])- .unwrap()- .iter()- .any(|matched| matched.rule == rule)- );+ assert_eq!(engine.counters().get(Counter::AtomSweeps), 1);+ let kept = engine.retained.selector_summary().tested_attribute_names;+ for name in tested {+ assert!(kept.contains(&name), "the sweep made {name:?} known unread");+ }}#[test]fn engine_atom_reuse_replaces_custom_property_names() {let mut engine = StyleEngine::new();let old_name = engine.intern_atom(0x1000);+ let old_text = ak::Utf16FlyString::from_utf16(&[u16::from(b'-'), u16::from(b'-'), u16::from(b'o')]);unsafe {- engine.note_custom_property_name(old_name, 0, &[u16::from(b'-'), u16::from(b'-'), u16::from(b'o')]);+ engine.note_custom_property_name(old_name, old_text.raw_identity());}for raw in 0x2000..0x2100 {engine.intern_atom(raw);@@ -11559,51 +1102,36 @@ fn engine_atom_reuse_replaces_custom_property_names() {let new_name = engine.intern_atom(0x3000);assert_eq!(new_name, old_name);- let new_text = [u16::from(b'-'), u16::from(b'-'), u16::from(b'n')];+ let new_text = ak::Utf16FlyString::from_utf16(&[u16::from(b'-'), u16::from(b'-'), u16::from(b'n')]);unsafe {- engine.note_custom_property_name(new_name, 0, &new_text);+ engine.note_custom_property_name(new_name, new_text.raw_identity());}assert_eq!(- engine- .custom_property_environments- .name(new_name)- .unwrap()- .text- .as_ref(),- new_text+ engine.custom_property_environments.name(new_name).unwrap().raw(),+ new_text.raw_identity());}#[test]fn owed_element_style_inputs_fold_into_covering_reactions() {- use super::transaction::{STYLE_REACTION_INHERITED_STYLE, STYLE_REACTION_RECOMPUTE_STYLE};+ use super::input_types::STYLE_REACTION_PSEUDO_INPUTS_MAY_HAVE_CHANGED;let mut engine = StyleEngine::new();let mut raw_nodes = [0; 1];engine.allocate_style_nodes(&mut raw_nodes);let node = StyleNodeID::from_raw(raw_nodes[0]).unwrap();- engine.record_derived_element_style_input(node, STYLE_REACTION_INHERITED_STYLE, 0b0010);+ engine.record_derived_element_style_input(node, STYLE_REACTION_PSEUDO_INPUTS_MAY_HAVE_CHANGED, 0b0010);assert!(engine.has_deferred_element_style_input(node));// A record delta covers only what it already carries.assert_eq!(- engine.absorb_element_style_input(node, STYLE_REACTION_INHERITED_STYLE, 0b0100, false),+ engine.absorb_element_style_input(node, STYLE_REACTION_PSEUDO_INPUTS_MAY_HAVE_CHANGED, 0b0100),0);assert!(engine.has_deferred_element_style_input(node));assert_eq!(- engine.absorb_element_style_input(node, STYLE_REACTION_INHERITED_STYLE, 0b0110, false),- u32::from(STYLE_REACTION_INHERITED_STYLE) | (0b0110 << 8)- );- assert!(!engine.has_deferred_element_style_input(node));-- // A materialization covers anything, and the merge carries both sides.- engine.record_derived_element_style_input(node, STYLE_REACTION_INHERITED_STYLE, 0b0010);- let merged = engine.absorb_element_style_input(node, STYLE_REACTION_RECOMPUTE_STYLE, 0b0100, true);- assert_eq!(- merged & 0xff,- u32::from(STYLE_REACTION_RECOMPUTE_STYLE | STYLE_REACTION_INHERITED_STYLE)+ engine.absorb_element_style_input(node, STYLE_REACTION_PSEUDO_INPUTS_MAY_HAVE_CHANGED, 0b0110),+ u32::from(STYLE_REACTION_PSEUDO_INPUTS_MAY_HAVE_CHANGED) | (0b0110 << 8));- assert_eq!(merged >> 8, 0b0110);assert!(!engine.has_deferred_element_style_input(node));}@@ -11615,29 +1143,23 @@ fn held_style_records_outlive_engine_assignments_and_release_on_retirement() {let [first, second] = raw_nodes.map(|node| StyleNodeID::from_raw(node).unwrap());let publish = |engine: &mut StyleEngine, node, pseudo_element_styles| {engine- .publish_computed_groups(+ .install_test_record(computed::ComputedStyleTarget::new(node, u8::MAX),- &[],- 0,- 0,- computed::ComputedMetadataInput {- pseudo_element_styles,- dependency_flags: 0,- counter_style_environment_identity: 0,- animation_overlay_identity: 0,- animated_overlay: HostShared::null(),- animation_overlay_payloads: &[],- longhand_table: HostShared::null(),- },+ None,+ None,+ pseudo_element_styles,)- .style_record_identity.raw()};+ let held = |engine: &StyleEngine, record| engine.computed_group_sets.host_record(record).cloned();let held_record = publish(&mut engine, first, 1);assert_eq!(publish(&mut engine, second, 1), held_record);- engine.set_held_style_record(first, held_record);- engine.set_held_style_record(first, held_record);- engine.set_held_style_record(second, held_record);+ let record = held(&engine, held_record);+ engine.set_held_style_record(first, record);+ let record = held(&engine, held_record);+ engine.set_held_style_record(first, record);+ let record = held(&engine, held_record);+ engine.set_held_style_record(second, record);// The engine can publish a replacement before the host installs it.let replacement = publish(&mut engine, first, 2);@@ -11645,13 +1167,15 @@ fn held_style_records_outlive_engine_assignments_and_release_on_retirement() {engine.computed_group_sets.reclaim_unreachable();assert!(engine.computed_group_sets.final_style_record_is_live(held_record));- engine.set_held_style_record(first, replacement);+ let record = held(&engine, replacement);+ engine.set_held_style_record(first, record);engine.computed_group_sets.reclaim_unreachable();assert!(engine.computed_group_sets.final_style_record_is_live(held_record));assert!(engine.computed_group_sets.final_style_record_is_live(replacement));+ assert_eq!(engine.held_style_record(first), Some(replacement));// Clearing one holder must not release another holder's shared record.- engine.set_held_style_record(first, 0);+ engine.set_held_style_record(first, None);engine.computed_group_sets.remove(first);engine.computed_group_sets.reclaim_unreachable();assert!(engine.computed_group_sets.final_style_record_is_live(held_record));@@ -11663,34 +1187,24 @@ fn held_style_records_outlive_engine_assignments_and_release_on_retirement() {}#[test]-fn held_pseudo_style_records_outlive_engine_assignments_and_release_on_retirement() {- use super::publication::pseudo_kind::{AFTER, BEFORE};+fn pseudo_element_records_the_host_references_outlive_engine_assignments() {+ use super::publication::pseudo_kind::BEFORE;let mut engine = StyleEngine::new();let mut raw_node = [0];engine.allocate_style_nodes(&mut raw_node);let node = StyleNodeID::from_raw(raw_node[0]).unwrap();let publish = |engine: &mut StyleEngine, pseudo_kind, pseudo_element_styles| {engine- .publish_computed_groups(+ .install_test_record(computed::ComputedStyleTarget::new(node, pseudo_kind),- &[],- 0,- 0,- computed::ComputedMetadataInput {- pseudo_element_styles,- dependency_flags: 0,- counter_style_environment_identity: 0,- animation_overlay_identity: 0,- animated_overlay: HostShared::null(),- animation_overlay_payloads: &[],- longhand_table: HostShared::null(),- },+ None,+ None,+ pseudo_element_styles,)- .style_record_identity.raw()};let held_record = publish(&mut engine, BEFORE, 1);- engine.set_held_pseudo_style_record(node, BEFORE, held_record);+ let host_reference = engine.computed_group_sets.host_record(held_record).cloned();engine.set_held_pseudo_style_record(node, BEFORE, held_record);// The engine can publish a replacement before the host installs it.@@ -11698,25 +1212,15 @@ fn held_pseudo_style_records_outlive_engine_assignments_and_release_on_retiremenengine.computed_group_sets.reclaim_unreachable();assert!(engine.computed_group_sets.final_style_record_is_live(held_record));- // Installing the replacement lets go of the record it replaced, however often the host reported it.+ drop(host_reference);engine.set_held_pseudo_style_record(node, BEFORE, replacement);engine.computed_group_sets.reclaim_unreachable();assert!(!engine.computed_group_sets.final_style_record_is_live(held_record));assert!(engine.computed_group_sets.final_style_record_is_live(replacement));- // Clearing one pseudo-element's record must not release another's.- let after_record = publish(&mut engine, AFTER, 3);- engine.set_held_pseudo_style_record(node, AFTER, after_record);- engine.set_held_pseudo_style_record(node, BEFORE, 0);- engine.computed_group_sets.remove_pseudo(node, BEFORE);- engine.computed_group_sets.remove_pseudo(node, AFTER);- engine.computed_group_sets.reclaim_unreachable();- assert!(!engine.computed_group_sets.final_style_record_is_live(replacement));- assert!(engine.computed_group_sets.final_style_record_is_live(after_record));-engine.retire_node_state(node);engine.computed_group_sets.reclaim_unreachable();- assert!(!engine.computed_group_sets.final_style_record_is_live(after_record));+ assert!(!engine.computed_group_sets.final_style_record_is_live(replacement));}#[test]@@ -11727,29 +1231,12 @@ fn records_left_unreachable_under_a_lease_are_reclaimed_once_it_drops() {let target = computed::ComputedStyleTarget::new(StyleNodeID::from_raw(raw_node[0]).unwrap(), u8::MAX);let mut publish = |pseudo_element_styles| {engine- .publish_computed_groups(- target,- &[],- 0,- 0,- computed::ComputedMetadataInput {- pseudo_element_styles,- dependency_flags: 0,- counter_style_environment_identity: 0,- animation_overlay_identity: 0,- animated_overlay: HostShared::null(),- animation_overlay_payloads: &[],- longhand_table: HostShared::null(),- },- )- .style_record_identity+ .install_test_record(target, None, None, pseudo_element_styles).raw()};let first = publish(0);- // Each record replaces the last, so enough of them make reclamation due.- for pseudo_element_styles in 1..=1024 {- publish(pseudo_element_styles);- }+ // The next record replaces the first, which nothing holds then.+ publish(1);let lease = engine.lease_style_records();engine.begin_style_record_view_epoch();@@ -11762,109 +1249,6 @@ fn records_left_unreachable_under_a_lease_are_reclaimed_once_it_drops() {assert!(!engine.computed_group_sets.final_style_record_is_live(first));}-#[test]-fn sheet_occurrences_update_retained_cascade_order_without_recompiling() {- let (mut engine, nodes) = linear_document();- let target = StyleAtomID(200);- let shared_rule = add_target_rule(&mut engine, StyleSheetObjectID(1), target);- let middle_rule = add_target_rule(&mut engine, StyleSheetObjectID(2), target);- engine.set_rule_declared_properties(shared_rule, &[(1, false)]);- engine.set_rule_declared_properties(middle_rule, &[(1, false)]);- let shared = engine.program.rule_sheet(shared_rule);- let middle = engine.program.rule_sheet(middle_rule);- let scope = TreeScopeID::DOCUMENT;- engine.detach_sheet(shared, scope);- engine.detach_sheet(middle, scope);- engine.attach_sheet_occurrence(shared, scope, 1, 0, true);- engine.attach_sheet_occurrence(middle, scope, 2, 0, true);- engine.attach_sheet_occurrence(shared, scope, 3, 0, true);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);- let exact = engine.match_element(nodes[1]).unwrap();- let old = engine.matches_for_cascade(exact.clone(), false, Some(nodes[1]));- assert_eq!(old.len(), 1);- assert_eq!(old[0].rule, shared_rule);- engine.remember_retained_match_answer(nodes[1], &exact);- engine.remember_cascade_input(nodes[1], &old);- let version = engine.program.rule_version(shared_rule);-- engine.set_sheet_occurrence_conditions(scope, 3, false);- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes[1].raw()]);- engine.begin_adaptive_cold_matching_batch(nodes[0]);- let answer = engine.match_element_for_cascade(nodes[1]).unwrap();- engine.end_cold_matching_batch();- assert_eq!(answer.len(), 1);- assert_eq!(answer[0].rule, middle_rule);- assert_eq!(engine.program.rule_version(shared_rule), version);-}--#[test]-fn retiring_the_last_sheet_occurrence_invalidates_its_winners() {- let (mut engine, nodes) = linear_document();- let target = StyleAtomID(200);- let rule = add_target_rule(&mut engine, StyleSheetObjectID(1), target);- engine.set_rule_declared_properties(rule, &[(1, false)]);- let sheet = engine.program.rule_sheet(rule);- let scope = TreeScopeID::DOCUMENT;- engine.detach_sheet(sheet, scope);- engine.attach_sheet_occurrence(sheet, scope, 1, 0, true);- add_feature(&mut engine, nodes[1], LocalFeatureKey::Class(target));- discard_transaction(&mut engine);- let exact = engine.match_element(nodes[1]).unwrap();- let old = engine.matches_for_cascade(exact.clone(), false, Some(nodes[1]));- engine.remember_retained_match_answer(nodes[1], &exact);- engine.remember_cascade_input(nodes[1], &old);-- engine.detach_sheet_occurrence(scope, 1);- engine.begin_sheet_rules_replacement(sheet);- engine.finish_sheet_rules_replacement(sheet, 0);- let mut planned = Vec::new();- assert!(engine.take_style_transaction_nodes(nodes[0], |nodes| planned.extend_from_slice(nodes)));- assert_eq!(planned, vec![nodes[1].raw()]);-}--#[test]-fn a_reissued_style_node_identity_holds_no_retained_state() {- let (mut engine, nodes) = linear_document();- let class = StyleAtomID(200);- let rule = add_target_rule(&mut engine, StyleSheetObjectID(1), class);- engine.set_rule_declared_properties_with_values(rule, &[(1, false, SpecifiedValueID(101))]);- let leaving = nodes[3];- add_feature(&mut engine, leaving, LocalFeatureKey::Class(class));- discard_transaction(&mut engine);- assert!(engine.match_element_for_cascade(leaving).is_ok());- publish_current_cascade_as_computed(&mut engine, leaving);- engine.nodes_with_substituted_records.insert(leaving);- let holds_winners = |engine: &StyleEngine| {- engine- .winner_groups- .token_for(WinnerGroupKey::current(leaving, engine.program.version()))- .sparse()- .is_ok()- };- assert!(holds_winners(&engine));- assert!(engine.computed_group_sets.assigned_style_record(leaving).is_some());-- // The element leaves the tree. The transaction that sees it go retires its identity, and the end of that- // transaction's outputs releases the identity for the next element.- engine.record_tree_delta(- leaving,- Some(relations(Some(nodes[0].raw()), Some(nodes[2].raw()), None)),- None,- );- discard_transaction(&mut engine);- engine.discard_style_transaction_outputs();- let mut reissued = [0_u32; 1];- engine.allocate_style_nodes(&mut reissued);-- assert_eq!(reissued[0], leaving.raw());- assert!(!holds_winners(&engine));- assert!(engine.computed_group_sets.assigned_style_record(leaving).is_none());- assert!(!engine.nodes_with_substituted_records.contains(&leaving));-}-#[test]fn a_reissued_identity_holds_no_construction_facts() {use super::bridge::element_construction_fact::{IS_BODY, IS_EDITING_HOST, IS_IN_USER_AGENT_SHADOW_TREE};@@ -11886,7 +1270,7 @@ fn a_reissued_identity_holds_no_construction_facts() {);engine.retire_text_style_nodes([text]);discard_transaction(&mut engine);- engine.discard_style_transaction_outputs();+ engine.discard_style_update_outputs();let mut reissued = [0_u32; 1];engine.allocate_style_nodes(&mut reissued);assert_eq!(reissued[0], leaving.raw());@@ -11912,7 +1296,7 @@ fn a_reissued_identity_asks_for_no_particular_box() {None,);discard_transaction(&mut engine);- engine.discard_style_transaction_outputs();+ engine.discard_style_update_outputs();let mut reissued = [0_u32; 1];engine.allocate_style_nodes(&mut reissued);assert_eq!(reissued[0], leaving.raw());@@ -11937,7 +1321,7 @@ fn a_reissued_identity_has_no_replaced_content_input() {None,);discard_transaction(&mut engine);- engine.discard_style_transaction_outputs();+ engine.discard_style_update_outputs();let mut reissued = [0_u32; 1];engine.allocate_style_nodes(&mut reissued);assert_eq!(reissued[0], leaving.raw());@@ -11966,7 +1350,7 @@ fn a_text_node_holds_its_published_characters_until_its_identity_is_reissued() {assert!(engine.tree.text_is_password_input(text));engine.retire_text_style_nodes([text]);- engine.discard_style_transaction_outputs();+ engine.discard_style_update_outputs();let mut reissued = [0_u32; 1];engine.allocate_text_style_nodes(&mut reissued);assert_eq!(reissued[0], text.raw());@@ -11974,115 +1358,6 @@ fn a_text_node_holds_its_published_characters_until_its_identity_is_reissued() {assert!(!engine.tree.text_is_password_input(text));}-#[test]-fn reaction_batches_close_over_unstyled_ancestors_and_the_gaps_between_reactions() {- use super::bridge::InheritanceClosure;- let mut engine = StyleEngine::new();- let mut raw = [0_u32; 4];- engine.allocate_style_nodes(&mut raw);- let [root, outer, inner, leaf] = raw.map(|raw| StyleNodeID::from_raw(raw).unwrap());- for (child, parent) in [(outer, root), (inner, outer), (leaf, inner)] {- engine.tree.set_first_element_child(parent, Some(child));- engine.tree.set_parent(child, Some(parent));- }- let reaction = |node: StyleNodeID, gap| PublishedStyleDeltaRecord {- style_node: node.raw(),- match_answer: 0,- old_style_record: 0,- new_style_record: 0,- damage: FfiStyleDeltaDamage::None,- reaction: 0,- inherited_style_groups: 0,- pseudo_kind: u8::MAX,- gap,- uses_substitution: false,- record_reads: 0,- explicitly_inherited_groups: 0,- record_damage: 0,- owes_an_animation_plan: false,- owes_a_transition_step: false,- composed_by_the_host: false,- };- let closure =- |engine: &StyleEngine, reactions: &[PublishedStyleDeltaRecord], beside: Option<&HashSet<StyleNodeID>>| {- engine.close_over_inheritance(reactions, beside)- };-- // Every element has style: the elements between two reactions get rows of their own.- for node in [root, outer, inner, leaf] {- engine.retained.held_style_records.insert(node, 1);- }- let batch = [- reaction(root, FfiStyleDeltaGap::None),- reaction(leaf, FfiStyleDeltaGap::Materialize),- ];- assert_eq!(- closure(&engine, &batch, None),- InheritanceClosure {- gaps: vec![inner, outer],- ..Default::default()- }- );- // A reaction the engine answered as hidden inherits from nothing.- let batch = [- reaction(root, FfiStyleDeltaGap::None),- reaction(leaf, FfiStyleDeltaGap::Hidden),- ];- assert_eq!(closure(&engine, &batch, None), InheritanceClosure::default());-- // The ancestors without style a reaction inherits from compute theirs ahead of it.- engine.retained.held_style_records.remove(&outer);- engine.retained.held_style_records.remove(&inner);- let batch = [reaction(leaf, FfiStyleDeltaGap::Materialize)];- assert_eq!(- closure(&engine, &batch, None),- InheritanceClosure {- unstyled_ancestors: vec![inner, outer],- ..Default::default()- }- );-- // Draining the transaction that flew, a reaction inheriting from an element without style that arrived beside it- // is the next transaction's, and an element that arrived beside it stops the gap.- let beside = HashSet::from_iter([outer]);- assert_eq!(- closure(&engine, &batch, Some(&beside)),- InheritanceClosure {- left_to_next_transaction: HashSet::from_iter([leaf]),- ..Default::default()- }- );- engine.retained.held_style_records.insert(outer, 1);- engine.retained.held_style_records.insert(inner, 1);- let batch = [- reaction(root, FfiStyleDeltaGap::None),- reaction(leaf, FfiStyleDeltaGap::Materialize),- ];- assert_eq!(closure(&engine, &batch, Some(&beside)), InheritanceClosure::default());-- // The ancestors without style a reaction left to the next transaction went through are not in the batch, so- // they stop no gap: a reaction under a styled element below one of them gets no row for that element.- let mut raw = [0_u32; 2];- engine.allocate_style_nodes(&mut raw);- let [styled, under_styled] = raw.map(|raw| StyleNodeID::from_raw(raw).unwrap());- engine.tree.set_parent(styled, Some(inner));- engine.tree.set_parent(under_styled, Some(styled));- engine.retained.held_style_records.remove(&outer);- engine.retained.held_style_records.remove(&inner);- engine.retained.held_style_records.insert(styled, 1);- let batch = [- reaction(leaf, FfiStyleDeltaGap::Materialize),- reaction(under_styled, FfiStyleDeltaGap::Materialize),- ];- assert_eq!(- closure(&engine, &batch, Some(&HashSet::from_iter([outer]))),- InheritanceClosure {- left_to_next_transaction: HashSet::from_iter([leaf]),- ..Default::default()- }- );-}-#[test]fn inheritance_parent_keeps_the_dom_parent_of_nodes_outside_the_flat_tree() {let mut engine = StyleEngine::new();@@ -12093,23 +1368,25 @@ fn inheritance_parent_keeps_the_dom_parent_of_nodes_outside_the_flat_tree() {unreachable!()};- engine.tree.set_first_element_child(*host, Some(*assigned));- engine.tree.set_parent(*assigned, Some(*host));- engine.tree.set_next_element_sibling(*assigned, Some(*unassigned));- engine.tree.set_previous_element_sibling(*unassigned, Some(*assigned));- engine.tree.set_parent(*unassigned, Some(*host));- engine.tree.set_first_element_child(*shadow_root, Some(*wrapper));- engine.tree.set_parent(*wrapper, Some(*shadow_root));- engine.tree.set_first_element_child(*wrapper, Some(*slot));- engine.tree.set_parent(*slot, Some(*wrapper));- engine.tree.set_first_element_child(*slot, Some(*fallback));- engine.tree.set_parent(*fallback, Some(*slot));- let retained = &mut engine.retained;- retained.tree.set_shadow_root(*host, *shadow_root);- retained.tree.set_assigned_slot(*assigned, Some(*slot));- retained.tree.set_assigned_nodes(*slot, &[*assigned]);-- let tree = &engine.retained.tree;+ let projection = &mut engine.retained.projection;+ projection.set_first_element_child(*host, Some(*assigned));+ projection.set_parent(*assigned, Some(*host));+ projection.set_next_element_sibling(*assigned, Some(*unassigned));+ projection.set_previous_element_sibling(*unassigned, Some(*assigned));+ projection.set_parent(*unassigned, Some(*host));+ projection.set_first_element_child(*shadow_root, Some(*wrapper));+ projection.set_parent(*wrapper, Some(*shadow_root));+ projection.set_first_element_child(*wrapper, Some(*slot));+ projection.set_parent(*slot, Some(*wrapper));+ projection.set_first_element_child(*slot, Some(*fallback));+ projection.set_parent(*fallback, Some(*slot));+ projection.set_shadow_root(*host, *shadow_root);+ projection.set_assigned_slot(*assigned, Some(*slot));+ projection.set_assigned_nodes(*slot, &[*assigned]);+ projection.commit();+ projection.release();++ let tree = &engine.retained.projection;// A slotted element inherits from its slot, and a shadow tree's top-level element from the host.assert_eq!(tree.inheritance_parent(*assigned), Some(*slot));assert_eq!(tree.inheritance_parent(*wrapper), Some(*host));@@ -12123,103 +1400,6 @@ fn inheritance_parent_keeps_the_dom_parent_of_nodes_outside_the_flat_tree() {assert_eq!(tree.inheritance_parent(*fallback), Some(*slot));}-/// A document whose engine shares the process's user-agent selector programs, as a live engine does.-fn user_agent_sharing_document() -> StyleEngine {- let (mut engine, _) = linear_document();- engine.atoms = crate::fork::ForkShared::new(DocumentAtoms::for_test());- assert!(engine.shares_user_agent_selector_programs());- engine-}--/// Records `source` as a user-agent sheet, whose rules the identities from `first_identity` name, and publishes its-/// rules as the host does.-fn record_user_agent_sheet(engine: &mut StyleEngine, source: &str, first_identity: u64) -> SheetID {- let rules = native_rules(source);- let sheet = engine.add_sheet(StyleSheetObjectID(1), CascadeOrigin::UserAgent);- engine.attach_sheet(sheet, TreeScopeID::DOCUMENT);- engine.publish_sheet_rules(sheet.0 + 1, |engine| {- for index in 0..rules.len() {- let rule = rules.rule_at(index);- let bound = rule.matching_selectors();- let selectors: Vec<_> = bound.selectors.iter().map(|selector| selector.as_ref()).collect();- engine.add_user_agent_style_rule(sheet, None, first_identity + index as u64, &selectors, None);- }- });- sheet-}--/// The routing an engine makes when it routes every rule of `sheets` itself, once a transaction has committed them.-fn routing_built_from(engine: &StyleEngine, sheets: &[SheetID]) -> selector::RoutingRegistry {- let mut routing = selector::RoutingRegistry::new();- for &sheet in sheets {- for rule in engine.program.rules_in_sheet(sheet) {- if let Some(program) = engine.program.rule_version(rule).selector_program {- routing.add_rule(rule, program, &engine.programs);- }- }- }- routing-}--#[test]-fn later_documents_copy_the_routing_user_agent_sheets_made() {- const SHEETS: [(&str, u64); 2] = [- (".a {} .b > .c {}", 0x5541_0001_0000_0000),- ("[hidden] {} .b ~ .c {}", 0x5541_0002_0000_0000),- ];- let mut documents: Vec<_> = (0..3)- .map(|_| {- let mut engine = user_agent_sharing_document();- let sheets: Vec<_> = SHEETS- .iter()- .map(|&(source, identity)| record_user_agent_sheet(&mut engine, source, identity))- .collect();- (engine, sheets)- })- .collect();- // The first document routes both sheets itself, and the later ones take copies of what it made.- for (engine, _) in &documents[1..] {- assert!(engine.routing.is_finished_copy_of(&documents[0].0.routing));- }- for (engine, sheets) in &mut documents {- discard_transaction(engine);- assert!(engine.routing.has_routes_of(&routing_built_from(engine, sheets)));- }-}--#[test]-fn a_document_with_other_routes_routes_user_agent_rules_itself() {- const SHEET: (&str, u64) = (".d {} .e + .f {}", 0x5541_0003_0000_0000);- let mut first = user_agent_sharing_document();- let first_sheet = record_user_agent_sheet(&mut first, SHEET.0, SHEET.1);-- let mut engine = user_agent_sharing_document();- let author = engine.add_sheet(StyleSheetObjectID(2), CascadeOrigin::Author);- engine.attach_sheet(author, TreeScopeID::DOCUMENT);- let rules = native_rules(".g {}");- let rule = rules.rule_at(0);- let bound = rule.matching_selectors();- let selectors: Vec<_> = bound.selectors.iter().map(|selector| selector.as_ref()).collect();- super::bridge::publish_style_rule(- &mut engine,- author.0 + 1,- 0,- &selectors,- NamespaceScope::default(),- &super::bridge::BoundScopeChain::default(),- );- let sheet = record_user_agent_sheet(&mut engine, SHEET.0, SHEET.1);- assert!(!engine.routing.is_finished_copy_of(&first.routing));- discard_transaction(&mut first);- discard_transaction(&mut engine);- assert!(- engine- .routing- .has_routes_of(&routing_built_from(&engine, &[author, sheet]))- );- assert!(first.routing.has_routes_of(&routing_built_from(&first, &[first_sheet])));-}-#[test]fn shadow_text_line_break_language_follows_host_mutation() {use crate::layout::text_chunker::LineBreakLanguage;@@ -12233,7 +1413,7 @@ fn shadow_text_line_break_language_follows_host_mutation() {engine.record_tree_delta(shadow_root, None, Some(TreeRelations::detached(TreeScopeID(1))));engine.record_tree_delta(wrapper, None, Some(relations(Some(shadow_root.raw()), None, None)));engine.set_shadow_root(host, shadow_root);- engine.apply_staged_tree_deltas();+ engine.settle_tree_at_barrier();let mut raw_text = [0_u32; 5];engine.allocate_text_style_nodes(&mut raw_text);let [direct, wrapped, light, under_document, detached] = raw_text.map(|raw| StyleNodeID::from_raw(raw).unwrap());@@ -12341,13 +1521,13 @@ pub(super) fn staged_hover_pending_shadow_fixture() -> (StyleEngine, [StyleNodeIpub(super) fn staged_hover_shadow_fixture() -> (StyleEngine, [StyleNodeID; 10]) {let (mut engine, nodes) = staged_hover_pending_shadow_fixture();discard_transaction(&mut engine);- assert_eq!(engine.tree.parent(nodes[1]), None);- assert_eq!(engine.tree.first_element_child(nodes[0]), None);+ assert_eq!(engine.projection.parent(nodes[1]), None);+ assert_eq!(engine.projection.first_element_child(nodes[0]), None);assert_eq!(engine.tree.dom_children(nodes[0]).collect::<Vec<_>>(), vec![nodes[1]]);assert!(nodes.iter().all(|&node| engine.tree.is_live(node)));- assert_eq!(engine.tree.flat_tree_parent(nodes[6]), Some(nodes[5]));- assert_eq!(engine.tree.flat_tree_parent(nodes[4]), Some(nodes[2]));- assert_eq!(engine.tree.flat_tree_parent(nodes[9]), None);+ assert_eq!(engine.projection.flat_tree_parent(nodes[6]), Some(nodes[5]));+ assert_eq!(engine.projection.flat_tree_parent(nodes[4]), Some(nodes[2]));+ assert_eq!(engine.projection.flat_tree_parent(nodes[9]), None);(engine, nodes)}@@ -12355,13 +1535,7 @@ pub(super) fn assert_staged_hover_facts(engine: &StyleEngine, nodes: &[StyleNodelet actual: Vec<_> = nodes.iter().enumerate()- .filter_map(|(i, &node)| {- engine- .facts- .states_of_node(node)- .contains(StateFact::Hover)- .then_some(i)- })+ .filter_map(|(i, &node)| engine.projection.hover_is_placed_on(node).then_some(i)).collect();assert_eq!(actual, expected);}@@ -12382,14 +1556,14 @@ fn staged_hover_reads_pending_slot_reassignment_in_both_directions() {let mut after = before;after.assigned_slot = Some(nodes[8]);engine.record_tree_delta(nodes[6], Some(before), Some(after));- assert_eq!(engine.tree.assigned_slot_of(nodes[6]), Some(nodes[5]));+ assert_eq!(engine.projection.assigned_slot_of(nodes[6]), Some(nodes[5]));engine.set_hover(Some(nodes[6]));assert_staged_hover_facts(&engine, &nodes, &[1, 2, 4, 6, 7, 8]);engine.set_slot_assigned_nodes(nodes[5], &[]);engine.set_slot_assigned_nodes(nodes[8], &[nodes[6]]);discard_transaction(&mut engine);engine.record_tree_delta(nodes[6], Some(after), Some(before));- assert_eq!(engine.tree.assigned_slot_of(nodes[6]), Some(nodes[8]));+ assert_eq!(engine.projection.assigned_slot_of(nodes[6]), Some(nodes[8]));engine.set_hover(Some(nodes[6]));assert_staged_hover_facts(&engine, &nodes, &[1, 2, 4, 5, 6]);}@@ -12423,7 +1597,7 @@ fn staged_hover_fallback_observes_current_element_and_text_assignments() {engine.set_slot_assigned_nodes(nodes[5], &[text]);assert!(engine- .tree+ .projection.assigned_nodes_of(nodes[5]).iter().all(|node| node.text_index().is_some())@@ -12443,7 +1617,7 @@ fn staged_hover_pending_shadow_insertion_jumps_to_host() {after.tree_scope = TreeScopeID(1);engine.record_tree_delta(nodes[6], Some(before), Some(after));engine.set_slot_assigned_nodes(nodes[5], &[]);- assert_eq!(engine.tree.parent(nodes[6]), Some(nodes[2]));+ assert_eq!(engine.projection.parent(nodes[6]), Some(nodes[2]));engine.set_hover(Some(nodes[6]));assert_staged_hover_facts(&engine, &nodes, &[1, 2, 6]);}diff --git a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rsindex bbc16e22e9c..95b5867f482 100644--- a/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs+++ b/Libraries/LibWeb/Rust/src/painting/ffi/main_thread_entries.rs@@ -691,6 +691,13 @@ pub extern "C" fn render_state_hold_next_recording_for_testing() {crate::painting::recording_slot::hold_next_recording_for_testing();}+/// Keeps the Render thread from claiming the next style update that flies, until the test releases it or the host waits+/// for it, which then takes it back.+#[unsafe(no_mangle)]+pub extern "C" fn render_state_hold_next_style_flight_claim_for_testing() {+ crate::painting::recording_slot::hold_next_style_flight_claim_for_testing();+}+/// Holds the next style update that flies before it reads anything, until the test releases it or the host waits/// for it.#[unsafe(no_mangle)]diff --git a/Libraries/LibWeb/Rust/src/painting/recording_slot.rs b/Libraries/LibWeb/Rust/src/painting/recording_slot.rsindex 48370155aef..a9ae46d9fab 100644--- a/Libraries/LibWeb/Rust/src/painting/recording_slot.rs+++ b/Libraries/LibWeb/Rust/src/painting/recording_slot.rs@@ -334,6 +334,7 @@ enum RecordingHold {_parked: ParkedJob,},ArmedForStyle,+ ArmedForClaim,}static RECORDING_HOLD: Mutex<RecordingHold> = Mutex::new(RecordingHold::Idle);@@ -388,6 +389,17 @@ pub(crate) fn take_style_flight_hold_for_testing() -> bool {true}+/// Whether the style update about to fly is the one the test hold is armed to keep the Render thread from claiming.+#[cfg(not(test))]+pub(crate) fn take_style_flight_claim_hold_for_testing() -> bool {+ let mut hold = recording_hold();+ if !matches!(*hold, RecordingHold::ArmedForClaim) {+ return false;+ }+ *hold = RecordingHold::Holding;+ true+}+pub(crate) fn wait_while_recording_is_held_for_testing() {let _released = RECORDING_HOLD_RELEASED.wait_while(recording_hold(), |hold| matches!(hold, RecordingHold::Holding))@@ -407,6 +419,12 @@ pub(crate) fn hold_next_style_flight_for_testing() {*recording_hold() = RecordingHold::ArmedForStyle;}+/// Keeps the Render thread from claiming the next style update that flies until the host waits for it, which then takes+/// it back, or until [`release_held_recording_for_testing`].+pub(crate) fn hold_next_style_flight_claim_for_testing() {+ *recording_hold() = RecordingHold::ArmedForClaim;+}+/// Lets the recording held for the test go, or disarms the hold no recording has taken yet.pub(crate) fn release_held_recording_for_testing() {*recording_hold() = RecordingHold::Idle;diff --git a/Libraries/LibWeb/Rust/src/render_state.rs b/Libraries/LibWeb/Rust/src/render_state.rsindex c2ae8726028..7c76eb74687 100644--- a/Libraries/LibWeb/Rust/src/render_state.rs+++ b/Libraries/LibWeb/Rust/src/render_state.rs@@ -929,6 +929,8 @@ pub(crate) fn fly(host: &DocumentHost, job: FrameJob, _license: &crate::painting}#[cfg(not(test))]let lays_out_alone = !with_style || crate::painting::recording_slot::take_style_flight_hold_for_testing();+ #[cfg(not(test))]+ let claim_held = !lays_out_alone && crate::painting::recording_slot::take_style_flight_claim_hold_for_testing();host.note_flight_tree_depth(host.tree_depth_bound(&changes));host.let_frame_fly(|document, seed, marks| {// A host that waits for the frame says the stop word, and the frame comes back without running its round.@@ -969,6 +971,12 @@ pub(crate) fn fly(host: &DocumentHost, job: FrameJob, _license: &crate::painting// it flies with, as the stop word the waiting host says has it do on the thread.if lays_out_alone {crate::painting::recording_slot::submit_layout(run, |job| owner::hold(job))+ } else if claim_held {+ let flight = crate::stage_thread::render_thread().submit_reclaimable(run, |job| {+ crate::painting::recording_slot::wait_while_recording_is_held_for_testing();+ owner::hold(job);+ });+ (flight, true)} else {let flight = crate::stage_thread::render_thread().submit_reclaimable(run, |job| owner::hold(job));(flight, false)diff --git a/Meta/Linters/check_rust_process_wide_state.py b/Meta/Linters/check_rust_process_wide_state.pyindex a765803014c..e58bafce24e 100755--- a/Meta/Linters/check_rust_process_wide_state.py+++ b/Meta/Linters/check_rust_process_wide_state.py@@ -63,7 +63,6 @@ IN_ONE_LIBRARY = {# libweb_rust: `file:name` -> why the state is fine on a thread other than the document's.RENDER_STATE_CRATE = "Libraries/LibWeb/Rust"-STYLE_POOL = "style interning pool behind a mutex; becomes per-engine state before style runs on another thread"SCRATCH = "per-thread allocation pool; a thread without one only allocates more"DIAGNOSTIC = "counter diagnostics; off unless an environment variable turns them on"ENVIRONMENT_SWITCH = "read-once environment switch; every thread sees the same answer"@@ -78,23 +77,10 @@ def render_state_entries(reason, entries):RENDER_STATE_ALLOWED = {- **render_state_entries(- STYLE_POOL,- [- "css/style/matching.rs:DISPATCH_POOLS",- "css/style/native_rules/targets.rs:TARGET_PAGES",- "css/style/program.rs:RULE_DECLARATIONS",- "css/style/program/rule_records.rs:RULE_RECORD_PAGES",- "css/style/program/rule_versions.rs:RULE_VERSION_PAGES",- "css/style/selector.rs:ROUTING_POOLS",- "css/style/selector.rs:SELECTOR_PROGRAM_POOLS",- ],- ),**render_state_entries(SCRATCH,["css/cascaded_properties.rs:STORE_POOL",- "css/style/column.rs:STAMPED_INDEX_POOL",],),**render_state_entries(@@ -111,13 +97,6 @@ RENDER_STATE_ALLOWED = {**render_state_entries(ENVIRONMENT_SWITCH,[- "css/style/flush.rs:ENABLED",- "css/style/mod.rs:CASCADE_WINNERS",- "css/style/mod.rs:PREFIX_RELATION",- "css/style/mod.rs:PUBLISHED_STYLE_TRANSACTION",- "css/style/mod.rs:SELECTOR_TRUTH_DERIVATION",- "css/style/mod.rs:STYLE_ANSWER_PATCH",- "css/style/mod.rs:STYLE_PLAN_PROVENANCE","layout/run_repeatability.rs:ENABLED","layout/run_repeatability.rs:VERIFICATION","render_state/clock/hover.rs:LOGS",@@ -128,9 +107,6 @@ RENDER_STATE_ALLOWED = {["css/declaration_block.rs:NEXT_DECLARATION_BLOCK_IDENTITY","css/rule.rs:NEXT_RULE_IDENTITY",- "css/style/index.rs:NEXT",- "css/style/prefix.rs:NEXT",- "css/style/selector.rs:NEXT","css/style_sheet.rs:NEXT_SHEET_IDENTITY","layout/fragment_tree.rs:NEXT_IDENTITY","render_state/owner.rs:NEXT",@@ -153,20 +129,19 @@ RENDER_STATE_ALLOWED = {**render_state_entries(BUILT_ONCE,[- "css/computed_values.rs:DEFAULTS",- "css/computed_values.rs:MASKS","css/counter_representation.rs:DECIMAL","css/css_string.rs:EMPTY","css/custom_properties.rs:EMPTY","css/parser/stylesheet_cache.rs:HASHER","css/parser/stylesheet_cache.rs:KEYS","css/property_metadata.rs:SHORTHAND_LEAVES",- "css/style/publication.rs:REMAINING",+ "css/style_compute.rs:DIRECT","css/style_compute.rs:FONT_ORDER",+ "css/style_compute.rs:FONT_PHASES","css/style_compute.rs:KINDS",- "css/style_compute.rs:LONGHANDS","css/style_compute.rs:PHASE_BOUNDARIES","css/style_compute.rs:PX",+ "css/style_compute.rs:RANKS","css/style_compute.rs:REMAINING_ORDER","css/style_compute.rs:TABLE",],@@ -174,12 +149,7 @@ RENDER_STATE_ALLOWED = {**render_state_entries(LOCKED,[- "css/parser/arbitrary_substitution.rs:ATTR_NAMES_READ",- "css/parser/arbitrary_substitution.rs:ATTR_NAMES_READ_GENERATION","css/parser/stylesheet_cache.rs:CACHE",- "css/style/atoms.rs:GLOBAL_ATOMS",- "css/style/inputs.rs:CUSTOM_PROPERTY_DATA_LET_GO_BESIDE_THE_HOST",- "css/style/user_agent_selectors.rs:PROGRAMS",],),**render_state_entries(@@ -189,12 +159,18 @@ RENDER_STATE_ALLOWED = {"css/declaration_block.rs:DECLARATION_OWNER_ALLOCATIONS","css/descriptor_block.rs:DESCRIPTOR_OWNER_ALLOCATIONS","css/rule.rs:RULE_OWNER_ALLOCATIONS",- "css/style/atoms.rs:GLOBAL_ATOM_TEST_LOCK","css/style/font_resolution.rs:RESOLVES",- "css/style/mod.rs:SELECTOR_TRUTH_DERIVATION_OVERRIDE",- "css/style_compute.rs:FLY_STRINGS",- "css/style_compute.rs:FONT_CASCADE_LIST_UNREFS",- "css/style_compute.rs:NEXT",+ "css/style/pipeline/allocation_count.rs:ALLOCATIONS",+ "css/style/pipeline/allocation_count.rs:COUNTING",+ "css/style/pipeline/allocation_count.rs:LIVE_BYTES",+ "css/style/pipeline/allocation_count.rs:PRINTS_BACKTRACES",+ "css/style/pipeline/allocation_count.rs:PRINTS_BACKTRACES_CACHE",+ "css/style/pipeline/allocation_count.rs:STYLE_ALLOCATIONS",+ "css/style/pipeline/allocation_count.rs:STYLE_SECTION_DEPTH",+ "css/style/pipeline/test_support.rs:NAMES",+ "css/style_compute/ffi_test_stubs.rs:FLY_STRINGS",+ "css/style_compute/ffi_test_stubs.rs:FONT_CASCADE_LIST_UNREFS",+ "css/style_compute/ffi_test_stubs.rs:NEXT",],),f"{RENDER_STATE_CRATE}/src/css/parser/stylesheet_cache.rs:PARSE_DEPENDENCIES": "per-thread record of the parse running on this thread; scoped to that parse",@@ -204,7 +180,7 @@ RENDER_STATE_ALLOWED = {f"{RENDER_STATE_CRATE}/src/painting/recording_slot.rs:RECORDING_HOLD_RELEASED": "wakes the recording a test held once it lets it go",f"{RENDER_STATE_CRATE}/src/stage_thread.rs:THREAD_SETUP": "set once before the first stage thread starts, which runs it; read-only after",f"{RENDER_STATE_CRATE}/src/stage_thread.rs:FLIGHT_FINISHED": "set once before the first job is submitted, which a stage thread calls when one finishes; read-only after",- f"{RENDER_STATE_CRATE}/src/stage_thread.rs:STYLE_LAYOUT_THREAD": "the process's one StyleLayout thread, which every thread hands its jobs to",+ f"{RENDER_STATE_CRATE}/src/stage_thread.rs:RENDER_THREAD": "the process's one Render thread, which every thread hands its jobs to",f"{RENDER_STATE_CRATE}/src/paint_stage.rs:PAINT_THREAD": "the process's one Paint thread, which every thread hands its jobs to, and the stage only its own jobs reach",f"{RENDER_STATE_CRATE}/src/stage_thread.rs:THREAD": "test only",}diff --git a/Meta/StyleUpdateCapture/README.md b/Meta/StyleUpdateCapture/README.mdindex 776134b9657..f5a15365f1d 100644--- a/Meta/StyleUpdateCapture/README.md+++ b/Meta/StyleUpdateCapture/README.md@@ -18,9 +18,7 @@ Meta/StyleUpdateCapture/test_capture.pyTwo ledgers, each additive on its own and never to be summed with the other.`internals.styleEngineCounters()` reports cumulative microseconds at the transaction-boundary: `transactionMicroseconds` is exactly the sum of `commitMicroseconds`,-`routingPlanningMicroseconds`, `matchingCascadeMicroseconds`,-`computationPublicationMicroseconds`, `emitMicroseconds` and+boundary: `transactionMicroseconds` is exactly the sum of `commitMicroseconds` and`transactionRemainderMicroseconds`.`internals.getStyleInvalidationCounters()` reports the C++ side, where@@ -38,14 +36,7 @@ by the FFI diagnostics counters `longhandTableCopiedSlots` and `longhandTableCopThese are counts of work performed, not of output kept, and they do not depend on how fastthe machine is.-A finer set of pass clocks splits each phase into the passes a transaction actually runs-(routing setup, the routing input loop, sequence routing, the pending-route flush, batch-compilation, the winner-group version advance, the retained-answer patch, completion and the-computation loop). Reading a monotonic clock twice per pass is itself measurable on a-document that flushes often, so those are off unless `LIBWEB_STYLE_PASS_CLOCKS` is set in the-browser's environment. The phase clocks and the work counters are always on.--Documentation/Style/StyleEngine.md describes each counter and the boundary it measures.+`internals.styleCounters()` lists the counters, and `StyleCounter` in `css/style/pipeline/counters.rs` describes each.## Reading a capturediff --git a/Meta/StyleUpdateCapture/test_capture.py b/Meta/StyleUpdateCapture/test_capture.pyindex 1e306254495..97cfff05858 100755--- a/Meta/StyleUpdateCapture/test_capture.py+++ b/Meta/StyleUpdateCapture/test_capture.py@@ -27,13 +27,7 @@ def sample(amount=1):"rust": {"transactionMicroseconds": 20,"commitMicroseconds": 2,- "routingPlanningMicroseconds": 3,- "prepareMicroseconds": 1,- "matchingCascadeMicroseconds": 3,- "computationPublicationMicroseconds": 5,- "emitMicroseconds": 1,- "transactionRemainderMicroseconds": 5,- "reachedStyleNodes": 10,+ "transactionRemainderMicroseconds": 18,},"cpp": {"styleUpdateMicroseconds": 40,@@ -73,16 +67,6 @@ class CaptureTests(unittest.TestCase):row = capture.normalize(sample())self.assertEqual(row["metrics"]["rust.transactionMicroseconds"], 20)self.assertEqual(row["metrics"]["cpp.styleUpdateMicroseconds"], 40)- self.assertEqual(row["reachedNodes"], 10)-- def test_older_libraries_keep_preparation_in_matching(self):- row = sample()- for boundary in ("before", "after"):- fields = row[boundary]["rust"]- fields["matchingCascadeMicroseconds"] += fields.pop("prepareMicroseconds")- normalized = capture.normalize(row)- self.assertNotIn("rust.prepareMicroseconds", normalized["metrics"])- self.assertEqual(normalized["metrics"]["rust.matchingCascadeMicroseconds"], 4)def test_bad_partition_is_rejected(self):row = sample()diff --git a/Meta/lint-ci.sh b/Meta/lint-ci.shindex bce18e97325..82fd45bcc50 100755--- a/Meta/lint-ci.sh+++ b/Meta/lint-ci.sh@@ -41,7 +41,9 @@ for cmd in \Meta/Linters/check_libweb_realm_mentions.py \Meta/Linters/check_newlines_at_eof.py \Meta/Linters/check_png_sizes.sh \+ Meta/Linters/check_rust_address_keys.py \Meta/Linters/check_rust_process_wide_state.py \+ Meta/Linters/check_rust_style_value_arc.py \Meta/Linters/check_style.py \Meta/Linters/check_vcpkg.py \Meta/Linters/lint_executable_resources.sh \diff --git a/Meta/measure-style-amplification.py b/Meta/measure-style-amplification.pydeleted file mode 100755index ae573815a1e..00000000000--- a/Meta/measure-style-amplification.py+++ /dev/null@@ -1,479 +0,0 @@-#!/usr/bin/env python3--# Copyright (c) 2026-present, the Ladybird developers.-# SPDX-License-Identifier: BSD-2-Clause--"""Profile StyleEngine action-to-reaction amplification in all StyleBench suites."""--import argparse-import json-import os-import socket-import statistics-import subprocess-import tempfile-import time-import urllib.error-import urllib.request--from pathlib import Path--DEFAULT_WEBDRIVER = "Build/release/bin/Ladybird.app/Contents/MacOS/WebDriver"-DEFAULT_URL = "http://localhost:8000/resources/style-bench.html"-STYLE_BENCH_FLUSHES_PER_ITERATION = 26--PROFILE_SCRIPT = r"""-const suiteIndex = arguments[0];-const flushCount = arguments[1];-const mutationsPerKind = arguments[2];--function difference(after, before) {- const result = {};- for (const [name, value] of Object.entries(after)) {- const delta = value - before[name];- if (delta)- result[name] = delta;- }- return result;-}--function snapshot() {- return {- graph: internals.styleEngineCounters(),- style: internals.getStyleInvalidationCounters(),- wall: performance.now(),- };-}--function sample(before, after) {- return {- wallMicroseconds: (after.wall - before.wall) * 1000,- graph: difference(after.graph, before.graph),- style: difference(after.style, before.style),- };-}--const kinds = arguments[3] ?? "all";-const configuration = StyleBench.predefinedConfigurations()[suiteIndex];-if (!configuration)- throw new Error(`No StyleBench suite at index ${suiteIndex}`);--const setupBefore = snapshot();-const bench = createBenchmark(configuration);-bench.testRoot.offsetWidth;-const setup = sample(setupBefore, snapshot());--const flushes = [];-for (let flush = 0; flush < flushCount; ++flush) {- const before = snapshot();- if (kinds === "all" || kinds === "classes") {- bench.addClasses(mutationsPerKind);- bench.removeClasses(mutationsPerKind);- }- if (kinds === "all" || kinds === "leaves") {- bench.addLeafElements(mutationsPerKind);- bench.removeLeafElements(mutationsPerKind);- }- if (kinds === "all" || kinds === "attributes")- bench.mutateAttributes(mutationsPerKind);- bench.testRoot.offsetWidth;- flushes.push(sample(before, snapshot()));-}--// One trailing nudge so set-style counters, published at transaction start, reflect the state-// after the measured flushes.-bench.addClasses(1);-bench.testRoot.offsetWidth;--return JSON.stringify({- suite: configuration.name,- setup,- flushes,- finalAbsolute: internals.styleEngineCounters(),-});-"""---def request_json(base_url, method, path, body=None, timeout=600):- data = None if body is None else json.dumps(body).encode()- request = urllib.request.Request(- base_url + path,- data=data,- headers={"Content-Type": "application/json"},- method=method,- )- with urllib.request.urlopen(request, timeout=timeout) as response:- return json.load(response)---def unused_port():- with socket.socket() as listener:- listener.bind(("127.0.0.1", 0))- return listener.getsockname()[1]---def wait_for_webdriver(base_url, process):- for _ in range(200):- if process.poll() is not None:- raise RuntimeError("WebDriver exited before accepting connections")- try:- request_json(base_url, "GET", "/status", timeout=1)- return- except (OSError, urllib.error.URLError):- time.sleep(0.05)- raise RuntimeError("WebDriver did not accept connections within 10 seconds")---def stop_process(process):- if process.poll() is not None:- return- process.terminate()- try:- process.wait(timeout=5)- except subprocess.TimeoutExpired:- process.kill()- process.wait()---def run_profile(webdriver, url, suite_index, flushes, mutations_per_kind, kinds):- port = unused_port()- base_url = f"http://127.0.0.1:{port}"- with tempfile.TemporaryDirectory(prefix="ladybird-stylegraph-amplification-") as profiles_directory:- process = subprocess.Popen(- [- webdriver,- "--headless",- "--disable-sandbox",- "--expose-internals-object",- "--profiles-directory",- profiles_directory,- "--port",- str(port),- ],- stdout=subprocess.DEVNULL,- stderr=None if os.environ.get("STYLE_HARNESS_KEEP_STDERR") else subprocess.DEVNULL,- )- session = None- try:- wait_for_webdriver(base_url, process)- session = request_json(- base_url,- "POST",- "/session",- {"capabilities": {"alwaysMatch": {}}},- )["value"]["sessionId"]- request_json(- base_url,- "POST",- f"/session/{session}/timeouts",- {"script": 600_000, "pageLoad": 600_000},- )- request_json(base_url, "POST", f"/session/{session}/url", {"url": url})- value = request_json(- base_url,- "POST",- f"/session/{session}/execute/sync",- {- "script": PROFILE_SCRIPT,- "args": [suite_index, flushes, mutations_per_kind, kinds],- },- )["value"]- return json.loads(value)- finally:- if session is not None:- try:- request_json(base_url, "DELETE", f"/session/{session}", timeout=10)- except (OSError, urllib.error.URLError):- pass- stop_process(process)---def counter(sample, domain, name):- return sample[domain].get(name, 0)---def counters(sample, domain, names):- return sum(counter(sample, domain, name) for name in names)---def ratio(work, normalized_actions, reactions):- denominator = normalized_actions + reactions- return None if denominator == 0 else work / denominator---def stage_model(sample):- normalized_actions = counter(sample, "graph", "normalizedUniqueKeys")- selector_work = counters(- sample,- "graph",- [- "candidateChecks",- "localFeatureTests",- "stateTests",- "combinatorSteps",- "structuralTests",- "relationalTests",- "prefixCompoundsEvaluated",- "prefixConvergenceNodes",- "remainingPostingRowsInspected",- "preparedMatchingBatchCompletenessRowsInspected",- ],- )- selector_reactions = counters(- sample,- "graph",- ["selectorTruthAdditions", "selectorTruthRemovals"],- )- match_work = counters(- sample,- "graph",- [- "coldNodesEvaluated",- "ruleMatchesEmitted",- "retainedMatchAnswerDeltaEntries",- "preparedMatchingBatchRowsCloned",- ],- )- match_reactions = counter(sample, "graph", "matchAnswerChanges")- cascade_work = counter(sample, "graph", "cascadeMatchesBeforeCompaction")- cascade_reactions = counter(sample, "graph", "cascadeNodeHandlesPublished")- computed_work = counters(- sample,- "style",- ["elementStyleRecomputations", "elementInheritedStyleRecomputations"],- )- computed_reactions = counter(sample, "style", "elementComputedStyleChanges")- observer_work = counter(sample, "style", "styleEngineReactionElements")- observer_reactions = counter(sample, "style", "committedStyleObserverConsequences")- style_update_microseconds = counter(sample, "style", "styleUpdateMicroseconds")- accounted_microseconds = counters(- sample,- "style",- [- "styleEngineTransactionSetupMicroseconds",- "styleEnginePlanningMicroseconds",- ],- )- return {- "actions": {- "raw_mutation_records": counter(sample, "graph", "rawMutationRecords"),- "normalized_actions": normalized_actions,- "tree": counter(sample, "graph", "treeDeltas"),- "local_feature": counter(sample, "graph", "localFeatureDeltas"),- "state": counter(sample, "graph", "stateDeltas"),- "element_declaration": counter(sample, "graph", "elementDeclarationDeltas"),- "program": counter(sample, "graph", "programDeltas"),- "cascade_topology": counter(sample, "graph", "cascadeTopologyDeltas"),- },- "selector": {- "work_units": selector_work,- "semantic_reactions": selector_reactions,- "refresh_upqueries": counter(sample, "graph", "selectorTruthRefreshes"),- "repair_upqueries": counter(sample, "graph", "selectorTruthRepairUpqueries"),- "repair_additions": counter(sample, "graph", "selectorTruthRepairAdditions"),- "repair_removals": counter(sample, "graph", "selectorTruthRepairRemovals"),- "work_per_action_and_reaction": ratio(selector_work, normalized_actions, selector_reactions),- },- "match": {- "work_units": match_work,- "semantic_reactions": match_reactions,- "upqueries": counter(sample, "graph", "matchAnswerUpqueries"),- "work_per_action_and_reaction": ratio(match_work, normalized_actions, match_reactions),- },- "cascade": {- "work_units": cascade_work,- "published_cascade_node_handle_proxy": cascade_reactions,- "work_per_action_and_reaction": ratio(cascade_work, normalized_actions, cascade_reactions),- },- "computed": {- "element_evaluations": computed_work,- "element_output_changes": computed_reactions,- "longhand_wrappers_minted": counter(sample, "style", "longhandWrappersMinted"),- "work_per_action_and_reaction": ratio(computed_work, normalized_actions, computed_reactions),- },- "observer": {- "work_list_elements": observer_work,- "committed_consequences": observer_reactions,- "work_per_action_and_reaction": ratio(observer_work, normalized_actions, observer_reactions),- },- "published_node_provenance": {- "direct_action": counter(sample, "graph", "plannedNodesWithDirectAction"),- "signed_delta": counter(sample, "graph", "plannedNodesWithSignedDelta"),- "output_change": counter(sample, "graph", "plannedNodesWithOutputChange"),- "upquery": counter(sample, "graph", "plannedNodesWithUpquery"),- "unattributed": counter(sample, "graph", "plannedNodesUnattributed"),- },- "physical_factorization": {- "logical_region_nodes": counter(sample, "graph", "exactRegionBatchNodes"),- "physical_region_intervals": counter(sample, "graph", "exactRegionBatchIntervals"),- "match_answer_identities": counter(sample, "graph", "matchAnswerSignatures"),- "match_answer_identity_reuses": counter(sample, "graph", "matchAnswerSignatureReuses"),- "published_match_answer_records": counter(sample, "graph", "publishedMatchAnswerRecords"),- "published_match_answer_identity_reads": counter(sample, "graph", "publishedMatchAnswerIdentityReads"),- "published_match_answer_payload_consumptions": counter(sample, "graph", "publishedMatchAnswerConsumptions"),- "published_match_answer_shared_payloads": counter(sample, "graph", "publishedMatchAnswerSharedPayloads"),- "published_match_answer_shared_payload_reuses": counter(- sample, "graph", "publishedMatchAnswerSharedPayloadReuses"- ),- "published_match_answer_contextual_payloads": counter(- sample, "graph", "publishedMatchAnswerContextualPayloads"- ),- "published_match_answer_identity_repairs": counter(sample, "graph", "publishedMatchAnswerIdentityRepairs"),- "published_match_answer_identity_repair_stops": counter(- sample, "graph", "publishedMatchAnswerIdentityRepairStops"- ),- "cascade_node_handle_publications": cascade_reactions,- "cascade_states_interned": counter(sample, "graph", "cascadeStatesInterned"),- "cascade_winner_groups_interned": counter(sample, "graph", "cascadeWinnerGroupsInterned"),- "cascade_winner_entries_interned": counter(sample, "graph", "cascadeWinnerEntriesInterned"),- "shared_style_computations": counter(sample, "style", "elementStyleSharedComputations"),- },- "typed_gaps": {- "selector_truth_refreshes": counter(sample, "graph", "selectorTruthRefreshes"),- "selector_truth_repair_upqueries": counter(sample, "graph", "selectorTruthRepairUpqueries"),- "match_answer_upqueries": counter(sample, "graph", "matchAnswerUpqueries"),- "cold_batch_missing_rows": counter(sample, "graph", "coldMatchingBatchMissingRows"),- "prefix_convergence_upqueries": counter(sample, "graph", "prefixConvergenceUpqueries"),- "unattributed_published_nodes": counter(sample, "graph", "plannedNodesUnattributed"),- },- "timing_microseconds": {- "wall": sample["wallMicroseconds"],- "style_update": style_update_microseconds,- "transaction_setup": counter(sample, "style", "styleEngineTransactionSetupMicroseconds"),- "planning": counter(sample, "style", "styleEnginePlanningMicroseconds"),- "cascade": counter(sample, "style", "styleCascadeMicroseconds"),- "computed_values": counter(sample, "style", "styleValuesMicroseconds"),- "accounted_operator_total": accounted_microseconds,- "outside_accounted_operators": max(0, style_update_microseconds - accounted_microseconds),- },- }---def add_samples(samples):- result = {"wallMicroseconds": 0, "graph": {}, "style": {}}- for sample in samples:- result["wallMicroseconds"] += sample["wallMicroseconds"]- for domain in ["graph", "style"]:- for name, value in sample[domain].items():- result[domain][name] = result[domain].get(name, 0) + value- return result---def timing_summary(samples, name):- values = [counter(sample, "style", name) for sample in samples]- return {- "minimum": min(values),- "median": statistics.median(values),- "maximum": max(values),- }---def summarize_suite(profiles, target_flushes, include_raw_profiles):- setup_samples = [profile["setup"] for profile in profiles]- flush_samples = [sample for profile in profiles for sample in profile["flushes"]]- aggregate_setup = add_samples(setup_samples)- aggregate_flushes = add_samples(flush_samples)- average_setup_style_time = counter(aggregate_setup, "style", "styleUpdateMicroseconds") / len(setup_samples)- average_flush_style_time = counter(aggregate_flushes, "style", "styleUpdateMicroseconds") / len(flush_samples)- result = {- "setup": stage_model(aggregate_setup),- "mutation_flushes": stage_model(aggregate_flushes),- "flush_count": len(flush_samples),- "style_update_microseconds_per_flush": timing_summary(flush_samples, "styleUpdateMicroseconds"),- "projected_current_pipeline_iteration_microseconds": average_setup_style_time- + average_flush_style_time * target_flushes,- }- if include_raw_profiles:- result["raw_profiles"] = profiles- return result---def main():- parser = argparse.ArgumentParser(description=__doc__)- parser.add_argument("--webdriver", default=DEFAULT_WEBDRIVER, help="WebDriver executable")- parser.add_argument("--url", default=DEFAULT_URL, help="StyleBench runner URL")- parser.add_argument("--iterations", type=int, default=1, help="fresh processes per suite")- parser.add_argument("--flushes", type=int, default=5, help="measured mutation flushes per process")- parser.add_argument("--mutations-per-kind", type=int, default=10, help="mutations of each kind per flush")- parser.add_argument(- "--kinds",- choices=("all", "classes", "leaves", "attributes"),- default="all",- help="which mutation kinds each measured flush performs",- )- parser.add_argument(- "--target-flushes-per-suite",- type=int,- default=STYLE_BENCH_FLUSHES_PER_ITERATION,- help="flush count used for the current-pipeline iteration projection",- )- parser.add_argument(- "--include-raw-profiles",- action="store_true",- help="include every nonzero raw counter delta in the JSON output",- )- parser.add_argument(- "--suite-indexes",- type=lambda text: [int(part) for part in text.split(",")],- default=list(range(6)),- help="comma-separated StyleBench suite indexes to measure (default all six)",- )- parser.add_argument("--output", type=Path, help="also write the JSON result to this path")- args = parser.parse_args()-- if min(args.iterations, args.flushes, args.mutations_per_kind, args.target_flushes_per_suite) < 1:- parser.error("iteration, flush, mutation, and target-flush counts must be positive")- webdriver = str(Path(args.webdriver).resolve())- if not Path(webdriver).is_file():- parser.error(f"WebDriver executable not found: {webdriver}")-- by_suite = {}- for suite_index in args.suite_indexes:- profiles = []- for iteration in range(args.iterations):- print(f"Running suite {suite_index + 1}/6, iteration {iteration + 1}/{args.iterations}...", flush=True)- profiles.append(- run_profile(- webdriver,- args.url,- suite_index,- args.flushes,- args.mutations_per_kind,- args.kinds,- )- )- suite_name = profiles[0]["suite"]- by_suite[suite_name] = summarize_suite(- profiles,- args.target_flushes_per_suite,- args.include_raw_profiles,- )-- result = {- "webdriver": webdriver,- "url": args.url,- "iterations_per_suite": args.iterations,- "measured_flushes_per_iteration": args.flushes,- "mutations_per_kind": args.mutations_per_kind,- "target_flushes_per_suite": args.target_flushes_per_suite,- "projected_current_pipeline_six_suite_iteration_microseconds": sum(- suite["projected_current_pipeline_iteration_microseconds"] for suite in by_suite.values()- ),- "coverage_gaps": [- "derived feedback actions and stabilization passes do not exist before Phase 6",- "cascadeNodeHandlesPublished is a physical publication proxy, not complete semantic winner changes",- "computed-value counters are per element, not per property dependency evaluation and change",- "StyleRecord assignment and change identities do not exist before Phase 5",- "transition, animation, and stabilization reactions do not exist before Phase 6",- "bulk distinct work is represented by setup totals until the Phase 8 bulk plan exists",- ],- "by_suite": by_suite,- }- encoded = json.dumps(result, indent=2)- print(encoded)- if args.output:- args.output.write_text(encoded + "\n")---if __name__ == "__main__":- main()diff --git a/Meta/measure-style-scale.py b/Meta/measure-style-scale.pyindex 0c17d72cb39..45b5523d8de 100644--- a/Meta/measure-style-scale.py+++ b/Meta/measure-style-scale.py@@ -20,47 +20,13 @@ from pathlib import PathDEFAULT_WEBDRIVER = "Build/release/bin/Ladybird.app/Contents/MacOS/WebDriver"-GRAPH_COUNTERS = [+MATCHING_COUNTERS = ["normalizedUniqueKeys",- "routedEntryPoints",- "candidateChecks",- "localFeatureTests",- "combinatorSteps",- "structuralTests",- "coldNodesEvaluated",- "selectorTruthAdditions",- "selectorTruthRemovals",- "selectorTruthRefreshes",- "matchAnswerChanges",- "matchAnswerUpqueries",- "retainedMatchAnswerReuses",- "retainedMatchAnswerRefusals",- "retainedMatchAnswerPatches",- "retainedMatchAnswerDeltaPatches",- "retainedMatchAnswerFilteredPatches",- "retainedMatchAnswerPatchMisses",- "retainedPatchesUnattributed",- "retainedPatchesPoisoned",- "retainedPatchesCoarseCovered",- "tier3BenefitEvictions",- "remainingPostingRowsCopied",- "remainingPostingRowsInspected",- "preparedMatchingBatchCompletenessRowsInspected",- "preparedMatchingBatchRowsCloned",- "invalidatedStyleNodes",- "plannedNodesWithDirectAction",- "plannedNodesWithSignedDelta",- "plannedNodesWithOutputChange",- "plannedNodesWithUpquery",- "plannedNodesUnattributed",]STYLE_COUNTERS = ["styleEngineReactionElements","styleEnginePublishedReactions",- "elementStyleRecomputations",- "elementComputedStyleChanges",- "committedStyleObserverConsequences",]BENCHMARK_SCRIPT = r"""@@ -204,7 +170,7 @@ def run_iteration(webdriver, document_size, cycles, warmup_cycles):f"/session/{session}/execute/sync",{"script": BENCHMARK_SCRIPT,- "args": [document_size, cycles, warmup_cycles, GRAPH_COUNTERS, STYLE_COUNTERS],+ "args": [document_size, cycles, warmup_cycles, MATCHING_COUNTERS, STYLE_COUNTERS],},)["value"]return json.loads(value)@@ -234,7 +200,7 @@ def summarize(values):def summarize_size(iterations):samples = [sample for iteration in iterations for sample in iteration]- graph = {name: sorted(set(sample["graph"][name] for sample in samples)) for name in GRAPH_COUNTERS}+ graph = {name: sorted(set(sample["graph"][name] for sample in samples)) for name in MATCHING_COUNTERS}style = {name: sorted(set(sample["style"][name] for sample in samples)) for name in STYLE_COUNTERS}nonzero_graph = {name: valuesdiff --git a/Meta/style-update-capture.py b/Meta/style-update-capture.pyindex db6ed1468cf..a0900d74af6 100755--- a/Meta/style-update-capture.py+++ b/Meta/style-update-capture.py@@ -51,11 +51,6 @@ PHASES = {"transactionMicroseconds",["commitMicroseconds",- "routingPlanningMicroseconds",- "prepareMicroseconds",- "matchingCascadeMicroseconds",- "computationPublicationMicroseconds",- "emitMicroseconds","transactionRemainderMicroseconds",],),@@ -271,17 +266,12 @@ def difference(before, after):def normalize(sample):delta = difference(sample["before"], sample["after"])for lane, (whole, phases) in PHASES.items():- # Older saved libraries include preparation in routing/matching instead of naming it.- phases = [key for key in phases if key != "prepareMicroseconds" or key in delta[lane]]values = [delta[lane][key] for key in [whole, *phases]]if any(value < 0 or int(value) != value for value in values) or sum(values[1:]) != values[0]:raise RuntimeError(f"Non-additive {lane} clocks in {sample['name']}: {values}")sample["counters"] = deltasample["metrics"] = {- f"{lane}.{key}": delta[lane][key]- for lane, (whole, phases) in PHASES.items()- for key in [whole, *phases]- if key != "prepareMicroseconds" or key in delta[lane]+ f"{lane}.{key}": delta[lane][key] for lane, (whole, phases) in PHASES.items() for key in [whole, *phases]}# Optional pass clocks sit alongside the phases in the same lanes. compare() leaves every# microsecond counter out of its counter diff, so each clock has to reach the metrics to be read.@@ -299,7 +289,6 @@ def normalize(sample):for key in ["mutationMicroseconds", "observationMicroseconds", "cpuMicroseconds", "rssBytes"]})- sample["reachedNodes"] = delta["rust"]["reachedStyleNodes"]return samplediff --git a/Tests/LibWeb/Text/expected/HTML/frame-in-flight/style-flight-taken-back-lets-its-rendering-update-go-on.txt b/Tests/LibWeb/Text/expected/HTML/frame-in-flight/style-flight-taken-back-lets-its-rendering-update-go-on.txtnew file mode 100644index 00000000000..47177fb9e36--- /dev/null+++ b/Tests/LibWeb/Text/expected/HTML/frame-in-flight/style-flight-taken-back-lets-its-rendering-update-go-on.txt@@ -0,0 +1,3 @@+state beside the frame: in-flight+color the read sees: rgb(0, 128, 0)+the animation frame callback randiff --git a/Tests/LibWeb/Text/expected/css/style-memory/bytes-of-worker-caches.txt b/Tests/LibWeb/Text/expected/css/style-memory/bytes-of-worker-caches.txtnew file mode 100644index 00000000000..1be3b1af56a--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-memory/bytes-of-worker-caches.txt@@ -0,0 +1,2 @@+2000 elements: within 65536 per thread+10000 elements: within 65536 per threaddiff --git a/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-animated-element.txt b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-animated-element.txtnew file mode 100644index 00000000000..e54fad7fad2--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-animated-element.txt@@ -0,0 +1,58 @@+animation: 500 elements+ initial: within 0+ ruleStore: within 0+ ruleIndex: within 0+ userAgentIndex: within 0+ sheetSegments: within 0+ sharedDeclarations: within 0+ invalidation: within 0+ specifiedValues: within 0+ records: within 456+ payloads: within 656+ groupValueFacts: within 0+ customProperties: within 0+ retainedSlots: within 36+ recordCells: within 4+ installed: within 100+ projection: within 52+ hostTree: within 24+ elementDeclarations: within 0+ heldRecordMaps: within 12+ layoutStyleColumns: within 28+ otherMaps: within 0+ styleValues: within 0+ animationEffects: within 388+ fontResolutions: within 0+ cssAnimations: within 320+ hostMemo: within 180+ cppInstalledStyles: within 8+ cppHintProperties: within 0+transition: 500 elements+ initial: within 0+ ruleStore: within 0+ ruleIndex: within 0+ userAgentIndex: within 0+ sheetSegments: within 0+ sharedDeclarations: within 0+ invalidation: within 0+ specifiedValues: within 0+ records: within 456+ payloads: within 352+ groupValueFacts: within 0+ customProperties: within 0+ retainedSlots: within 36+ recordCells: within 4+ installed: within 88+ projection: within 52+ hostTree: within 24+ elementDeclarations: within 0+ heldRecordMaps: within 12+ layoutStyleColumns: within 0+ otherMaps: within 0+ styleValues: within 0+ animationEffects: within 456+ fontResolutions: within 0+ cssAnimations: within 0+ hostMemo: within 248+ cppInstalledStyles: within 8+ cppHintProperties: within 0diff --git a/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-at-rule-by-owner.txt b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-at-rule-by-owner.txtnew file mode 100644index 00000000000..232ba1f8c8d--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-at-rule-by-owner.txt@@ -0,0 +1,35 @@+@media that holds:+ ruleStore: within 76+ ruleIndex: within 56+ sheetSegments: within 240+ invalidation: within 0+ sharedDeclarations: within 40+ animationEffects: within 0+@media that fails:+ ruleStore: within 68+ ruleIndex: within 0+ sheetSegments: within 0+ invalidation: within 0+ sharedDeclarations: within 40+ animationEffects: within 0+@layer:+ ruleStore: within 84+ ruleIndex: within 60+ sheetSegments: within 240+ invalidation: within 0+ sharedDeclarations: within 40+ animationEffects: within 0+@container:+ ruleStore: within 60+ ruleIndex: within 196+ sheetSegments: within 240+ invalidation: within 0+ sharedDeclarations: within 40+ animationEffects: within 0+@keyframes:+ ruleStore: within 116+ ruleIndex: within 0+ sheetSegments: within 0+ invalidation: within 0+ sharedDeclarations: within 0+ animationEffects: within 0diff --git a/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-document-by-owner.txt b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-document-by-owner.txtnew file mode 100644index 00000000000..9d0a23e26c4--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-document-by-owner.txt@@ -0,0 +1,29 @@+initial: within 6216+ruleStore: within 1216+ruleIndex: within 1520+userAgentIndex: within 149568+sheetSegments: within 0+sharedDeclarations: within 14592+invalidation: within 904+specifiedValues: within 0+records: within 1552+payloads: within 7120+groupValueFacts: within 672+customProperties: within 0+retainedSlots: within 540+recordCells: within 112+installed: within 1320+projection: within 5216+hostTree: within 4672+elementDeclarations: within 16+heldRecordMaps: within 1168+layoutStyleColumns: within 104+otherMaps: within 88+styleValues: within 3632+animationEffects: within 0+fontResolutions: within 712+liveScratch: within 1936+cssAnimations: within 0+hostMemo: within 256+cppInstalledStyles: within 24+cppHintProperties: within 0diff --git a/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-element-by-owner.txt b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-element-by-owner.txtnew file mode 100644index 00000000000..6e417f462e1--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-element-by-owner.txt@@ -0,0 +1,174 @@+shared: 500 elements, 500 styled+ initial: within 0+ ruleStore: within 0+ ruleIndex: within 0+ userAgentIndex: within 0+ sheetSegments: within 0+ sharedDeclarations: within 0+ invalidation: within 0+ specifiedValues: within 0+ records: within 4+ payloads: within 4+ groupValueFacts: within 4+ customProperties: within 0+ retainedSlots: within 36+ recordCells: within 4+ installed: within 20+ projection: within 52+ hostTree: within 24+ elementDeclarations: within 0+ heldRecordMaps: within 12+ layoutStyleColumns: within 28+ otherMaps: within 0+ styleValues: within 4+ animationEffects: within 0+ fontResolutions: within 0+ cssAnimations: within 0+ hostMemo: within 0+ cppInstalledStyles: within 8+ cppHintProperties: within 0+custom: 500 elements, 500 styled+ initial: within 0+ ruleStore: within 0+ ruleIndex: within 0+ userAgentIndex: within 0+ sheetSegments: within 0+ sharedDeclarations: within 0+ invalidation: within 0+ specifiedValues: within 0+ records: within 312+ payloads: within 164+ groupValueFacts: within 4+ customProperties: within 280+ retainedSlots: within 36+ recordCells: within 0+ installed: within 48+ projection: within 52+ hostTree: within 24+ elementDeclarations: within 80+ heldRecordMaps: within 12+ layoutStyleColumns: within 0+ otherMaps: within 0+ styleValues: within 108+ animationEffects: within 0+ fontResolutions: within 0+ cssAnimations: within 0+ hostMemo: within 36+ cppInstalledStyles: within 8+ cppHintProperties: within 0+unique: 500 elements, 500 styled+ initial: within 0+ ruleStore: within 0+ ruleIndex: within 0+ userAgentIndex: within 0+ sheetSegments: within 0+ sharedDeclarations: within 0+ invalidation: within 0+ specifiedValues: within 32+ records: within 92+ payloads: within 164+ groupValueFacts: within 4+ customProperties: within 0+ retainedSlots: within 36+ recordCells: within 0+ installed: within 40+ projection: within 52+ hostTree: within 24+ elementDeclarations: within 40+ heldRecordMaps: within 12+ layoutStyleColumns: within 0+ otherMaps: within 0+ styleValues: within 0+ animationEffects: within 0+ fontResolutions: within 0+ cssAnimations: within 0+ hostMemo: within 0+ cppInstalledStyles: within 8+ cppHintProperties: within 0+uniqueFont: 500 elements, 500 styled+ initial: within 0+ ruleStore: within 0+ ruleIndex: within 0+ userAgentIndex: within 0+ sheetSegments: within 0+ sharedDeclarations: within 0+ invalidation: within 0+ specifiedValues: within 68+ records: within 160+ payloads: within 340+ groupValueFacts: within 4+ customProperties: within 0+ retainedSlots: within 36+ recordCells: within 0+ installed: within 20+ projection: within 52+ hostTree: within 24+ elementDeclarations: within 40+ heldRecordMaps: within 12+ layoutStyleColumns: within 208+ otherMaps: within 0+ styleValues: within 28+ animationEffects: within 0+ fontResolutions: within 244+ cssAnimations: within 0+ hostMemo: within 0+ cppInstalledStyles: within 8+ cppHintProperties: within 0+uniqueVisual: 500 elements, 500 styled+ initial: within 0+ ruleStore: within 0+ ruleIndex: within 0+ userAgentIndex: within 0+ sheetSegments: within 0+ sharedDeclarations: within 0+ invalidation: within 0+ specifiedValues: within 0+ records: within 156+ payloads: within 188+ groupValueFacts: within 4+ customProperties: within 0+ retainedSlots: within 36+ recordCells: within 0+ installed: within 60+ projection: within 52+ hostTree: within 24+ elementDeclarations: within 40+ heldRecordMaps: within 12+ layoutStyleColumns: within 0+ otherMaps: within 0+ styleValues: within 180+ animationEffects: within 0+ fontResolutions: within 0+ cssAnimations: within 0+ hostMemo: within 0+ cppInstalledStyles: within 8+ cppHintProperties: within 0+substituted: 500 elements, 500 styled+ initial: within 0+ ruleStore: within 0+ ruleIndex: within 0+ userAgentIndex: within 0+ sheetSegments: within 0+ sharedDeclarations: within 0+ invalidation: within 0+ specifiedValues: within 0+ records: within 312+ payloads: within 164+ groupValueFacts: within 4+ customProperties: within 448+ retainedSlots: within 36+ recordCells: within 0+ installed: within 16+ projection: within 44+ hostTree: within 24+ elementDeclarations: within 80+ heldRecordMaps: within 12+ layoutStyleColumns: within 0+ otherMaps: within 0+ styleValues: within 124+ animationEffects: within 0+ fontResolutions: within 0+ cssAnimations: within 0+ hostMemo: within 72+ cppInstalledStyles: within 8+ cppHintProperties: within 0diff --git a/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-element-reading-style-text.txt b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-element-reading-style-text.txtnew file mode 100644index 00000000000..975c42013f2--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-element-reading-style-text.txt@@ -0,0 +1,2 @@+projection: within 148+hostMemo: within 52diff --git a/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-element-with-hints.txt b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-element-with-hints.txtnew file mode 100644index 00000000000..1237747020a--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-element-with-hints.txt@@ -0,0 +1,21 @@+repeated:+ specifiedValues: within 4+ elementDeclarations: within 12+ styleValues: within 4+ records: within 4+ payloads: within 4+ cppHintProperties: within 16+repeated two:+ specifiedValues: within 4+ elementDeclarations: within 12+ styleValues: within 4+ records: within 4+ payloads: within 4+ cppHintProperties: within 32+unique:+ specifiedValues: within 32+ elementDeclarations: within 40+ styleValues: within 92+ records: within 160+ payloads: within 320+ cppHintProperties: within 16diff --git a/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-rule-by-owner.txt b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-rule-by-owner.txtnew file mode 100644index 00000000000..2f34578ba56--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-rule-by-owner.txt@@ -0,0 +1,38 @@+document:+ ruleStore: within 1216+ ruleIndex: within 2520+ userAgentIndex: within 149568+ sheetSegments: within 0+ invalidation: within 880+ specifiedValues: within 0+ styleValues: within 4224+class:+ ruleStore: within 80+ ruleIndex: within 24+ userAgentIndex: within 0+ sheetSegments: within 56+ invalidation: within 8+ specifiedValues: within 0+ sharedDeclarations: within 40+ styleValues: within 8+ total: within 184+descendant:+ ruleStore: within 72+ ruleIndex: within 24+ userAgentIndex: within 0+ sheetSegments: within 344+ invalidation: within 8+ specifiedValues: within 0+ sharedDeclarations: within 40+ styleValues: within 0+ total: within 460+selector list:+ ruleStore: within 72+ ruleIndex: within 24+ userAgentIndex: within 0+ sheetSegments: within 112+ invalidation: within 8+ specifiedValues: within 0+ sharedDeclarations: within 40+ styleValues: within 8+ total: within 224diff --git a/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-selector-by-owner.txt b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-selector-by-owner.txtnew file mode 100644index 00000000000..8530ca54f0d--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-memory/bytes-per-selector-by-owner.txt@@ -0,0 +1,50 @@+class:+ ruleStore: within 80+ ruleIndex: within 64+ userAgentIndex: within 0+ sheetSegments: within 248+ invalidation: within 8+ specifiedValues: within 0+ sharedDeclarations: within 8+ styleValues: within 0+ total: within 392+descendant:+ ruleStore: within 72+ ruleIndex: within 64+ userAgentIndex: within 0+ sheetSegments: within 424+ invalidation: within 8+ specifiedValues: within 0+ sharedDeclarations: within 8+ styleValues: within 0+ total: within 568+is:+ ruleStore: within 72+ ruleIndex: within 64+ userAgentIndex: within 0+ sheetSegments: within 408+ invalidation: within 8+ specifiedValues: within 0+ sharedDeclarations: within 8+ styleValues: within 0+ total: within 544+selector list:+ ruleStore: within 72+ ruleIndex: within 104+ userAgentIndex: within 0+ sheetSegments: within 488+ invalidation: within 8+ specifiedValues: within 0+ sharedDeclarations: within 8+ styleValues: within 0+ total: within 664+descendant, media print:+ ruleStore: within 72+ ruleIndex: within 0+ userAgentIndex: within 0+ sheetSegments: within 0+ invalidation: within 0+ specifiedValues: within 0+ sharedDeclarations: within 8+ styleValues: within 0+ total: within 80diff --git a/Tests/LibWeb/Text/expected/css/style-memory/inline-style-rewrites-keep-specified-values-bounded.txt b/Tests/LibWeb/Text/expected/css/style-memory/inline-style-rewrites-keep-specified-values-bounded.txtnew file mode 100644index 00000000000..e1f05d8473f--- /dev/null+++ b/Tests/LibWeb/Text/expected/css/style-memory/inline-style-rewrites-keep-specified-values-bounded.txt@@ -0,0 +1 @@+bounded: truediff --git a/Tests/LibWeb/Text/input/HTML/frame-in-flight/style-flight-taken-back-lets-its-rendering-update-go-on.html b/Tests/LibWeb/Text/input/HTML/frame-in-flight/style-flight-taken-back-lets-its-rendering-update-go-on.htmlnew file mode 100644index 00000000000..20c34686724--- /dev/null+++ b/Tests/LibWeb/Text/input/HTML/frame-in-flight/style-flight-taken-back-lets-its-rendering-update-go-on.html@@ -0,0 +1,33 @@+<!DOCTYPE html>+<script src="../../include.js"></script>+<script src="frame-in-flight.js"></script>+<iframe id="frame" srcdoc="<div id=inner>child</div>"></iframe>+<script>+ // A task of the container runs beside the child's style update in flight, ahead of the next rendering task, which+ // waits behind the update until it has finished. The task's read takes the style update back from the Render thread,+ // which has not begun it, so that no thread lands it. Nothing else follows that would bring the event loop around to+ // finish the update, which has to happen for the animation frame callback to run.+ asyncTest(async done => {+ if (!frame.contentDocument?.getElementById("inner"))+ await new Promise(resolve => frame.addEventListener("load", resolve, { once: true }));+ const inner = frame.contentDocument.getElementById("inner");+ await twoFramesLanded();++ requestAnimationFrame(() => {+ internals.holdNextFrame("claim");+ internals.setManualRenderingOpportunities(true);+ inner.style.color = "rgb(0, 128, 0)";+ setTimeout(() => {+ println(`state beside the frame: ${internals.frameSchedulerState()}`);+ window.onmessage = () => println(`color the read sees: ${frame.contentWindow.getComputedStyle(inner).color}`);+ window.postMessage(null, "*");+ requestAnimationFrame(() => {+ internals.setManualRenderingOpportunities(false);+ println("the animation frame callback ran");+ done();+ });+ internals.injectRenderingOpportunity(performance.now());+ }, 0);+ });+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/style-memory/bytes-of-worker-caches.html b/Tests/LibWeb/Text/input/css/style-memory/bytes-of-worker-caches.htmlnew file mode 100644index 00000000000..d339bb07058--- /dev/null+++ b/Tests/LibWeb/Text/input/css/style-memory/bytes-of-worker-caches.html@@ -0,0 +1,35 @@+<!doctype html>+<body>+<script src="../../include.js"></script>+<script>+ // What the caches of the style threads keep from one pass to the next, which the other style memory tests leave out+ // as depending on which thread styled what last: it has to stay bounded however many groups a page makes.+ function workerCaches() {+ document.body.offsetWidth;+ return internals.styleMemoryReport().owners.workerCaches;+ }++ function addElements(count) {+ const container = document.createElement("div");+ for (let index = 0; index < count; ++index) {+ const element = document.createElement("div");+ element.style.width = `${document.body.childElementCount}.${index}px`;+ element.style.color = `rgb(${index % 256}, ${index >> 8}, 7)`;+ container.appendChild(element);+ }+ document.body.appendChild(container);+ }++ // Bytes a thread may keep, and the threads a pass runs on at most.+ const budgetPerThread = 65536;+ const maxThreads = 16;++ test(() => {+ addElements(2000);+ const small = workerCaches();+ addElements(8000);+ const large = workerCaches();+ for (const [name, bytes] of [["2000 elements", small], ["10000 elements", large]])+ println(`${name}: ${bytes <= budgetPerThread * maxThreads ? "within" : `OVER (${bytes})`} ${budgetPerThread} per thread`);+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/style-memory/bytes-per-animated-element.html b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-animated-element.htmlnew file mode 100644index 00000000000..86d1d8e1bdb--- /dev/null+++ b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-animated-element.html@@ -0,0 +1,116 @@+<!doctype html>+<style>+ @keyframes fade {+ from { opacity: 0.25; }+ to { opacity: 0.75; }+ }+ .animated {+ animation: fade 10s linear infinite paused;+ }+ .transitioning {+ transition: opacity 1000s linear;+ }+ .transitioning.faded {+ opacity: 0.5;+ }+</style>+<body>+<script src="../../include.js"></script>+<script>+ // The style memory each animated element adds, by owner: the report on a page of 1000 elements running one paused+ // CSS animation of one @keyframes rule, or one CSS transition, less the one on the same page of 500, over the 500+ // elements between.+ function report() {+ document.body.offsetWidth;+ return internals.styleMemoryReport();+ }++ // NB: Each page's elements go in a container of their own, beside those of the pages before, so that every+ // element takes a slot no element held before.+ function slopes(makeElements) {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const reports = [];+ for (const count of [500, 1000]) {+ makeElements(container, count);+ reports.push(report());+ }+ const elements = reports[1].elements - reports[0].elements;+ const slopes = {};+ for (const owner in reports[1].owners)+ slopes[owner] = (reports[1].owners[owner] - reports[0].owners[owner]) / elements;+ return { elements, slopes };+ }++ // Bytes per animated element each owner may add, which a change that grows an owner past has to raise.+ // - animationEffects: describes each running animation for sampling (its effect, beside the keyframes it shares+ // with every element running the same @keyframes rule).+ // - cssAnimations: each CSS animation's name and applied definition.+ // - hostMemo: the versions of the effects the host described to the engine.+ const animationBudgets = {+ records: 456,+ payloads: 656,+ retainedSlots: 36,+ recordCells: 4,+ installed: 100,+ projection: 52,+ hostTree: 24,+ heldRecordMaps: 12,+ layoutStyleColumns: 28,+ animationEffects: 388,+ cssAnimations: 320,+ hostMemo: 180,+ cppInstalledStyles: 8,+ };+ const transitionBudgets = {+ records: 456,+ payloads: 352,+ retainedSlots: 36,+ recordCells: 4,+ installed: 88,+ projection: 52,+ hostTree: 24,+ heldRecordMaps: 12,+ animationEffects: 456,+ hostMemo: 248,+ cppInstalledStyles: 8,+ };++ // NB: What a transaction in flight holds of earlier generations, and what the style threads keep for the next+ // pass, depend on when the report runs and on which passes ran last, which running transitions decide.+ const transientOwners = ["projectionGenerations", "workerCaches", "liveScratch"];++ function check(name, result, budgets) {+ println(`${name}: ${result.elements} elements`);+ for (const owner in result.slopes) {+ if (transientOwners.includes(owner))+ continue;+ const slope = result.slopes[owner];+ const budget = budgets[owner] ?? 0;+ println(` ${owner}: ${slope.toFixed(1) <= budget ? "within" : `OVER (${slope.toFixed(1)})`} ${budget}`);+ }+ }++ test(() => {+ check("animation", slopes((container, count) => {+ while (container.childElementCount < count) {+ const element = document.createElement("div");+ element.className = "animated";+ container.appendChild(element);+ }+ }), animationBudgets);+ // Each element is styled once before it fades, so that the fade starts a transition.+ check("transition", slopes((container, count) => {+ const added = [];+ while (container.childElementCount < count) {+ const element = document.createElement("div");+ element.className = "transitioning";+ container.appendChild(element);+ added.push(element);+ }+ document.body.offsetWidth;+ for (const element of added)+ element.classList.add("faded");+ }), transitionBudgets);+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/style-memory/bytes-per-at-rule-by-owner.html b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-at-rule-by-owner.htmlnew file mode 100644index 00000000000..8f87626e4b1--- /dev/null+++ b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-at-rule-by-owner.html@@ -0,0 +1,58 @@+<!doctype html>+<style id="rules"></style>+<body>+<div class="a1"><span class="b1">x</span></div>+<script src="../../include.js"></script>+<script>+ // What the style engine holds per at-rule, by owner: the report with 1000 at-rules in the sheet, less the one with+ // 500, over the 500 at-rules between. Each holds one style rule, or two keyframes, with values no other page declares.+ const owners = ["ruleStore", "ruleIndex", "sheetSegments", "invalidation", "sharedDeclarations", "animationEffects"];++ function report() {+ document.body.offsetWidth;+ return internals.styleMemoryReport();+ }++ function slopes(makeRule) {+ const sheet = document.getElementById("rules");+ const reports = [];+ for (const count of [500, 1000]) {+ let text = "";+ for (let index = 0; index < count; ++index)+ text += makeRule(index) + "\n";+ sheet.textContent = text;+ reports.push(report());+ }+ const slopes = {};+ for (const owner of owners)+ slopes[owner] = (reports[1].owners[owner] - reports[0].owners[owner]) / 500;+ return slopes;+ }++ function check(name, slopes, budgets) {+ println(`${name}:`);+ for (const owner of owners) {+ const budget = budgets[owner] ?? 0;+ const slope = slopes[owner];+ println(` ${owner}: ${slope.toFixed(1) <= budget ? "within" : `OVER (${slope.toFixed(1)})`} ${budget}`);+ }+ }++ // Bytes per at-rule each owner may add, which a change that grows an owner past has to raise.+ const budgets = {+ mediaHolds: { ruleStore: 76, ruleIndex: 56, sheetSegments: 240, sharedDeclarations: 40 },+ // NB: A rule under a condition that fails takes no place in the index until the condition holds.+ mediaFails: { ruleStore: 68, sharedDeclarations: 40 },+ layer: { ruleStore: 84, ruleIndex: 60, sheetSegments: 240, sharedDeclarations: 40 },+ container: { ruleStore: 60, ruleIndex: 196, sheetSegments: 240, sharedDeclarations: 40 },+ keyframes: { ruleStore: 116 },+ };++ test(() => {+ check("@media that holds", slopes(index => `@media (min-width: ${index + 1}px), screen { .m${index} { padding-top: ${index}.0625px; } }`), budgets.mediaHolds);+ check("@media that fails", slopes(index => `@media print and (min-width: ${index + 1}px) { .p${index} { padding-top: ${index}.1875px; } }`), budgets.mediaFails);+ check("@layer", slopes(index => `@layer l${index} { .l${index} { padding-top: ${index}.3125px; } }`), budgets.layer);+ check("@container", slopes(index => `@container (min-width: ${index + 1}px) { .c${index} { padding-top: ${index}.4375px; } }`), budgets.container);+ check("@keyframes", slopes(index => `@keyframes k${index} { from { padding-top: ${index}.5625px; } to { padding-top: ${index}.6875px; } }`), budgets.keyframes);+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/style-memory/bytes-per-document-by-owner.html b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-document-by-owner.htmlnew file mode 100644index 00000000000..1b96db04245--- /dev/null+++ b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-document-by-owner.html@@ -0,0 +1,74 @@+<!doctype html>+<body>+<script src="../../include.js"></script>+<script>+ // The style memory a frame's document holds, by owner: the reports of blank same-origin iframes, each of whose+ // documents has an engine of its own. The mean over the second and third frame is what one more frame adds.+ // NB: A document's report counts what its engine shares with the other engines of the process, such as the user+ // agent rules, as its own.+ function frameLoaded(iframe) {+ return new Promise(resolve => iframe.addEventListener("load", resolve, { once: true }));+ }++ function report(iframe) {+ iframe.contentDocument.body.offsetWidth;+ return iframe.contentWindow.internals.styleMemoryReport();+ }++ // Bytes per document each owner may hold, which a change that grows an owner past has to raise.+ const budgets = {+ initial: 6216,+ ruleStore: 1216,+ ruleIndex: 1520,+ // NB: The user agent rules' index, which the engines of the process share and each document's report counts.+ userAgentIndex: 149568,+ sharedDeclarations: 14592,+ invalidation: 904,+ records: 1552,+ payloads: 7120,+ groupValueFacts: 672,+ retainedSlots: 540,+ recordCells: 112,+ installed: 1320,+ projection: 5216,+ hostTree: 4672,+ elementDeclarations: 16,+ heldRecordMaps: 1168,+ layoutStyleColumns: 104,+ otherMaps: 88,+ styleValues: 3632,+ // NB: The resolution of the initial font.+ fontResolutions: 712,+ // NB: The slots of the scratch each style thread keeps, of which only the calling thread's is made here, and+ // the first chunk of restyle hints with its group.+ liveScratch: 1936,+ // NB: The host's memo of the record views it read, which grows with the views it is told.+ hostMemo: 256,+ cppInstalledStyles: 24,+ };++ // NB: What a transaction in flight holds of earlier generations, and the groups the style threads keep for the+ // next pass, depend on when the report runs and on which threads styled what last.+ const transientOwners = ["projectionGenerations", "workerCaches"];++ asyncTest(async done => {+ const frames = [];+ for (let index = 0; index < 3; ++index) {+ const iframe = document.createElement("iframe");+ iframe.srcdoc = "<!doctype html><body>";+ const loaded = frameLoaded(iframe);+ document.body.appendChild(iframe);+ await loaded;+ frames.push(iframe);+ }+ const reports = frames.map(report);+ for (const owner in reports[1].owners) {+ if (transientOwners.includes(owner))+ continue;+ const bytes = (reports[1].owners[owner] + reports[2].owners[owner]) / 2;+ const budget = budgets[owner] ?? 0;+ println(`${owner}: ${bytes <= budget ? "within" : `OVER (${bytes.toFixed(0)})`} ${budget}`);+ }+ done();+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/style-memory/bytes-per-element-by-owner.html b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-element-by-owner.htmlnew file mode 100644index 00000000000..09654008ac0--- /dev/null+++ b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-element-by-owner.html@@ -0,0 +1,210 @@+<!doctype html>+<style>+ .item {+ color: green;+ margin: 1px;+ }+</style>+<body>+<script src="../../include.js"></script>+<script>+ // The style memory each element adds, by owner: the report on a flat page of 1000 elements, less the one on the+ // same page of 500, over the 500 elements between. Per-document costs cancel out.+ function report() {+ document.body.offsetWidth;+ return internals.styleMemoryReport();+ }++ // NB: Each page's elements go in a container of their own, beside those of the pages before,+ // so that every element takes a slot no element held before.+ function slopes(makeElement) {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const reports = [];+ for (const count of [500, 1000]) {+ while (container.childElementCount < count)+ container.appendChild(makeElement(container.childElementCount));+ reports.push(report());+ }+ const elements = reports[1].elements - reports[0].elements;+ const slopes = {};+ for (const owner in reports[1].owners)+ slopes[owner] = (reports[1].owners[owner] - reports[0].owners[owner]) / elements;+ return {+ elements,+ styledElements: reports[1].styledElements - reports[0].styledElements,+ slopes,+ };+ }++ // Bytes per element each owner may add, which a change that grows an owner past has to raise.+ // - records, payloads, groupValueFacts: the computed style and its group data.+ // - retainedSlots, recordCells, installed, heldRecordMaps: which style an element holds.+ // - layoutStyleColumns: the layout object's style pointer.+ // - styleValues, specifiedValues, elementDeclarations: the inline style property set.+ // - customProperties: the inherited variables map.+ // - projection: a row per element: tag, flags, host facts, states, interned fact lists pointer, dispatch bloom and+ // element links.+ // - hostTree: the DOM child sequence (text nodes included) and unique node id of each node.+ // - hostMemo: the atoms of the names the host interned, here each element's style attribute text, and the+ // environments the engine holds.+ const sharedBudgets = {+ records: 4,+ payloads: 4,+ groupValueFacts: 4,+ retainedSlots: 36,+ recordCells: 4,+ installed: 20,+ projection: 52,+ hostTree: 24,+ heldRecordMaps: 12,+ layoutStyleColumns: 28,+ styleValues: 4,+ cppInstalledStyles: 8,+ };+ const customBudgets = {+ records: 312,+ payloads: 164,+ groupValueFacts: 4,+ customProperties: 280,+ retainedSlots: 36,+ installed: 48,+ projection: 52,+ hostTree: 24,+ elementDeclarations: 80,+ heldRecordMaps: 12,+ styleValues: 108,+ hostMemo: 36,+ cppInstalledStyles: 8,+ };+ const substitutedBudgets = {+ records: 312,+ payloads: 164,+ groupValueFacts: 4,+ customProperties: 448,+ retainedSlots: 36,+ installed: 16,+ projection: 44,+ hostTree: 24,+ elementDeclarations: 80,+ heldRecordMaps: 12,+ styleValues: 124,+ hostMemo: 72,+ cppInstalledStyles: 8,+ };+ const uniqueBudgets = {+ specifiedValues: 32,+ records: 92,+ payloads: 164,+ groupValueFacts: 4,+ retainedSlots: 36,+ installed: 40,+ projection: 52,+ hostTree: 24,+ elementDeclarations: 40,+ heldRecordMaps: 12,+ cppInstalledStyles: 8,+ };++ const uniqueFontBudgets = {+ specifiedValues: 68,+ records: 160,+ payloads: 340,+ groupValueFacts: 4,+ retainedSlots: 36,+ installed: 20,+ projection: 52,+ hostTree: 24,+ elementDeclarations: 40,+ heldRecordMaps: 12,+ // NB: The layout node arena's per-node columns double their capacity within this page's range of slots.+ layoutStyleColumns: 208,+ styleValues: 28,+ // NB: A resolution per distinct font request, which another engine keys a font fallback list by a ~168 B+ // font description for: ours holds the request once, in a list that doubles its capacity.+ fontResolutions: 244,+ cppInstalledStyles: 8,+ };++ const uniqueVisualBudgets = {+ records: 156,+ payloads: 188,+ groupValueFacts: 4,+ retainedSlots: 36,+ installed: 60,+ projection: 52,+ hostTree: 24,+ elementDeclarations: 40,+ heldRecordMaps: 12,+ styleValues: 180,+ cppInstalledStyles: 8,+ };++ // NB: The caches the style threads keep for the next pass hold a few hundred groups whatever the page holds, and+ // how many depends on which threads styled what last. The scratch the engine keeps between passes, a dirty+ // bit and an install mark per element slot among it, grows in vectors that double their capacity as the last+ // passes needed, which the timing of those passes decides.+ const transientOwners = ["projectionGenerations", "workerCaches", "liveScratch"];++ // NB: An attr() that can read the style attribute, in any document this process styled before this one, makes every+ // document keep each element's text of it, which bytes-per-element-reading-style-text covers. Where one ran, what+ // that text adds to these owners is not this page's to bound.++ // NB: Elements styled on different threads can each make a value or record of the same style.+ const slack = 1;++ function check(name, result, budgets) {+ println(`${name}: ${result.elements} elements, ${result.styledElements} styled`);+ for (const owner in result.slopes) {+ // NB: What a transaction in flight holds of earlier generations depends on when the report runs.+ if (transientOwners.includes(owner))+ continue;+ const slope = result.slopes[owner];+ const budget = budgets[owner] ?? 0;+ println(` ${owner}: ${slope.toFixed(1) <= budget + slack ? "within" : `OVER (${slope.toFixed(1)})`} ${budget}`);+ }+ }++ test(() => {+ check("shared", slopes(() => {+ const element = document.createElement("div");+ element.className = "item";+ return element;+ }), sharedBudgets);+ check("custom", slopes(index => {+ const element = document.createElement("div");+ element.className = "item";+ element.style.setProperty("--size", `${index}px`);+ element.style.setProperty("--name", "x");+ element.style.width = "var(--size)";+ return element;+ }), customBudgets);+ check("unique", slopes(index => {+ const element = document.createElement("div");+ element.className = "item";+ element.style.width = `${index}px`;+ return element;+ }), uniqueBudgets);+ check("uniqueFont", slopes(index => {+ const element = document.createElement("div");+ element.className = "item";+ element.style.fontFamily = `f${index}`;+ return element;+ }), uniqueFontBudgets);+ // NB: Each element owns a set of the groups of what it paints, which those of the other pages share.+ check("uniqueVisual", slopes(index => {+ const element = document.createElement("div");+ element.className = "item";+ element.style.backgroundColor = `rgb(${index % 256}, ${index >> 8}, 0)`;+ return element;+ }), uniqueVisualBudgets);+ check("substituted", slopes(index => {+ const element = document.createElement("div");+ element.className = "item";+ element.style.setProperty("--size", `${index}px`);+ element.style.setProperty("--alias", "var(--size)");+ element.style.width = "var(--alias)";+ return element;+ }), substitutedBudgets);+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/style-memory/bytes-per-element-reading-style-text.html b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-element-reading-style-text.htmlnew file mode 100644index 00000000000..a31fe646598--- /dev/null+++ b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-element-reading-style-text.html@@ -0,0 +1,38 @@+<!doctype html>+<style>+ /* NB: A selector reading what the style attribute spells keeps a reference to each element's text of it. */+ [style*="never-written"] {+ color: red;+ }+</style>+<body>+<script src="../../include.js"></script>+<script>+ // What it costs an element that something reads its style attribute's text, by the owners holding that text: the+ // report on a page of 1000 elements, less the one on the same page of 500, over the 500 elements between.+ function report() {+ document.body.offsetWidth;+ return internals.styleMemoryReport();+ }++ const budgets = {+ projection: 148,+ hostMemo: 52,+ };++ test(() => {+ const reports = [];+ for (const count of [500, 1000]) {+ while (document.body.childElementCount < count + 1) {+ const element = document.createElement("div");+ element.style.width = `${document.body.childElementCount}px`;+ document.body.appendChild(element);+ }+ reports.push(report());+ }+ for (const owner in budgets) {+ const slope = (reports[1].owners[owner] - reports[0].owners[owner]) / 500;+ println(`${owner}: ${slope.toFixed(1) <= budgets[owner] ? "within" : `OVER (${slope.toFixed(1)})`} ${budgets[owner]}`);+ }+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/style-memory/bytes-per-element-with-hints.html b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-element-with-hints.htmlnew file mode 100644index 00000000000..f3cf708ab55--- /dev/null+++ b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-element-with-hints.html@@ -0,0 +1,88 @@+<!doctype html>+<body>+<script src="../../include.js"></script>+<script>+ // The style memory each element with a presentational hint adds, by owner: the report on a page of 1000 elements,+ // less the one on the same page of 500, over the 500 elements between.+ function report() {+ document.body.offsetWidth;+ return internals.styleMemoryReport();+ }++ function slopes(makeElement) {+ const container = document.createElement("div");+ document.body.appendChild(container);+ const reports = [];+ for (const count of [500, 1000]) {+ while (container.childElementCount < count)+ container.appendChild(makeElement(container.childElementCount));+ reports.push(report());+ }+ const elements = reports[1].elements - reports[0].elements;+ const slopes = {};+ for (const owner in reports[1].owners)+ slopes[owner] = (reports[1].owners[owner] - reports[0].owners[owner]) / elements;+ return slopes;+ }++ // Bytes per element each owner may add, which a change that grows an owner past has to raise. Only the owners a+ // hint can move are listed: bytes-per-element-by-owner bounds the rest.+ const hintOwners = [+ "specifiedValues",+ "elementDeclarations",+ "styleValues",+ "records",+ "payloads",+ "cppHintProperties",+ ];+ // NB: The engine holds elements with equal hints on one row. What each holds of its own is the C++ list of the hints+ // it published, which only tells a republication that nothing moved.+ const repeatedBudgets = {+ specifiedValues: 4,+ elementDeclarations: 12,+ styleValues: 4,+ records: 4,+ payloads: 4,+ cppHintProperties: 16,+ };+ const repeatedTwoBudgets = {+ ...repeatedBudgets,+ cppHintProperties: 32,+ };+ const uniqueBudgets = {+ specifiedValues: 32,+ elementDeclarations: 40,+ styleValues: 92,+ records: 160,+ payloads: 320,+ cppHintProperties: 16,+ };++ function check(name, slopes, budgets) {+ println(`${name}:`);+ for (const owner of hintOwners) {+ const slope = slopes[owner];+ const budget = budgets[owner];+ println(` ${owner}: ${slope.toFixed(1) <= budget ? "within" : `OVER (${slope.toFixed(1)})`} ${budget}`);+ }+ }++ test(() => {+ check("repeated", slopes(() => {+ const element = document.createElement("font");+ element.setAttribute("color", "red");+ return element;+ }), repeatedBudgets);+ check("repeated two", slopes(() => {+ const element = document.createElement("table");+ element.setAttribute("bgcolor", "green");+ element.setAttribute("width", "50");+ return element;+ }), repeatedTwoBudgets);+ check("unique", slopes(index => {+ const element = document.createElement("font");+ element.setAttribute("color", `#${(index + 0x100000).toString(16)}`);+ return element;+ }), uniqueBudgets);+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/style-memory/bytes-per-rule-by-owner.html b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-rule-by-owner.htmlnew file mode 100644index 00000000000..550d0420dbf--- /dev/null+++ b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-rule-by-owner.html@@ -0,0 +1,128 @@+<!doctype html>+<style id="rules"></style>+<body>+<div class="a1"><span class="b1">x</span></div>+<script src="../../include.js"></script>+<script>+ // The rule memory each style rule adds, by owner: the report with 1000 rules in the sheet, less the one with 500,+ // over the 500 rules between. Per-document costs cancel out. The rules declare values no other test declares, which+ // the process interns for this page alone whatever ran before it.+ const ruleOwners = [+ "ruleStore",+ "ruleIndex",+ "userAgentIndex",+ "sheetSegments",+ "invalidation",+ "specifiedValues",+ "sharedDeclarations",+ "styleValues",+ ];++ function report() {+ document.body.offsetWidth;+ return internals.styleMemoryReport();+ }++ function slopes(makeRule) {+ const sheet = document.getElementById("rules");+ const reports = [];+ for (const count of [500, 1000]) {+ let text = "";+ for (let index = 0; index < count; ++index)+ text += makeRule(index) + "\n";+ sheet.textContent = text;+ reports.push(report());+ }+ const slopes = {};+ for (const owner of ruleOwners)+ slopes[owner] = (reports[1].owners[owner] - reports[0].owners[owner]) / 500;+ return slopes;+ }++ // The rule memory of a document with no rules of its own, by owner: what every document pays for the user agent's.+ function checkDocument(budgets) {+ document.getElementById("rules").textContent = "";+ const owners = report().owners;+ println("document:");+ for (const owner of ruleOwners) {+ // NB: The declarations of the documents the process styled before are not this one.+ if (owner === "sharedDeclarations")+ continue;+ const bytes = owners[owner];+ const budget = budgets[owner] ?? 0;+ println(` ${owner}: ${bytes <= budget ? "within" : `OVER (${bytes})`} ${budget}`);+ }+ }++ function check(name, slopes, budgets) {+ println(`${name}:`);+ let total = 0;+ for (const owner of ruleOwners) {+ const slope = slopes[owner];+ total += slope;+ const budget = budgets[owner] ?? 0;+ println(` ${owner}: ${slope.toFixed(1) <= budget ? "within" : `OVER (${slope.toFixed(1)})`} ${budget}`);+ }+ const budget = budgets.total ?? 0;+ println(` total: ${total <= budget ? "within" : `OVER (${total.toFixed(1)})`} ${budget}`);+ }++ // Bytes per rule each owner may add, which a change that grows an owner past has to raise.+ // The declarations are the process's, which every document reaching the same sheet shares, and which the+ // documents a process styled before can only lower, where they interned some of the same values.+ const classBudgets = {+ ruleStore: 80,+ ruleIndex: 24,+ invalidation: 8,+ sheetSegments: 56,+ sharedDeclarations: 40,+ styleValues: 8,+ total: 184,+ };+ const descendantBudgets = {+ ruleStore: 72,+ ruleIndex: 24,+ invalidation: 8,+ sheetSegments: 344,+ sharedDeclarations: 40,+ total: 460,+ };+ const listBudgets = {+ styleValues: 8,+ ruleStore: 72,+ ruleIndex: 24,+ invalidation: 8,+ sheetSegments: 112,+ sharedDeclarations: 40,+ total: 224,+ };+ // Bytes of a document with no rules of its own each owner may hold.+ // NB: The user agent index owner counts the rules of every user agent sheet the process published so far, which+ // depends on what ran in the process before: the budget is for all of them.+ const documentBudgets = {+ ruleStore: 1216,+ ruleIndex: 2520,+ userAgentIndex: 149568,+ invalidation: 880,+ styleValues: 4224,+ };++ test(() => {+ checkDocument(documentBudgets);+ check(+ "class",+ slopes(index => `.c${index} { color: rgb(${index % 256}, 3, 7); margin-left: ${index}.375px; }`),+ classBudgets+ );+ check(+ "descendant",+ slopes(index => `.a${index} .b${index} > span { padding-top: ${index}.625px; }`),+ descendantBudgets+ );+ check(+ "selector list",+ slopes(index => `.a${index}, .b${index} { padding-bottom: ${index}.125px; }`),+ listBudgets+ );+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/style-memory/bytes-per-selector-by-owner.html b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-selector-by-owner.htmlnew file mode 100644index 00000000000..a7e3359366f--- /dev/null+++ b/Tests/LibWeb/Text/input/css/style-memory/bytes-per-selector-by-owner.html@@ -0,0 +1,103 @@+<!doctype html>+<style id="rules"></style>+<body>+<div class="a1"><span class="b1">x</span></div>+<script src="../../include.js"></script>+<script>+ // The memory each selector shape adds to the document, by owner: the report with 1000 rules in the sheet, less+ // the one with 500, over the 500 rules between. Every rule declares the same block, which the sheet shares between+ // them, so what a rule adds is what its selector costs the rule store, the rule index and invalidation.+ const owners = [+ "ruleStore",+ "ruleIndex",+ "userAgentIndex",+ "sheetSegments",+ "invalidation",+ "specifiedValues",+ "sharedDeclarations",+ "styleValues",+ ];++ function report() {+ document.body.offsetWidth;+ return internals.styleMemoryReport();+ }++ function slopes(makeSelector, media = "all") {+ const sheet = document.getElementById("rules");+ sheet.media = media;+ const reports = [];+ for (const count of [500, 1000]) {+ let text = "";+ for (let index = 0; index < count; ++index)+ text += `${makeSelector(index)} { color: green }\n`;+ sheet.textContent = text;+ reports.push(report());+ }+ const slopes = {};+ for (const owner of owners)+ slopes[owner] = (reports[1].owners[owner] - reports[0].owners[owner]) / 500;+ return slopes;+ }++ function check(name, slopes, budgets) {+ println(`${name}:`);+ let total = 0;+ for (const owner of owners) {+ const slope = slopes[owner];+ total += slope;+ const budget = budgets[owner] ?? 0;+ println(` ${owner}: ${slope.toFixed(1) <= budget ? "within" : `OVER (${slope.toFixed(1)})`} ${budget}`);+ }+ const budget = budgets.total ?? 0;+ println(` total: ${total <= budget ? "within" : `OVER (${total.toFixed(1)})`} ${budget}`);+ }++ // Bytes per selector each owner may add, which a change that grows an owner past has to raise.+ const classBudgets = {+ ruleStore: 80,+ ruleIndex: 64,+ invalidation: 8,+ sheetSegments: 248,+ sharedDeclarations: 8,+ total: 392,+ };+ const descendantBudgets = {+ ruleStore: 72,+ ruleIndex: 64,+ invalidation: 8,+ sheetSegments: 424,+ sharedDeclarations: 8,+ total: 568,+ };+ const isBudgets = {+ ruleStore: 72,+ ruleIndex: 64,+ invalidation: 8,+ sheetSegments: 408,+ sharedDeclarations: 8,+ total: 544,+ };+ const printBudgets = {+ ruleStore: 72,+ sharedDeclarations: 8,+ total: 80,+ };+ const listBudgets = {+ ruleStore: 72,+ ruleIndex: 104,+ invalidation: 8,+ sheetSegments: 488,+ sharedDeclarations: 8,+ total: 664,+ };++ test(() => {+ check("class", slopes(index => `.c${index}`), classBudgets);+ check("descendant", slopes(index => `.a${index} .b${index} > span`), descendantBudgets);+ check("is", slopes(index => `:is(.x${index}, .y${index}) .z${index}`), isBudgets);+ check("selector list", slopes(index => `.a${index}, .b${index}`), listBudgets);+ // A sheet whose media does not apply indexes nothing, but its rules still hold what they compiled.+ check("descendant, media print", slopes(index => `.a${index} .b${index} > span`, "print"), printBudgets);+ });+</script>diff --git a/Tests/LibWeb/Text/input/css/style-memory/inline-style-rewrites-keep-specified-values-bounded.html b/Tests/LibWeb/Text/input/css/style-memory/inline-style-rewrites-keep-specified-values-bounded.htmlnew file mode 100644index 00000000000..c1e743777a7--- /dev/null+++ b/Tests/LibWeb/Text/input/css/style-memory/inline-style-rewrites-keep-specified-values-bounded.html@@ -0,0 +1,26 @@+<!doctype html>+<body>+<div id="target"></div>+<script src="../../include.js"></script>+<script>+ // Every write of an inline style interns its value. Once no declaration names a value, the table lets go of it,+ // so a script rewriting one inline style holds the table to what the document declares: the most it holds while+ // the script writes its last values is no more than the most it held while it wrote its first.+ test(() => {+ let written = 0;+ const peakWhileRewriting = count => {+ let peak = 0;+ for (let i = 0; i < count; ++i) {+ target.style.width = `${++written}px`;+ target.offsetWidth;+ if (i % 250 === 0)+ peak = Math.max(peak, internals.styleMemoryReport().owners.specifiedValues);+ }+ return peak;+ };+ const first = peakWhileRewriting(3000);+ peakWhileRewriting(3000);+ const last = peakWhileRewriting(3000);+ println(`bounded: ${last <= first * 1.25}`);+ });+</script>diff --git a/Tests/LibWeb/test-web/Application.cpp b/Tests/LibWeb/test-web/Application.cppindex af4b7030b8f..6cc7b26db14 100644--- a/Tests/LibWeb/test-web/Application.cpp+++ b/Tests/LibWeb/test-web/Application.cpp@@ -85,15 +85,10 @@ void Application::create_platform_arguments(Core::ArgsParser& args_parser)void Application::create_platform_options(WebView::BrowserOptions& browser_options, WebView::RequestServerOptions& request_server_options, WebView::WebContentOptions& web_content_options){if (verify_style) {- static constexpr Array verification_variables {- "LIBWEB_VERIFY_STYLE_PLAN_PROVENANCE"sv,- "LIBWEB_VERIFY_PUBLISHED_STYLE_TRANSACTION"sv,- "LIBWEB_VERIFY_STYLE_ANSWER_PATCH"sv,- "LIBWEB_VERIFY_CASCADE_WINNERS"sv,- "LIBWEB_VERIFY_PREFIX_RELATION"sv,- };- for (auto variable : verification_variables)- MUST(Core::Environment::set(variable, "1"sv, Core::Environment::Overwrite::Yes));+ // NB: The style engine checks what it installed against a cold computation of the document.+ MUST(Core::Environment::set("LIBWEB_STYLE_SELFCHECK"sv, "1"sv, Core::Environment::Overwrite::Yes));+ // NB: A cold computation per update takes a large document's test past the usual timeout.+ per_test_timeout_in_seconds = max(per_test_timeout_in_seconds, 180);}browser_options.headless_mode = WebView::HeadlessMode::Test;browser_options.disable_sql_database = WebView::DisableSQLDatabase::Yes;