Truly independent web browser
LibWeb: Keep matched declarations from one style pass to the next
Andreas Kling76bd0922e195
diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/counters.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/counters.rsindex f287db14625..18e585368dc 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/counters.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/counters.rs@@ -50,8 +50,9 @@ pub(in super::super) enum StyleCounter {/// 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.+ /// The elements passes gave the record of an element that matched the same rules and declared+ /// the same declarations, under a parent they inherit the same from, which they matched but+ /// did not cascade or compute.ReusedElements,/// The rule indexes the engine built: one as it started, and one for each pass after a rule/// change.diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/differential_tests.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/differential_tests.rsindex 0b6004c56ab..39a74d97413 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/differential_tests.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/differential_tests.rs@@ -122,6 +122,33 @@ fn losing_rule_source(index: usize) -> String {format!("{selector} {{ {declaration}; }}")}+/// The style rule of `index` for the matched declarations workload: the shapes of [`rule_source`],+/// with declarations whose computed values read the parent, the document's root or each other.+fn matched_declarations_rule_source(index: usize) -> String {+ let a = class_name(index % CLASSES);+ let b = class_name((index + 3) % CLASSES);+ let selector = match index % 3 {+ 0 => format!(".{a}"),+ 1 => format!(".{a} .{b}"),+ _ => format!(".{a} > .{b}"),+ };+ let declaration = match index % 12 {+ 0 => format!("font-size: {}px", 8 + 4 * index),+ 1 => "width: 2em".to_owned(),+ 2 => format!("color: rgb({}, 0, 0)", 16 * index),+ 3 => "background-color: currentcolor".to_owned(),+ 4 => format!("--width: {}px", 1 + index),+ 5 => "height: var(--width, 3px)".to_owned(),+ 6 => "width: inherit".to_owned(),+ 7 => "padding-top: 1rem".to_owned(),+ 8 => "font-size: larger".to_owned(),+ 9 => "margin-inline-start: 2em".to_owned(),+ 10 => "writing-mode: vertical-rl".to_owned(),+ _ => "display: revert".to_owned(),+ };+ format!("{selector} {{ {declaration}; }}")+}+/// 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()`.@@ -539,6 +566,20 @@ fn seeded_transactions_restyle_rules_that_lose_as_a_cold_pass_does() {}}+#[test]+fn seeded_transactions_restyle_what_matched_declarations_read_as_a_cold_pass_does() {+ for seed_index in 0..seeds() {+ run_seed(seed_index, matched_declarations_rule_source);+ }+}++#[test]+fn seeded_transactions_restyle_what_matched_declarations_read_alike_on_one_thread_and_on_several() {+ for seed_index in 0..seeds() {+ run_seed_on_one_thread_and_on_several(seed_index, matched_declarations_rule_source);+ }+}+#[test]fn seeded_transactions_restyle_has_anchors_as_a_cold_pass_does() {for seed_index in 0..seeds() {diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rsindex ed266c861cd..65281a7fab5 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/live.rs@@ -165,6 +165,11 @@ struct LiveScratch {memos: super::pool::PerThread<FollowScratch>,/// The group caches the passes keep for the next, by thread, for the threads that styled.groups: super::pool::PerThread<super::compute::GroupCache>,+ /// The matched declarations cache the passes keep for the next.+ matched_declarations: super::matched_declarations::MatchedDeclarationsCache,+ /// The inputs of the document the entries of the matched declarations cache read, as they+ /// were when the last pass started.+ matched_declarations_inputs: Option<MatchedDeclarationsInputs>,/// The DOM order version of the tree the memos measured where siblings stand in, where the/// transaction they measured it for moved no element, so the tree before it was the same.memos_dom_order_version: Option<u64>,@@ -414,7 +419,45 @@ impl InitialStyleInputs {}}+/// What every computation may read of the document, which the elements reading it are restyled for+/// as it moves, and the entries of the matched declarations cache do not hold on to: what the+/// initial style computes from, the viewport, the color schemes, the custom property registrations+/// and what a `url()` resolves against.+#[derive(Clone, Copy, PartialEq, Eq)]+struct MatchedDeclarationsInputs {+ initial_style: InitialStyleInputs,+ in_quirks_mode: bool,+ viewport: [u64; 2],+ preferred_color_scheme: u8,+ supported_color_schemes: Option<(u8, [u8; 4])>,+ custom_property_registration_generation: u64,+ style_sheet_resource_contexts_version: u64,+}++impl MatchedDeclarationsInputs {+ fn of(inputs: &super::super::bridge::FfiDocumentStyleComputationInputs) -> Self {+ Self {+ initial_style: InitialStyleInputs::of(inputs),+ in_quirks_mode: inputs.in_quirks_mode,+ viewport: [inputs.viewport_width.to_bits(), inputs.viewport_height.to_bits()],+ preferred_color_scheme: inputs.preferred_color_scheme,+ supported_color_schemes: inputs.has_document_supported_schemes.then_some((+ inputs.document_supported_scheme_count,+ inputs.document_supported_scheme_codes,+ )),+ custom_property_registration_generation: inputs.custom_property_registration_generation,+ style_sheet_resource_contexts_version: inputs.style_sheet_resource_contexts_version,+ }+ }+}+impl Live {+ /// The matched declarations cache the passes keep for the next.+ #[cfg(test)]+ pub(super) fn matched_declarations(&self) -> &super::matched_declarations::MatchedDeclarationsCache {+ &self.scratch.matched_declarations+ }+/// Counts the rule data, initial style and records the engine holds, by owner. Rule data/// and initial style come first, as every record shares their groups and declarations.pub(in super::super) fn report_memory(&self, report: &mut MemoryReport) {@@ -460,6 +503,7 @@ impl Live {+ vec_bytes(&self.kept_hidden)+ vec_bytes(&self.scratch.kept),);+ self.scratch.matched_declarations.report_memory(report);for cache in self.scratch.groups.made() {cache.lock()@@ -493,6 +537,12 @@ impl Live {if transaction.restyles_everything {self.pending_everything = true;}+ if transaction.restyles_everything+ || !transaction.environment.is_empty()+ || !transaction.rule_changes.is_empty()+ {+ self.scratch.matched_declarations.forget();+ }let changes = state.projection.changes();if transaction.has_no_element_inputs() && changes.is_empty() && transaction.rule_changes.is_empty() {return;@@ -684,6 +734,7 @@ impl Live {/// A record computed while its scope had no registry names none, though its style reads one,/// so what a record names is compared with what it would name now.fn note_counter_style_environment_moved(&mut self, state: &RetainedState) {+ self.scratch.matched_declarations.forget();self.restyle_records_where(state, |_, target, record| {record.rare().counter_style_environment_identity!= state.values_counter_style_environment_identity(target, |property| record.effective_value(property))@@ -747,6 +798,7 @@ impl Live {if names.is_empty() {return;}+ self.scratch.matched_declarations.forget();let raw: HashSet<usize> = names.iter().map(ak::Utf16FlyString::raw_identity).collect();let texts: Vec<std::borrow::Cow<'_, [u16]>> = names.iter().map(ak::Utf16FlyString::to_utf16).collect();self.restyle_records_where(state, |records, target, record| {@@ -857,6 +909,7 @@ impl Live {/// they compute: those whose custom properties call a custom function, or whose longhands/// substitute something that may.fn note_custom_functions_moved(&mut self, state: &RetainedState) {+ self.scratch.matched_declarations.forget();self.restyle_records_where(state, |_, _, record| {record.rare().custom_property_reads == LonghandCustomPropertyReads::Any|| record.custom_declarations().is_some_and(|declarations| {@@ -1938,6 +1991,15 @@ impl Live {let changed_sheets = std::mem::take(&mut self.changed_sheets);let reordered_scopes = std::mem::take(&mut self.reordered_scopes);let layered_scopes = std::mem::take(&mut self.layered_scopes);+ let matched_declarations_inputs = MatchedDeclarationsInputs::of(&state.document_style_computation_inputs);+ if rebuilds_index+ || updates_index+ || self.scratch.matched_declarations_inputs != Some(matched_declarations_inputs)+ {+ self.scratch.matched_declarations.forget();+ self.scratch.matched_declarations_inputs = Some(matched_declarations_inputs);+ }+ self.scratch.matched_declarations.prepare(slot_count);if rebuilds_index {self.rebuild_index(state);} else if updates_index {@@ -2074,6 +2136,7 @@ impl Live {keeps_matches: true,suspends: true,group_caches: Some(&self.scratch.groups),+ kept_matched_declarations: Some(&self.scratch.matched_declarations),cache_audit: self.cache_audit,root_font: root_font.map_or_else(Default::default, std::sync::OnceLock::from),root_font_moved: root_font_moved.map_or_else(Default::default, std::sync::OnceLock::from),diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/matched_declarations.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/matched_declarations.rsnew file mode 100644index 00000000000..d864e3d7620--- /dev/null+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/matched_declarations.rs@@ -0,0 +1,1085 @@+/*+ * Copyright (c) 2026-present, the Ladybird developers.+ *+ * SPDX-License-Identifier: BSD-2-Clause+ */++//! The matched declarations cache: an element that matched the same rules and declares the same+//! declarations as one computed before it, under a parent it inherits the same from, takes that+//! element's record without cascading or computing its own, and likewise for the pseudo-elements+//! of an element, which inherit from it as a child does.+//!+//! An element looks first by what it matched, which saves its cascade, and then by what its cascade+//! picked, which finds elements that matched other rules losing to the same declarations.+//!+//! The cache is the document's: every thread of a pass reads what any of them stored, and it stays+//! from one pass to the next, which is what finds the elements a small restyle adds to a list. A+//! pass holds it shared and only adds to it, each thread claiming a way of a bucket with one+//! compare-exchange. Only between passes, where the engine holds it exclusively, does it let go of+//! anything: as an input every entry may have read moves, and as it fills.+//!+//! What a computation reads beyond the key is in the conditions of the entry, which what the+//! computation recorded it read decides. A computation reading something of the element that+//! neither the key nor the conditions name is not stored at all.++use super::super::animations::DeclarationScope;+use super::super::*;+use super::cascade::Winner;+use super::compute::RootFontInputs;+use super::matching::ElementMatch;+use super::records::Record;+use crate::css::display::FfiDisplay;+use std::hash::{Hash, Hasher};+use std::sync::atomic::{AtomicPtr, AtomicU32, Ordering};+use std::sync::{Arc, OnceLock};++/// How many entries a bucket holds: as many as fit a cache line with their tags, so that an element+/// no entry answers for costs one load.+const WAYS: usize = 5;++/// The most buckets a cache holds, which bounds what it keeps alive.+const MAX_BUCKETS: usize = 512;++/// The fewest buckets a cache holds.+const MIN_BUCKETS: usize = 16;++/// How many elements of a document a cache makes room for one entry per.+const ELEMENTS_PER_ENTRY: usize = 2;++/// How many of the elements with declarations of their own a thread remembers the hashes of. One is+/// stored only once its hash recurs, so the many whose inline style is their own cost a hash+/// rather than an entry.+const SEEN_CAPACITY: usize = 64;++/// How many lookups the hit counts of elements with declarations of their own cover before they+/// start over.+const COUNT_PERIOD: u32 = 1024;++/// What a computation reads of its parent and of the element, besides what the element matched+/// and declares. The parent's groups and custom properties are compared by identity, which the+/// entry's reference to the parent's record keeps from going to another.+#[derive(Clone, Copy, PartialEq)]+pub(super) struct MatchedContext {+ pub(super) parent_inherited_groups: [usize; super::super::computed::ENGINE_INHERITED_GROUP_COUNT],+ pub(super) parent_color: u32,+ /// The inherited longhands the parent holds as bits, and its effective zoom.+ pub(super) parent_inherited_values: crate::css::computed_value_types::InheritedSetValues,+ pub(super) parent_dependency_flags: u8,+ /// The display of the parent, which is the box the element would be a child of.+ pub(super) parent_display: FfiDisplay,+ /// The custom properties the parent hands down and the ones it holds.+ pub(super) parent_custom_properties: [usize; 2],+ /// The kind of the pseudo-element styled, or `u8::MAX` for the element itself: only the matches+ /// for it are looked at.+ pub(super) pseudo_kind: u8,+ pub(super) adjustment_facts: u32,+ pub(super) language: StyleAtomID,+ pub(super) directionality: StyleAtomID,+ /// The tree scope of the element, which orders its own declarations among the rules it matched.+ pub(super) tree_scope: TreeScopeID,+ /// The identity of the counter-style registry of the element's style scope, which its+ /// `list-style-type` or `content` may resolve counter styles against.+ pub(super) counter_style_environment: u64,+}++/// What an element's declarations are told apart by: what it matched, which is known before its+/// cascade, or what its cascade picked.+#[derive(Clone, Copy)]+pub(super) enum Declared<'d> {+ Matched(&'d [ElementMatch]),+ Picked {+ winners: &'d [Winner],+ custom_winners: &'d [(CustomDeclaration, RetainedStyleValueData)],+ animation_name_scope: DeclarationScope,+ },+}++/// What an element is looked for by, beside what it matched and declares.+#[derive(Clone, Copy)]+pub(super) struct MatchedKey<'a> {+ hash: u64,+ /// The hash of everything but what the element matched.+ context_hash: u64,+ context: MatchedContext,+ parent: &'a Arc<Record>,+ declares_own: bool,+}++/// What the computation of a record read beyond its key, which its entry answers only where it+/// holds still.+#[derive(Clone, Copy, PartialEq)]+pub(super) struct MatchedConditions {+ /// The font of the document element, where the computation resolved a length against it.+ pub(super) root_font: Option<Option<RootFontInputs>>,+ /// Whether the computation read the parent's value of a property that does not inherit, which+ /// only the same parent's record tells.+ pub(super) reads_parent_reset_values: bool,+}++enum EntryDeclarations {+ Matched(Box<[ElementMatch]>),+ Picked {+ winners: Box<[Winner]>,+ custom_winners: Box<[(CustomDeclaration, RetainedStyleValueData)]>,+ animation_name_scope: DeclarationScope,+ },+}++struct Entry {+ hash: u64,+ context: MatchedContext,+ conditions: MatchedConditions,+ declarations: EntryDeclarations,+ /// What the element declared, which the entry keeps alive so that no other value takes an+ /// address it is compared by.+ declared: Box<[(ElementDeclarationKind, DeclarationEntry, RetainedStyleValueData)]>,+ custom_declared: Box<[(CustomDeclaration, RetainedStyleValueData)]>,+ record: Arc<Record>,+ /// The parent's record, which holds the groups and custom properties the context names.+ parent: Arc<Record>,+}++const _: fn() = || {+ fn assert_shared_between_threads<T: Send + Sync>() {}+ assert_shared_between_threads::<Entry>();+};++/// What `node` declares itself, in the order the cascade reads the kinds of its declarations.+fn declared_by(+ state: &RetainedState,+ node: StyleNodeID,+) -> impl Iterator<Item = (ElementDeclarationKind, &DeclarationEntry, &RetainedStyleValueData)> {+ ElementDeclarationKind::ALL.into_iter().flat_map(move |kind| {+ state+ .element_declarations+ .declarations(node, kind)+ .unwrap_or_default()+ .iter()+ .map(move |(declared, written)| (kind, declared, written))+ })+}++/// The custom properties `node` declares itself.+fn custom_declared_by(+ state: &RetainedState,+ node: StyleNodeID,+) -> impl Iterator<Item = (&CustomDeclaration, &RetainedStyleValueData)> {+ let custom = state.element_declarations.custom(node);+ custom+ .into_iter()+ .flat_map(|custom| custom.declared().iter().zip(custom.written_values()))+}++/// Whether `node` declares anything itself.+pub(super) fn declares_own(state: &RetainedState, node: StyleNodeID) -> bool {+ declared_by(state, node).next().is_some() || custom_declared_by(state, node).next().is_some()+}++impl<'a> MatchedKey<'a> {+ /// The key of `node`, which matched `matches`, under the parent whose record is `parent`.+ pub(super) fn new(+ state: &RetainedState,+ node: StyleNodeID,+ matches: &[ElementMatch],+ context: MatchedContext,+ parent: &'a Arc<Record>,+ declares_own: bool,+ ) -> Self {+ let mut hasher = crate::fast_hash::fast_hasher();+ if declares_own {+ for (kind, declared, written) in declared_by(state, node) {+ (kind as u8).hash(&mut hasher);+ declared.hash(&mut hasher);+ written.pointer().hash(&mut hasher);+ }+ for (declared, written) in custom_declared_by(state, node) {+ declared.hash(&mut hasher);+ written.pointer().hash(&mut hasher);+ }+ }+ context.parent_inherited_groups.hash(&mut hasher);+ context.parent_color.hash(&mut hasher);+ context.parent_custom_properties.hash(&mut hasher);+ context.adjustment_facts.hash(&mut hasher);+ context.pseudo_kind.hash(&mut hasher);+ let context_hash = hasher.finish();+ for matched in matches+ .iter()+ .filter(|matched| matched.pseudo_kind == context.pseudo_kind)+ {+ hasher.write_u32(matched.entry);+ matched.scope.hash(&mut hasher);+ }+ Self {+ hash: hasher.finish(),+ context_hash,+ context,+ parent,+ declares_own,+ }+ }++ pub(super) fn declares_own(&self) -> bool {+ self.declares_own+ }++ /// This key, looking for what `winners` and `custom_winners` were picked by a cascade.+ pub(super) fn for_picked(+ &self,+ winners: &[Winner],+ custom_winners: &[(CustomDeclaration, RetainedStyleValueData)],+ ) -> Self {+ let mut hasher = crate::fast_hash::fast_hasher();+ self.context_hash.hash(&mut hasher);+ winners.hash(&mut hasher);+ for (declared, written) in custom_winners {+ declared.hash(&mut hasher);+ written.pointer().hash(&mut hasher);+ }+ Self {+ hash: hasher.finish(),+ ..*self+ }+ }++ /// The tag of the entries of this key, which is never that of an empty way.+ fn tag(&self) -> u32 {+ tag_of(self.hash)+ }+}++fn tag_of(hash: u64) -> u32 {+ (hash >> 32) as u32 | 1+}++/// What of a thread's lookups for elements with declarations of their own says whether they are+/// worth their cost, and which of those elements recur.+pub(super) struct OwnDeclarationLookups {+ seen: [u64; SEEN_CAPACITY],+ next_seen: usize,+ hits: u32,+ misses: u32,+ lookups: u32,+}++impl Default for OwnDeclarationLookups {+ fn default() -> Self {+ Self {+ seen: [0; SEEN_CAPACITY],+ next_seen: 0,+ hits: 0,+ misses: 0,+ lookups: 0,+ }+ }+}++impl OwnDeclarationLookups {+ /// Whether looking for the next element with declarations of its own is worth its cost.+ pub(super) fn worth_looking(&mut self) -> bool {+ self.lookups += 1;+ if self.lookups == COUNT_PERIOD {+ self.lookups = 0;+ self.hits = 0;+ self.misses = 0;+ }+ // A hit saves a cascade and a computation, which cost some twenty lookups that miss.+ self.misses < 64 || self.hits * 20 >= self.misses+ }++ pub(super) fn note_answer(&mut self, found: bool) {+ match found {+ true => self.hits += 1,+ false => self.misses += 1,+ }+ }++ /// Whether the element of `key` is worth an entry: one with declarations of its own is once+ /// its hash recurs.+ fn worth_storing(&mut self, key: &MatchedKey<'_>) -> bool {+ if !key.declares_own || self.seen.contains(&key.hash) {+ return true;+ }+ self.seen[self.next_seen] = key.hash;+ self.next_seen = (self.next_seen + 1) % SEEN_CAPACITY;+ false+ }+}++#[repr(C, align(64))]+struct Bucket {+ tags: [AtomicU32; WAYS],+ entries: [AtomicPtr<Entry>; WAYS],+}++const _: () = assert!(size_of::<Bucket>() == 64);++impl Bucket {+ fn new() -> Self {+ Self {+ tags: [const { AtomicU32::new(0) }; WAYS],+ entries: [const { AtomicPtr::new(std::ptr::null_mut()) }; WAYS],+ }+ }++ /// Take `entry` into a free way, or hand it back where none is.+ fn claim(&self, tag: u32, entry: *mut Entry) -> Result<(), *mut Entry> {+ for way in 0..WAYS {+ if self.entries[way]+ .compare_exchange(std::ptr::null_mut(), entry, Ordering::Release, Ordering::Relaxed)+ .is_ok()+ {+ self.tags[way].store(tag, Ordering::Release);+ return Ok(());+ }+ }+ Err(entry)+ }++ /// The entries in the ways tagged `tag`.+ fn tagged(&self, tag: u32) -> impl Iterator<Item = &Entry> {+ (0..WAYS).filter_map(move |way| {+ if self.tags[way].load(Ordering::Relaxed) != tag {+ return None;+ }+ // SAFETY: A way holds null or an entry nothing frees while the cache is shared, and the+ // acquire load sees the writes that made it.+ unsafe { self.entries[way].load(Ordering::Acquire).as_ref() }+ })+ }++ fn is_full(&self) -> bool {+ self.entries+ .iter()+ .all(|entry| !entry.load(Ordering::Relaxed).is_null())+ }+}++/// The cache: buckets of ways, a table a pass reads and adds to through shared references. Nothing+/// leaves it but through an exclusive reference, so an entry a thread reads outlives its read.+#[derive(Default)]+pub(super) struct MatchedDeclarationsCache {+ buckets: OnceLock<Box<[Bucket]>>,+ entries: AtomicU32,+}++fn buckets_for(elements: usize) -> usize {+ (elements / ELEMENTS_PER_ENTRY / WAYS)+ .next_power_of_two()+ .clamp(MIN_BUCKETS, MAX_BUCKETS)+}++fn new_buckets(count: usize) -> Box<[Bucket]> {+ (0..count).map(|_| Bucket::new()).collect()+}++impl MatchedDeclarationsCache {+ /// The record of the element or pseudo-element of `key` with the declarations `declared`, against+ /// the document element's font `root_font`, with what its computation read, where an entry+ /// answers for it.+ pub(super) fn find(+ &self,+ state: &RetainedState,+ node: StyleNodeID,+ declared: Declared<'_>,+ key: &MatchedKey<'_>,+ root_font: Option<RootFontInputs>,+ ) -> Option<(&Arc<Record>, MatchedConditions)> {+ let buckets = self.buckets.get()?;+ let bucket = &buckets[key.hash as usize & (buckets.len() - 1)];+ bucket+ .tagged(key.tag())+ .find(|entry| entry.answers(state, node, declared, key, root_font))+ .map(|entry| (&entry.record, entry.conditions))+ }++ /// Keep `record` for the elements of `key`, where a way of its bucket is free. Styling goes on+ /// without it where none is, where the element is unlikely to recur, or where another thread+ /// that computed the same stored it first, which would only take a way from other keys. Threads+ /// storing at the very same time can still each take one.+ #[allow(clippy::too_many_arguments)]+ pub(super) fn insert(+ &self,+ state: &RetainedState,+ node: StyleNodeID,+ declared_by_cascade: Declared<'_>,+ key: MatchedKey<'_>,+ conditions: MatchedConditions,+ record: Arc<Record>,+ lookups: &mut OwnDeclarationLookups,+ ) {+ if !lookups.worth_storing(&key) {+ return;+ }+ let buckets = self.buckets.get_or_init(|| new_buckets(MIN_BUCKETS));+ let bucket = &buckets[key.hash as usize & (buckets.len() - 1)];+ if bucket.is_full()+ || bucket+ .tagged(key.tag())+ .any(|entry| entry.stores(state, node, declared_by_cascade, &key, conditions))+ {+ return;+ }+ let (declared, custom_declared) = match key.declares_own {+ true => (+ declared_by(state, node)+ .map(|(kind, declared, written)| (kind, *declared, written.clone()))+ .collect(),+ custom_declared_by(state, node)+ .map(|(declared, written)| (*declared, written.clone()))+ .collect(),+ ),+ false => (Default::default(), Default::default()),+ };+ let entry = Box::into_raw(Box::new(Entry {+ hash: key.hash,+ context: key.context,+ conditions,+ declarations: match declared_by_cascade {+ Declared::Matched(matches) => EntryDeclarations::Matched(+ matches+ .iter()+ .filter(|matched| matched.pseudo_kind == key.context.pseudo_kind)+ .copied()+ .collect(),+ ),+ Declared::Picked {+ winners,+ custom_winners,+ animation_name_scope,+ } => EntryDeclarations::Picked {+ winners: winners.into(),+ custom_winners: custom_winners.into(),+ animation_name_scope,+ },+ },+ declared,+ custom_declared,+ record,+ parent: key.parent.clone(),+ }));+ match bucket.claim(key.tag(), entry) {+ Ok(()) => {+ self.entries.fetch_add(1, Ordering::Relaxed);+ }+ // SAFETY: The entry was just made, and nothing else names it.+ Err(entry) => drop(unsafe { Box::from_raw(entry) }),+ }+ }++ /// Let go of every entry: an input they may have read moved.+ pub(super) fn forget(&mut self) {+ let Some(buckets) = self.buckets.take() else {+ return;+ };+ for bucket in &buckets {+ for entry in &bucket.entries {+ let entry = entry.load(Ordering::Relaxed);+ if !entry.is_null() {+ // SAFETY: The cache holds the entry alone, and is held exclusively.+ drop(unsafe { Box::from_raw(entry) });+ }+ }+ }+ *self.entries.get_mut() = 0;+ }++ /// Make room for the pass over a document of `elements` elements that follows: more buckets+ /// where the document grew or the cache filled, and none of its entries where it is as large+ /// as it goes and filled.+ pub(super) fn prepare(&mut self, elements: usize) {+ let entries = *self.entries.get_mut() as usize;+ let buckets = self.buckets.get_or_init(|| new_buckets(buckets_for(elements)));+ let count = buckets.len();+ if entries * 4 > count * WAYS * 3 && count == MAX_BUCKETS {+ self.forget();+ self.buckets.get_or_init(|| new_buckets(MAX_BUCKETS));+ return;+ }+ let buckets = self.buckets.get_mut().expect("the cache just made its buckets");+ let filling = entries * 2 > count * WAYS;+ let wanted = buckets_for(elements)+ .max(if filling { count * 2 } else { count })+ .min(MAX_BUCKETS);+ if wanted == count {+ return;+ }+ let bigger = new_buckets(wanted);+ let mut kept = 0;+ for entry in buckets.iter().flat_map(|bucket| &bucket.entries) {+ let entry = entry.load(Ordering::Relaxed);+ // SAFETY: A way holds null or an entry, and the cache is held exclusively.+ let Some(hash) = (unsafe { entry.as_ref() }).map(|entry| entry.hash) else {+ continue;+ };+ match bigger[hash as usize & (wanted - 1)].claim(tag_of(hash), entry) {+ Ok(()) => kept += 1,+ // SAFETY: The entry just left the buckets holding it, which go below.+ Err(entry) => drop(unsafe { Box::from_raw(entry) }),+ }+ }+ *buckets = bigger;+ *self.entries.get_mut() = kept;+ }++ /// Counts the cache's table and entries, and the records only it holds, toward the worker caches.+ pub(super) fn report_memory(&self, report: &mut crate::css::style::memory_report::MemoryReport) {+ use crate::css::style::memory_report::MemoryOwner;+ let Some(buckets) = self.buckets.get() else {+ return;+ };+ report.add(MemoryOwner::WorkerCaches, std::mem::size_of_val(&**buckets));+ for entry in buckets.iter().flat_map(|bucket| &bucket.entries) {+ // SAFETY: A way holds null or an entry nothing frees while the cache is shared.+ let Some(entry) = (unsafe { entry.load(Ordering::Acquire).as_ref() }) else {+ continue;+ };+ let bytes = size_of::<Entry>()+ + match &entry.declarations {+ EntryDeclarations::Matched(matches) => std::mem::size_of_val(&**matches),+ EntryDeclarations::Picked {+ winners,+ custom_winners,+ ..+ } => std::mem::size_of_val(&**winners) + std::mem::size_of_val(&**custom_winners),+ }+ + std::mem::size_of_val(&*entry.declared)+ + std::mem::size_of_val(&*entry.custom_declared);+ report.add(MemoryOwner::WorkerCaches, bytes);+ if report.sizer.first_sight(Arc::as_ptr(&entry.record)) {+ report.add(MemoryOwner::WorkerCaches, size_of::<Record>());+ }+ }+ }+}++impl Drop for MatchedDeclarationsCache {+ fn drop(&mut self) {+ self.forget();+ }+}++impl EntryDeclarations {+ fn are(&self, declared: Declared<'_>, pseudo_kind: u8) -> bool {+ match (self, declared) {+ (Self::Matched(held), Declared::Matched(matches)) => held+ .iter()+ .eq(matches.iter().filter(|matched| matched.pseudo_kind == pseudo_kind)),+ (+ Self::Picked {+ winners: held_winners,+ custom_winners: held_custom_winners,+ animation_name_scope: held_scope,+ },+ Declared::Picked {+ winners,+ custom_winners,+ animation_name_scope,+ },+ ) => {+ *held_scope == animation_name_scope+ && **held_winners == *winners+ && held_custom_winners+ .iter()+ .map(|(declared, written)| (*declared, written.pointer()))+ .eq(custom_winners+ .iter()+ .map(|(declared, written)| (*declared, written.pointer())))+ }+ _ => false,+ }+ }+}++impl Entry {+ /// Whether this entry is one of the element of `key`, whatever its conditions.+ fn is_of(&self, state: &RetainedState, node: StyleNodeID, declared: Declared<'_>, key: &MatchedKey<'_>) -> bool {+ self.hash == key.hash+ && self.context == key.context+ && self.declarations.are(declared, key.context.pseudo_kind)+ && self.declares_as(state, node, key.declares_own)+ }++ /// Whether the record answers for the element of `key`.+ fn answers(+ &self,+ state: &RetainedState,+ node: StyleNodeID,+ declared: Declared<'_>,+ key: &MatchedKey<'_>,+ root_font: Option<RootFontInputs>,+ ) -> bool {+ self.is_of(state, node, declared, key)+ && self.conditions.root_font.is_none_or(|read| read == root_font)+ && (!self.conditions.reads_parent_reset_values || Arc::ptr_eq(&self.parent, key.parent))+ }++ /// Whether this entry answers wherever an entry of the element of `key` with `conditions` would.+ fn stores(+ &self,+ state: &RetainedState,+ node: StyleNodeID,+ declared: Declared<'_>,+ key: &MatchedKey<'_>,+ conditions: MatchedConditions,+ ) -> bool {+ self.conditions == conditions+ && (!conditions.reads_parent_reset_values || Arc::ptr_eq(&self.parent, key.parent))+ && self.is_of(state, node, declared, key)+ }++ /// Whether `node` declares what the element of this entry did.+ fn declares_as(&self, state: &RetainedState, node: StyleNodeID, declares_own: bool) -> bool {+ if !declares_own {+ return self.declared.is_empty() && self.custom_declared.is_empty();+ }+ self.declared+ .iter()+ .map(|(kind, declared, written)| (*kind, *declared, written.pointer()))+ .eq(declared_by(state, node).map(|(kind, declared, written)| (kind, *declared, written.pointer())))+ && self+ .custom_declared+ .iter()+ .map(|(declared, written)| (*declared, written.pointer()))+ .eq(custom_declared_by(state, node).map(|(declared, written)| (*declared, written.pointer())))+ }+}++#[cfg(test)]+impl MatchedDeclarationsCache {+ /// Have the entries of pseudo-elements, or those of elements, answer with `wrong`.+ pub(super) fn poison_with(&self, wrong: &Arc<Record>, pseudo_elements: bool) {+ let buckets = self.buckets.get().expect("the pass kept records");+ for entry in buckets.iter().flat_map(|bucket| &bucket.entries) {+ // SAFETY: A way holds null or an entry nothing frees while the cache is shared, and a+ // test's pass on one thread reads none of them while this writes.+ let Some(entry) = (unsafe { entry.load(Ordering::Acquire).as_mut() }) else {+ continue;+ };+ if (entry.context.pseudo_kind != u8::MAX) == pseudo_elements {+ entry.record = wrong.clone();+ }+ }+ }+}++#[cfg(test)]+mod tests {+ use super::super::counters::StyleCounter;+ use super::super::test_support::{+ add_class, add_rules, add_sheet, allocate_nodes, assert_live_matches_cold, document_with_children, live_record,+ records_equal, relations, remove_class, run_style_update, set_tag, start_live, start_live_on,+ };+ use super::*;+ use crate::css::style_value::{RetainedStyleValueData, StyleValueData};++ fn reused(engine: &StyleEngine) -> u64 {+ engine.retained.live_counters.get(StyleCounter::ReusedElements as u32)+ }++ fn matched_declarations(engine: &StyleEngine) -> &MatchedDeclarationsCache {+ engine+ .retained+ .live_style+ .as_ref()+ .expect("the engine runs")+ .matched_declarations()+ }++ impl MatchedDeclarationsCache {+ fn entry_count(&self) -> usize {+ self.buckets.get().map_or(0, |buckets| {+ buckets+ .iter()+ .flat_map(|bucket| &bucket.entries)+ .filter(|entry| !entry.load(Ordering::Relaxed).is_null())+ .count()+ })+ }+ }++ /// `root -> [first -> child, second -> child]`, with `source` for its rules.+ fn two_parents(source: &str) -> (StyleEngine, Vec<StyleNodeID>) {+ let (mut engine, nodes) = document_with_children(3);+ let children = allocate_nodes(&mut engine, 2);+ for (&child, parent) in children.iter().zip([nodes[1], nodes[2]]) {+ engine.record_tree_delta(child, None, Some(relations(Some(parent), None, None)));+ set_tag(&mut engine, child, "div");+ }+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, sheet, source);+ let mut all = nodes;+ all.extend(children);+ (engine, all)+ }++ #[test]+ fn an_element_takes_the_record_an_element_of_a_pass_before_it_kept() {+ let (mut engine, nodes) = document_with_children(3);+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, sheet, ".item { width: 1px; font-size: 12px; }");+ add_class(&mut engine, nodes[1], "item");+ start_live(&mut engine, nodes[0]);+ let before = reused(&engine);+ add_class(&mut engine, nodes[2], "item");+ run_style_update(&mut engine, nodes[0]);+ assert_eq!(reused(&engine), before + 1);+ assert!(Arc::ptr_eq(+ &live_record(&engine, nodes[1]),+ &live_record(&engine, nodes[2])+ ));+ assert_live_matches_cold(&mut engine, nodes[0]);+ }++ #[test]+ fn a_rule_change_leaves_no_record_computed_from_the_rules_before_it() {+ let (mut engine, nodes) = document_with_children(3);+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, sheet, ".item { width: 1px; }");+ add_class(&mut engine, nodes[1], "item");+ start_live(&mut engine, nodes[0]);+ assert_ne!(matched_declarations(&engine).entry_count(), 0);+ add_rules(&mut engine, sheet, ".item { width: 2px; }");+ add_class(&mut engine, nodes[2], "item");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ }++ #[test]+ fn parents_inheriting_otherwise_keep_their_children_apart() {+ let (mut engine, nodes) = two_parents(+ ".small { font-size: 10px; color: rgb(1, 1, 1); } .large { font-size: 20px; color: rgb(2, 2, 2); } \+ .child { width: 2em; background-color: currentcolor; }",+ );+ add_class(&mut engine, nodes[1], "small");+ add_class(&mut engine, nodes[2], "large");+ add_class(&mut engine, nodes[3], "child");+ add_class(&mut engine, nodes[4], "child");+ start_live(&mut engine, nodes[0]);+ assert!(!Arc::ptr_eq(+ &live_record(&engine, nodes[3]),+ &live_record(&engine, nodes[4])+ ));+ assert_live_matches_cold(&mut engine, nodes[0]);+ }++ #[test]+ fn a_parent_of_the_same_inherited_style_takes_its_children_along() {+ let (mut engine, nodes) = two_parents(".narrow { width: 1px; } .wide { width: 2px; } .child { height: 3px; }");+ add_class(&mut engine, nodes[1], "narrow");+ add_class(&mut engine, nodes[2], "wide");+ add_class(&mut engine, nodes[3], "child");+ start_live(&mut engine, nodes[0]);+ add_class(&mut engine, nodes[4], "child");+ run_style_update(&mut engine, nodes[0]);+ assert!(Arc::ptr_eq(+ &live_record(&engine, nodes[3]),+ &live_record(&engine, nodes[4])+ ));+ assert_live_matches_cold(&mut engine, nodes[0]);+ }++ #[test]+ fn an_explicit_inherit_of_a_reset_property_reads_the_very_parent() {+ let (mut engine, nodes) =+ two_parents(".narrow { width: 1px; } .wide { width: 2px; } .child { width: inherit; }");+ add_class(&mut engine, nodes[1], "narrow");+ add_class(&mut engine, nodes[2], "wide");+ add_class(&mut engine, nodes[3], "child");+ start_live(&mut engine, nodes[0]);+ add_class(&mut engine, nodes[4], "child");+ run_style_update(&mut engine, nodes[0]);+ assert!(!Arc::ptr_eq(+ &live_record(&engine, nodes[3]),+ &live_record(&engine, nodes[4])+ ));+ assert_live_matches_cold(&mut engine, nodes[0]);+ }++ #[test]+ fn a_root_font_moving_leaves_no_length_resolved_against_it() {+ let (mut engine, nodes) = document_with_children(3);+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(+ &mut engine,+ sheet,+ ".small { font-size: 10px; } .large { font-size: 20px; } .item { width: 2rem; }",+ );+ add_class(&mut engine, nodes[0], "small");+ add_class(&mut engine, nodes[1], "item");+ start_live(&mut engine, nodes[0]);+ remove_class(&mut engine, nodes[0], "small");+ add_class(&mut engine, nodes[0], "large");+ add_class(&mut engine, nodes[2], "item");+ run_style_update(&mut engine, nodes[0]);+ assert_live_matches_cold(&mut engine, nodes[0]);+ }++ #[test]+ fn the_cache_holds_no_more_than_its_table_holds() {+ const ELEMENTS: usize = 6000;+ let (mut engine, nodes) = document_with_children(ELEMENTS);+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ let source: String = (0..ELEMENTS)+ .map(|index| format!(".class{index} {{ width: {index}px; }} "))+ .collect();+ add_rules(&mut engine, sheet, &source);+ for (index, &node) in nodes.iter().enumerate().skip(1) {+ add_class(&mut engine, node, &format!("class{index}"));+ }+ start_live(&mut engine, nodes[0]);+ let entries = matched_declarations(&engine).entry_count();+ assert_ne!(entries, 0);+ assert!(entries <= MAX_BUCKETS * WAYS, "{entries} entries");+ assert_live_matches_cold(&mut engine, nodes[0]);+ }++ #[test]+ fn a_full_bucket_hands_back_what_it_has_no_way_for() {+ let bucket = Bucket::new();+ let mut entries = [0_usize; WAYS + 1];+ let pointers: Vec<*mut Entry> = entries+ .iter_mut()+ .map(|entry| std::ptr::from_mut(entry).cast::<Entry>())+ .collect();+ for &pointer in &pointers[..WAYS] {+ assert!(bucket.claim(3, pointer).is_ok());+ }+ assert!(bucket.is_full());+ assert_eq!(bucket.claim(3, pointers[WAYS]), Err(pointers[WAYS]));+ }++ #[test]+ fn a_document_decides_how_many_buckets_a_cache_starts_with() {+ assert_eq!(buckets_for(0), MIN_BUCKETS);+ assert_eq!(buckets_for(1000), 128);+ assert_eq!(buckets_for(usize::MAX / 2), MAX_BUCKETS);+ }++ /// What a key of the stress test below is told apart by, and holds its element's parent to.+ fn stress_context(state: &RetainedState, node: StyleNodeID, parent: &Arc<Record>, index: u32) -> MatchedContext {+ let facts = state.projection.facts(node).expect("the node is an element");+ MatchedContext {+ parent_inherited_groups: [0; crate::css::style::computed::ENGINE_INHERITED_GROUP_COUNT],+ parent_color: parent.payloads.current_color(),+ parent_inherited_values: parent.payloads.inherited_values(),+ parent_dependency_flags: parent.facts().publication_dependency_flags(),+ parent_display: parent.facts().display(),+ parent_custom_properties: [0, 0],+ pseudo_kind: u8::MAX,+ adjustment_facts: index,+ language: facts.language(),+ directionality: facts.directionality(),+ tree_scope: TreeScopeID::DOCUMENT,+ counter_style_environment: 0,+ }+ }++ #[test]+ fn threads_adding_and_reading_at_once_find_only_what_was_stored_for_their_key() {+ const RECORDS: usize = 8;+ const KEYS: u32 = 512;+ const ROUNDS: u32 = 32;+ const WRITERS: u32 = 4;+ const READERS: u32 = 4;+ let (mut engine, nodes) = document_with_children(RECORDS + 3);+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ let source: String = (0..RECORDS)+ .map(|index| format!(".class{index} {{ width: {}px; }} ", index + 1))+ .collect();+ add_rules(&mut engine, sheet, &source);+ for (index, &node) in nodes[1..=RECORDS].iter().enumerate() {+ add_class(&mut engine, node, &format!("class{index}"));+ }+ // An element with declarations of its own, whose values every entry of its keys retains.+ let declaring = nodes[RECORDS + 1];+ let plain = nodes[RECORDS + 2];+ // NB: A value no other test holds, as tests run side by side and small numbers are shared.+ let written = RetainedStyleValueData::from_owned(StyleValueData::Number { value: 8675309.25 });+ engine.element_declarations.set(+ declaring,+ ElementDeclarationKind::InlineStyle,+ vec![(+ DeclarationEntry::new(+ crate::css::property_metadata::property_id::MARGIN_LEFT,+ false,+ CascadeOperator::Declared,+ ),+ written.clone_retained(),+ )],+ );+ start_live_on(&mut engine, nodes[0], 1);+ let parent = live_record(&engine, nodes[0]);+ let records: Vec<Arc<Record>> = nodes[1..=RECORDS]+ .iter()+ .map(|&node| live_record(&engine, node))+ .collect();+ let parent_count = Arc::strong_count(&parent);+ let record_counts: Vec<usize> = records.iter().map(Arc::strong_count).collect();+ let written_count =+ crate::css::style_value_arc::StyleValueArc::strong_count(&written.clone_retained().into_arc());++ let mut cache = MatchedDeclarationsCache::default();+ let state = &engine.retained;+ let key_of = |index: u32| {+ // Every eighth key names the element declaring its own, whose entries retain them.+ let declares_own = index.is_multiple_of(8);+ let node = if declares_own { declaring } else { plain };+ let key = MatchedKey::new(+ state,+ node,+ &[],+ stress_context(state, node, &parent, index),+ &parent,+ declares_own,+ );+ (node, key)+ };+ let record_of = |index: u32| &records[index as usize % RECORDS];+ let mut hits = 0_u64;+ for round in 0..ROUNDS {+ let writing = std::sync::atomic::AtomicU32::new(WRITERS);+ let start = std::sync::Barrier::new((WRITERS + READERS) as usize);+ let table = &cache;+ hits += std::thread::scope(|scope| {+ for writer in 0..WRITERS {+ let (writing, start, key_of, record_of) = (&writing, &start, &key_of, &record_of);+ scope.spawn(move || {+ let mut lookups = OwnDeclarationLookups::default();+ start.wait();+ // Twice, as a key declaring its own is stored only once it recurs. Every+ // writer goes through the keys from elsewhere, so that they meet everywhere.+ for index in 0..KEYS * 2 {+ let index = (index + writer * KEYS / WRITERS) % KEYS;+ let (node, key) = key_of(index);+ table.insert(+ state,+ node,+ Declared::Matched(&[]),+ key,+ MatchedConditions {+ root_font: None,+ reads_parent_reset_values: false,+ },+ record_of(index).clone(),+ &mut lookups,+ );+ }+ writing.fetch_sub(1, Ordering::Release);+ });+ }+ let readers: Vec<_> = (0..READERS)+ .map(|reader| {+ let (writing, start, key_of, record_of) = (&writing, &start, &key_of, &record_of);+ scope.spawn(move || {+ let mut hits = 0_u64;+ start.wait();+ let mut index = reader * KEYS / READERS;+ // One sweep over all keys after the last writer is done, too.+ let mut left = KEYS;+ while left != 0 {+ if writing.load(Ordering::Acquire) == 0 {+ left -= 1;+ }+ index = (index + 1) % KEYS;+ let (node, key) = key_of(index);+ if let Some((record, _)) = table.find(state, node, Declared::Matched(&[]), &key, None) {+ assert!(+ Arc::ptr_eq(record, record_of(index)),+ "key {index} found another's record"+ );+ // Have the refcount and the payloads of what was found raced on.+ let kept = record.clone();+ assert!(records_equal(&kept, record_of(index)));+ hits += 1;+ }+ }+ hits+ })+ })+ .collect();+ readers+ .into_iter()+ .map(|reader| reader.join().expect("a reader finishes"))+ .sum::<u64>()+ });++ // What every thread left is whole: the count holds, and a tag names its entry.+ let held = cache.entry_count();+ assert_eq!(*cache.entries.get_mut() as usize, held);+ for bucket in cache.buckets.get().expect("the writers added") {+ for (tag, entry) in bucket.tags.iter().zip(&bucket.entries) {+ let tag = tag.load(Ordering::Relaxed);+ let entry = entry.load(Ordering::Relaxed);+ // SAFETY: A way holds null or an entry, and the threads are done.+ match unsafe { entry.as_ref() } {+ Some(entry) => assert_eq!(tag, tag_of(entry.hash)),+ None => assert_eq!(tag, 0),+ }+ }+ }+ // Every way between passes: all entries going, more buckets, the largest table filled.+ match round % 4 {+ 0 => cache.forget(),+ 1 => cache.prepare(KEYS as usize),+ 2 => cache.prepare(MAX_BUCKETS * WAYS * ELEMENTS_PER_ENTRY),+ _ => cache.prepare(0),+ }+ }+ assert_ne!(hits, 0);++ // Nothing but the entries held these, and no entry holds them now.+ cache.forget();+ assert_eq!(Arc::strong_count(&parent), parent_count);+ for (record, count) in records.iter().zip(record_counts) {+ assert_eq!(Arc::strong_count(record), count);+ }+ assert_eq!(+ crate::css::style_value_arc::StyleValueArc::strong_count(&written.clone_retained().into_arc()),+ written_count+ );+ }++ #[test]+ fn a_key_stored_already_takes_no_other_way() {+ let (mut engine, nodes) = document_with_children(3);+ let sheet = add_sheet(&mut engine, TreeScopeID::DOCUMENT);+ add_rules(&mut engine, sheet, ".item { width: 1px; }");+ add_class(&mut engine, nodes[1], "item");+ start_live(&mut engine, nodes[0]);+ let parent = live_record(&engine, nodes[0]);+ let record = live_record(&engine, nodes[1]);+ let cache = MatchedDeclarationsCache::default();+ let state = &engine.retained;+ let mut lookups = OwnDeclarationLookups::default();+ let mut insert = |index: u32, root_font: Option<Option<RootFontInputs>>| {+ let key = MatchedKey::new(+ state,+ nodes[2],+ &[],+ stress_context(state, nodes[2], &parent, index),+ &parent,+ false,+ );+ let conditions = MatchedConditions {+ root_font,+ reads_parent_reset_values: false,+ };+ cache.insert(+ state,+ nodes[2],+ Declared::Matched(&[]),+ key,+ conditions,+ record.clone(),+ &mut lookups,+ );+ cache.entry_count()+ };+ assert_eq!(insert(0, None), 1);+ assert_eq!(insert(0, None), 1);+ // An entry answering under other conditions does not answer for this one.+ assert_eq!(insert(0, Some(None)), 2);+ assert_eq!(insert(1, None), 3);+ }+}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/matching.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/matching.rsindex 1d52a4d3a90..69a0fc34895 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/matching.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/matching.rs@@ -18,7 +18,7 @@ use crate::css::selector::Specificity;use smallvec::SmallVec;/// One rule entry matching the element.-#[derive(Clone, Copy)]+#[derive(Clone, Copy, PartialEq)]pub(super) struct ElementMatch {/// The entry in the rule index.pub(super) entry: u32,diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/mod.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/mod.rsindex cb9403fa36b..3f09b8242e0 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/mod.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/mod.rs@@ -32,6 +32,7 @@ mod install_scratch;mod invalidation;mod live;pub(crate) mod main_effects;+mod matched_declarations;mod matched_rules;mod matching;mod pending_inputs;@@ -39,7 +40,6 @@ pub(super) use pending_inputs::HoverSealMemo;pub(crate) mod pool;pub(in crate::css::style) mod projection;mod records;-mod results;mod rule_changes;pub(crate) mod rule_store;mod rules;diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/records.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/records.rsindex 50fa12f29f5..c5574ef5cbb 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/records.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/records.rs@@ -2274,16 +2274,6 @@ pub(super) enum HighlightParent<'a> {Installed(computed::FinalStyleRecordID),}-impl HighlightParent<'_> {- /// The identity of the record, which tells it apart from any other one live.- pub(super) fn identity(self) -> usize {- match self {- Self::Record(record) => Arc::as_ptr(record) as usize,- Self::Installed(record) => record.raw() as usize,- }- }-}-impl DriveRecords for Records<'_> {fn assigned_record_view(&self, node: StyleNodeID) -> Option<computed::StyleRecordView<'_>> {let Some(record) = self.get_shared(node) else {diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/results.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/results.rsdeleted file mode 100644index 58f9cd8025d..00000000000--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/results.rs+++ /dev/null@@ -1,226 +0,0 @@-/*- * Copyright (c) 2026-present, the Ladybird developers.- *- * SPDX-License-Identifier: BSD-2-Clause- */--//! The cascade result cache: an element whose cascade picked the same declarations as one computed-//! shortly before it, under a parent whose inherited style is the same, takes that element's record-//! instead of computing its own.-//!-//! Where the style sharing cache finds siblings and cousins before matching, this finds elements-//! anywhere that end up with the same winners, such as the levels of a chain of identically styled-//! elements. What a computation reads beyond its winners is in the key: the parent's inherited groups-//! by identity, its color, zoom and dependency flags, the box the element would be a child of, the-//! element's custom-property store by identity, the facts its computation adjusts for and the-//! counter-style registry of its style scope. Winners from an element's own declarations match-//! where those declarations declare the same values.--use super::super::animations::DeclarationScope;-use super::super::computed::ENGINE_INHERITED_GROUP_COUNT;-use super::super::*;-use super::cascade::Winner;-use super::records::Record;-use crate::css::display::FfiDisplay;-use smallvec::SmallVec;-use std::collections::VecDeque;-use std::hash::{Hash, Hasher};-use std::sync::Arc;--/// How many computed elements each thread keeps to reuse.-const CAPACITY: usize = 32;--/// How many hashes of recently computed elements each thread remembers. An element whose winners-/// include its own declarations is kept to reuse only once its hash recurs, so the many elements-/// whose inline style is their own cost a hash rather than an entry.-const SEEN_CAPACITY: usize = 64;--/// What a computation reads besides its winners and the element's own declarations.-#[derive(Clone, Copy, PartialEq)]-pub(super) struct ResultContext {- pub(super) parent_inherited_groups: [usize; ENGINE_INHERITED_GROUP_COUNT],- pub(super) parent_color: u32,- /// The inherited longhands the parent holds as bits, and its effective zoom.- pub(super) parent_inherited_values: crate::css::computed_value_types::InheritedSetValues,- pub(super) parent_dependency_flags: u8,- /// The display of the parent, which is the box the element would be a child of.- pub(super) parent_display: FfiDisplay,- pub(super) custom_properties: usize,- pub(super) adjustment_facts: u32,- pub(super) language: StyleAtomID,- pub(super) directionality: StyleAtomID,- /// The identity of the counter-style registry of the element's style scope, which its- /// `list-style-type` or `content` may resolve counter styles against.- pub(super) counter_style_environment: u64,- /// The hash of the context with the winners and the element's own declarations.- pub(super) hash: u64,-}--impl ResultContext {- /// Complete the context of `node` with the hash of everything its result depends on.- pub(super) fn hashed(mut self, state: &RetainedState, node: StyleNodeID, winners: &[Winner]) -> Self {- self.hash = self.hash_with(state, node, winners);- self- }-- fn hash_with(&self, state: &RetainedState, node: StyleNodeID, winners: &[Winner]) -> u64 {- let mut hasher = crate::fast_hash::fast_hasher();- winners.hash(&mut hasher);- for kind in element_declaration_kinds(winners) {- for (declared, written) in element_declarations(state, node, kind) {- declared.hash(&mut hasher);- written.pointer().hash(&mut hasher);- }- }- self.parent_inherited_groups.hash(&mut hasher);- self.parent_color.hash(&mut hasher);- self.custom_properties.hash(&mut hasher);- self.adjustment_facts.hash(&mut hasher);- hasher.finish()- }-}--struct Entry {- node: StyleNodeID,- winners: SmallVec<[Winner; 16]>,- context: ResultContext,- record: Arc<Record>,- /// The custom-property store the context names by identity, which the entry keeps alive so- /// that no other store takes its address. The record may hold another, computed from it.- _custom_properties: Option<Arc<crate::css::custom_properties::CustomPropertyStore>>,-}--pub(super) struct ResultCache {- /// Most recently computed last.- entries: VecDeque<Entry>,- seen: [u64; SEEN_CAPACITY],- next_seen: usize,- /// How often an element with declarations of its own was found and missed since the counts- /// last started over. While such elements rarely repeat, a thread computes them without- /// looking for them.- hits: u32,- misses: u32,- lookups: u32,-}--impl Default for ResultCache {- fn default() -> Self {- Self {- entries: VecDeque::new(),- seen: [0; SEEN_CAPACITY],- next_seen: 0,- hits: 0,- misses: 0,- lookups: 0,- }- }-}--/// How many lookups the hit counts cover before they start over.-const COUNT_PERIOD: u32 = 1024;--/// The declarations of `kind` of `node`, each with the value it was written with. Equal values-/// elements declare are one canonical value, so two elements declaring the same declare the same-/// values.-fn element_declarations(- state: &RetainedState,- node: StyleNodeID,- kind: ElementDeclarationKind,-) -> impl Iterator<Item = (&DeclarationEntry, &RetainedStyleValueData)> {- state- .element_declarations- .declarations(node, kind)- .unwrap_or_default()- .iter()-}--/// The kinds of an element's own declarations its winners came from.-fn element_declaration_kinds(winners: &[Winner]) -> impl Iterator<Item = ElementDeclarationKind> + '_ {- let mut seen = 0_u8;- winners.iter().filter_map(move |winner| match winner.source {- WinnerSource::Element(kind) if seen & (1 << kind.index()) == 0 => {- seen |= 1 << kind.index();- Some(kind)- }- _ => None,- })-}--impl ResultCache {- /// Whether looking for the next element with declarations of its own is worth its cost.- pub(super) fn worth_looking(&mut self) -> bool {- self.lookups += 1;- if self.lookups == COUNT_PERIOD {- self.lookups = 0;- self.hits = 0;- self.misses = 0;- }- // A hit saves a computation, which costs some twenty lookups that miss.- self.misses < 64 || self.hits * 20 >= self.misses- }-- pub(super) fn find(- &mut self,- state: &RetainedState,- node: StyleNodeID,- winners: &[Winner],- animation_name_scope: DeclarationScope,- context: &ResultContext,- ) -> Option<Arc<Record>> {- // NB: The winners of a sheet several shadow roots adopt are the same in each, but not the- // scope their `animation-name` looks for `@keyframes` in.- let position = self.entries.iter().rposition(|entry| {- entry.context == *context- && entry.winners[..] == *winners- && entry.record.rare().animation_name_scope == animation_name_scope- && element_declaration_kinds(winners).all(|kind| {- let identities = |node| {- element_declarations(state, node, kind)- .map(|(declared, written)| (*declared, written.pointer()))- };- identities(node).eq(identities(entry.node))- })- });- let declares_own = element_declaration_kinds(winners).next().is_some();- let Some(position) = position else {- self.misses += u32::from(declares_own);- return None;- };- self.hits += u32::from(declares_own);- let entry = self.entries.remove(position).expect("the position is in the cache");- let record = entry.record.clone();- self.entries.push_back(entry);- Some(record)- }-- pub(super) fn insert(- &mut self,- node: StyleNodeID,- winners: &[Winner],- context: ResultContext,- custom_properties: Option<Arc<crate::css::custom_properties::CustomPropertyStore>>,- record: Arc<Record>,- ) {- debug_assert_eq!(- context.custom_properties,- custom_properties- .as_ref()- .map_or(0, |store| Arc::as_ptr(store) as usize)- );- if element_declaration_kinds(winners).next().is_some() && !self.seen.contains(&context.hash) {- self.seen[self.next_seen] = context.hash;- self.next_seen = (self.next_seen + 1) % SEEN_CAPACITY;- return;- }- if self.entries.len() == CAPACITY {- self.entries.pop_front();- }- self.entries.push_back(Entry {- node,- winners: winners.into(),- context,- record,- _custom_properties: custom_properties,- });- }-}diff --git a/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal.rs b/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal.rsindex 2498b2852dd..0836e6cf153 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal.rs@@ -25,9 +25,11 @@ use super::cascade::{Cascade, CascadeCounters};use super::compute::{GroupSeeds, RootFontInputs};use super::custom_properties::{DrivenWithRegisteredProperties, SubstitutingSubject, drive_with_registered_properties};use super::drive::DriveRecords;+use super::matched_declarations::{+ self, Declared, MatchedConditions, MatchedContext, MatchedDeclarationsCache, MatchedKey, OwnDeclarationLookups,+};use super::matching::{ElementMatch, MatchCounters, Matcher};use super::records::{ChildImpact, RareStyleFacts, Record, Records};-use super::results::{ResultCache, ResultContext};use super::rule_changes::all_lose_every_longhand;use super::rules::{ContainerGateID, RuleIndex};use super::sharing::SharingCache;@@ -277,8 +279,12 @@ pub(super) struct PassContext<'a> {/// keeps its caches: an element restyled in a later pass finds the groups the elements styled/// before it built.pub(super) group_caches: Option<&'a super::pool::PerThread<super::compute::GroupCache>>,+ /// The matched declarations cache a pass keeps for the next, where it keeps its caches.+ pub(super) kept_matched_declarations: Option<&'a MatchedDeclarationsCache>,+ /// The cache of a pass that keeps none for the next.+ pub(super) own_matched_declarations: MatchedDeclarationsCache,/// Whether the pass reuses what it computed for one element for another: shares records- /// between elements, reuses results and pseudo-element records, and keeps the caches of its+ /// between elements, finds them in the matched declarations cache, and keeps the caches of its/// computations across elements. A reference pass checking the others does none of that.pub(super) uses_caches: bool,/// What the audit of what the pass reuses asks for, as `LIBWEB_STYLE_AUDIT_CACHES` asks.@@ -315,6 +321,8 @@ impl<'a> PassContext<'a> {keeps_matches: false,suspends: false,group_caches: None,+ kept_matched_declarations: None,+ own_matched_declarations: MatchedDeclarationsCache::default(),uses_caches: true,cache_audit: super::self_check::Mode::Off,held_root_font,@@ -324,6 +332,13 @@ impl<'a> PassContext<'a> {}}+impl PassContext<'_> {+ /// The matched declarations cache of the pass.+ fn matched_declarations(&self) -> &MatchedDeclarationsCache {+ self.kept_matched_declarations.unwrap_or(&self.own_matched_declarations)+ }+}+pub(super) fn is_document_element(state: &RetainedState, node: StyleNodeID) -> bool {state.projection.adjustment_facts(node) & bridge::element_adjustment_fact::IS_DOCUMENT_ELEMENT != 0}@@ -506,12 +521,8 @@ struct Scratch<'a> {substitutions: std::cell::RefCell<super::custom_properties::SubstitutionCache>,sharing: SharingCache,moved_names: super::custom_property_moves::MovedCustomProperties,- /// The pseudo-element records a thread computed, by kind, what they inherit from their- /// element and their winners: a pseudo-element's style is a function of those alone, where no- /// winner computes against the element itself or takes its value of a property that does not- /// inherit.- pseudo_elements: crate::fast_hash::FastMap<PseudoElementKey, std::sync::Arc<Record>>,- results: ResultCache,+ /// What decides which of the elements with declarations of their own the cache is worth for.+ own_declaration_lookups: OwnDeclarationLookups,/// The longhand table flags of the records the thread made last, most recent first, which the/// next record holding the same flags shares.table_flags: SmallVec<[std::sync::Arc<crate::css::computed_longhand_table::LonghandTableFlags>; TABLE_FLAGS_KEPT]>,@@ -533,8 +544,8 @@ struct Scratch<'a> {backing_elements_moved: bool,/// What `LIBWEB_STYLE_AUDIT_CACHES` found of what the pass reused, where it is set.cache_audit: Option<Box<cache_audit::CacheAudit>>,- /// The kinds of the pseudo-elements of the element styled last whose records came from- /// `pseudo_elements`, kept for the audit alone.+ /// The kinds of the pseudo-elements of the element styled last whose records came from the+ /// matched declarations cache, kept for the audit alone.pseudo_element_cache_hits: SmallVec<[u8; 2]>,}@@ -556,8 +567,7 @@ impl<'a> Scratch<'a> {substitutions: Default::default(),sharing: SharingCache::default(),moved_names: Default::default(),- pseudo_elements: Default::default(),- results: ResultCache::default(),+ own_declaration_lookups: OwnDeclarationLookups::default(),table_flags: SmallVec::new(),rare_facts: SmallVec::new(),last_record: None,@@ -892,11 +902,30 @@ impl<'a> Scratch<'a> {if matched {self.apply_container_gates(context, node, false);}- let cascaded = matched && self.cascade_element(context, node, backed);+ // An element that matched what one styled before did, with what that element's computation+ // read holding still, takes its record without a cascade.+ let matched_key = match matched {+ true => self.matched_key(context, node, backed),+ false => None,+ };+ let found = matched_key+ .as_ref()+ .and_then(|key| self.find_matched_declarations(context, node, key));+ let cascaded = found.is_some() || (matched && self.cascade_element(context, node, backed));let outcome = if !cascaded {Outcome::CascadeDeclined} else {- let computed = self.compute(context, node);+ let computed = match found {+ Some(record) => Ok((+ record,+ ComputedFacts {+ directly: false,+ element_dependent: false,+ reused: true,+ },+ )),+ None => self.compute(context, node, matched_key),+ };match computed {Ok((record, computed)) => {if let Some(before) = &matched_before {@@ -933,7 +962,7 @@ impl<'a> Scratch<'a> {context,node,match computed.reused {- true => cache_audit::Reuse::ReusedResult,+ true => cache_audit::Reuse::MatchedDeclarations,false => cache_audit::Reuse::ComputationCaches,},);@@ -1200,7 +1229,7 @@ impl<'a> Scratch<'a> {context: &PassContext<'_>,node: StyleNodeID,element: &std::sync::Arc<Record>,- inherited: &PseudoElementInheritance,+ inherited: &PseudoElementInheritance<'_>,kind: u8,read: PseudoElementRead,) -> PseudoElementOutcome {@@ -1233,6 +1262,25 @@ impl<'a> Scratch<'a> {if !read.styles(kind, has_rules || highlight_parent.is_some(), element) {return PseudoElementOutcome::Unstyled;}+ // A pseudo-element that generates a box, whose element inherits it what one did that left a+ // record, takes that record without a cascade, as an element does.+ let matched_key = (generating && !highlight)+ .then(|| Self::pseudo_element_matched_key(context, node, matches, inherited, kind))+ .flatten();+ if let Some(record) = matched_key.as_ref().and_then(|key| {+ context+ .matched_declarations()+ .find(state, node, Declared::Matched(matches), key, context.root_font())+ .map(|(record, _)| record.clone())+ }) {+ if self.cache_audit.is_some() {+ self.pseudo_element_cache_hits.push(kind);+ }+ return PseudoElementOutcome::Computed {+ record,+ element_dependent: false,+ };+ }self.cascade.cascade_pseudo_element(state, context.index, node, matches, kind);// A pseudo-element's own custom properties resolve over what its element hands down,@@ -1259,50 +1307,6 @@ impl<'a> Scratch<'a> {// The pseudo-element's other properties substitute the animated values of its custom// properties, which the host sampled over the environment it holds, as an element's do.let sampled_custom_properties = context.records.sampled_pseudo_element_custom_properties(node, kind);- let key = PseudoElementKey {- kind,- inherited_groups: inherited.groups,- color: inherited.color,- inherited_values: inherited.inherited_values,- element_dependency_flags: inherited.dependency_flags,- display: {- let display = element.facts().display();- [- display.tag,- display.outside,- display.inside,- u8::from(display.list_item),- display.internal,- display.box_value,- ]- },- custom_properties: inherited- .handed_down- .as_ref()- .map_or(0, |store| std::sync::Arc::as_ptr(store) as usize),- winners: self.cascade.winners.clone(),- custom_winners: self- .cascade- .custom_winners- .iter()- .map(|(declaration, value)| (*declaration, value.pointer() as usize))- .collect(),- animation_name_scope: self.cascade.animation_name_scope,- highlight_parent: highlight_parent.map_or(0, super::records::HighlightParent::identity),- counter_style_environment: state.counter_style_environment_identity_of(node),- };- if sampled_custom_properties.is_none()- && context.uses_caches- && let Some(record) = self.pseudo_elements.get(&key)- {- if self.cache_audit.is_some() {- self.pseudo_element_cache_hits.push(kind);- }- return PseudoElementOutcome::Computed {- record: record.clone(),- element_dependent: false,- };- }let group_seeds = context.initial.group_seeds(context.records.get_shared(inherited.parent));@@ -1406,10 +1410,17 @@ impl<'a> Scratch<'a> {Err(outcome) => return outcome,};let custom_properties = registered.unwrap_or(custom_properties);- if let Some(reads) = subject.container_reads.into_inner() {+ let asked_own_style = subject.asked_pseudo_element_style.get();+ let container_reads = subject.container_reads.into_inner();+ let reads_container_style = container_reads.is_some();+ if let Some(reads) = container_reads {self.container_reads.get_or_insert_default().add_reads(reads);}computed.reads.reads_attributes = Self::note_substitution_reads(&mut computed, &self.cascade.custom_winners);+ let storable = !asked_own_style+ && !reads_container_style+ && !self.recascades_monospace_font_size(&computed)+ && Self::reads_nothing_of_the_element(&computed);let value_of = |property| computed.groups.value(property);let counter_style_environment_identity = state.values_counter_style_environment_identity(super::super::computed::ComputedStyleTarget::new(node, kind),@@ -1446,15 +1457,23 @@ impl<'a> Scratch<'a> {.with_custom_properties(custom_properties.as_ref()),header: super::records::RecordHeader::new(computed.facts),});- if context.uses_caches- && !computed.element_dependent- && computed.reads.parent_reset_groups == 0+ if let Some(matched_key) = matched_key+ && storable&& sampled_custom_properties.is_none(){- if self.pseudo_elements.len() == 1024 {- self.pseudo_elements.clear();- }- self.pseudo_elements.insert(key, record.clone());+ let matches = match self.gated {+ true => &self.applied,+ false => &self.matches,+ };+ context.matched_declarations().insert(+ state,+ node,+ Declared::Matched(matches),+ matched_key,+ matched_conditions(context, computed.reads),+ record.clone(),+ &mut self.own_declaration_lookups,+ );}PseudoElementOutcome::Computed {record,@@ -1618,8 +1637,50 @@ impl<'a> Scratch<'a> {&mut self,context: &PassContext<'_>,node: StyleNodeID,+ key: Option<MatchedKey<'_>>,) -> Result<(std::sync::Arc<Record>, ComputedFacts), Outcome> {let state = context.state;+ // An element that matched other rules than one styled before, whose cascade picked the same+ // declarations all the same, takes its record, and the next to match what it did takes it+ // without a cascade.+ let picked_key = key+ .as_ref()+ .map(|key| key.for_picked(&self.cascade.winners, &self.cascade.custom_winners));+ if let (Some(key), Some(picked_key)) = (key.as_ref(), picked_key.as_ref()) {+ let declared = Declared::Picked {+ winners: &self.cascade.winners,+ custom_winners: &self.cascade.custom_winners,+ animation_name_scope: self.cascade.animation_name_scope,+ };+ if let Some((record, conditions)) =+ context+ .matched_declarations()+ .find(state, node, declared, picked_key, context.root_font())+ {+ let record = record.clone();+ let matches = match self.gated {+ true => &self.applied,+ false => &self.matches,+ };+ context.matched_declarations().insert(+ state,+ node,+ Declared::Matched(matches),+ *key,+ conditions,+ record.clone(),+ &mut self.own_declaration_lookups,+ );+ return Ok((+ record,+ ComputedFacts {+ directly: false,+ element_dependent: false,+ reused: true,+ },+ ));+ }+ }let inheritance_parent = state.projection.inheritance_parent(node);let parent = match inheritance_parent {Some(parent) => match context.records.current_color_of(parent) {@@ -1661,48 +1722,10 @@ impl<'a> Scratch<'a> {// samples its animations over the record the pass installs.let sampled_custom_properties = context.records.sampled_custom_properties(node).flatten();- // Elements styled by rules alone repeat; one with its own declarations mostly does not.- let declares_own = self- .cascade- .winners- .iter()- .any(|winner| matches!(winner.source, WinnerSource::Element(_)));- let result_context = (context.uses_caches- && sampled_custom_properties.is_none()- && !custom_properties_read_subject- && (!declares_own || self.results.worth_looking()))- .then(|| self.result_context(context, node, inheritance_parent, custom_properties.as_ref()))- .flatten();- if let Some(result_context) = &result_context- && let Some(record) = self.results.find(- state,- node,- &self.cascade.winners,- self.cascade.animation_name_scope,- result_context,- )- // NB: An element declaring other custom properties than the one whose result it is- // may resolve to the same ones, but declares its own, which a move of the custom- // properties it inherits builds them anew from.- && declares_the_custom_properties_of(&record, &self.cascade.custom_winners)- {- return Ok((- record,- ComputedFacts {- directly: false,- element_dependent: false,- reused: true,- },- ));- }-let group_seeds = context.initial.group_seeds(parent.and_then(|(parent, _)| context.records.get_shared(parent)));let requested = self.requested();- // The store the result context names, which the registered values of the element may- // compute to another.- let result_custom_properties = result_context.as_ref().and_then(|_| custom_properties.clone());let (mut computed, registered) = drive_with_registered_properties(|computed_store| {let mut suspended_font = None;let substituted = computed_store.unwrap_or(&custom_properties);@@ -1796,10 +1819,15 @@ impl<'a> Scratch<'a> {})})?;let custom_properties = registered.unwrap_or(custom_properties);- if let Some(reads) = subject.container_reads.into_inner() {+ let container_reads = subject.container_reads.into_inner();+ let reads_container_style = container_reads.is_some();+ if let Some(reads) = container_reads {self.container_reads.get_or_insert_default().add_reads(reads);}computed.reads.reads_attributes = Self::note_substitution_reads(&mut computed, &self.cascade.custom_winners);+ let storable = !reads_container_style+ && !self.recascades_monospace_font_size(&computed)+ && Self::reads_nothing_of_the_element(&computed);let value_of = |property| computed.groups.value(property);let counter_style_environment_identity = state.values_counter_style_environment_identity(super::super::computed::ComputedStyleTarget::new(node, u8::MAX),@@ -1847,19 +1875,35 @@ impl<'a> Scratch<'a> {.installed_record_holding_the_same_style_as(&record).cloned().unwrap_or(record);- // A result reading the parent's values of properties that are not inherited depends on- // more of the parent than the key holds.- if let Some(result_context) = result_context- && !computed.element_dependent- && computed.reads.parent_reset_groups == 0+ // Only what the key and the conditions of an entry name is read of what may differ between+ // the elements that find it.+ if let Some(key) = key+ && storable{- self.results.insert(+ let conditions = matched_conditions(context, computed.reads);+ let matches = match self.gated {+ true => &self.applied,+ false => &self.matches,+ };+ let cache = context.matched_declarations();+ let lookups = &mut self.own_declaration_lookups;+ cache.insert(+ state,node,- &self.cascade.winners,- result_context,- result_custom_properties,+ Declared::Matched(matches),+ key,+ conditions,record.clone(),+ lookups,);+ if let Some(picked_key) = picked_key {+ let declared = Declared::Picked {+ winners: &self.cascade.winners,+ custom_winners: &self.cascade.custom_winners,+ animation_name_scope: self.cascade.animation_name_scope,+ };+ cache.insert(state, node, declared, picked_key, conditions, record.clone(), lookups);+ }}Ok((record,@@ -1927,52 +1971,183 @@ impl<'a> Scratch<'a> {reads & FfiNodeRecordReads::Attributes as u8 != 0}- /// What the computation of `node` reads besides its winners, where its result may be reused:- /// it has a parent this pass styled, and no winner computes in the font phases, which can read- /// the cascaded font sizes of ancestors beyond the parent.- fn result_context(- &self,- context: &PassContext<'_>,+ /// What `node`, which just matched, is looked for by in the matched declarations cache, where+ /// its record may be one computed before: it has a parent this pass or one before it styled,+ /// and neither reads the animated values a record does not hold.+ fn matched_key<'c>(+ &mut self,+ context: &PassContext<'c>,node: StyleNodeID,- inheritance_parent: Option<StyleNodeID>,- custom_properties: Option<&std::sync::Arc<crate::css::custom_properties::CustomPropertyStore>>,- ) -> Option<ResultContext> {+ backed: Option<(u8, StyleNodeID)>,+ ) -> Option<MatchedKey<'c>> {+ if !context.uses_caches || backed.is_some() {+ return None;+ }let state = context.state;- if self- .cascade- .winners- .iter()- .any(|winner| crate::css::style_compute::computes_in_font_phases(winner.property))- {+ let facts = state.projection.facts(node)?;+ let parent = state.projection.inheritance_parent(node)?;+ let records = context.records;+ let parent_record = records.get_shared(parent)?;+ // A parent that generates no box makes the box its child would be in an ancestor's.+ let parent_display = parent_record.facts().display();+ if parent_display.is_contents() {return None;}- let parent = inheritance_parent?;- let parent_record = context.records.get(parent)?;// What a child computes under the composition of its parent's animations is not the- // parent's record's alone.- if context.records.composition(parent).is_some() {+ // parent's record's alone, and the custom properties animations sample are no record's.+ if records.composition(parent).is_some()+ || records.sampled_custom_properties(parent).flatten().is_some()+ || records.sampled_custom_properties(node).flatten().is_some()+ {return None;}+ let (parent_store, parent_held) = records.custom_stores_of(parent)?;+ // Elements styled by rules alone repeat; one with its own declarations mostly does not.+ let declares_own = matched_declarations::declares_own(state, node);+ if declares_own && !self.own_declaration_lookups.worth_looking() {+ return None;+ }+ let matches = match self.gated {+ true => &self.applied,+ false => &self.matches,+ };+ Some(MatchedKey::new(+ state,+ node,+ matches,+ MatchedContext {+ parent_inherited_groups: std::array::from_fn(|group| parent_record.payloads[group].as_ptr() as usize),+ parent_color: parent_record.payloads.current_color(),+ parent_inherited_values: parent_record.payloads.inherited_values(),+ parent_dependency_flags: parent_record.facts().publication_dependency_flags(),+ parent_display,+ parent_custom_properties: [+ custom_store_identity(parent_store.as_deref()),+ custom_store_identity(parent_held.as_deref()),+ ],+ pseudo_kind: u8::MAX,+ adjustment_facts: state.projection.adjustment_facts(node),+ language: facts.language(),+ directionality: facts.directionality(),+ tree_scope: state.projection.tree_scope(node),+ counter_style_environment: state.counter_style_environment_identity_of(node),+ },+ parent_record,+ declares_own,+ ))+ }++ /// What the pseudo-element of `kind` of `node`, inheriting `inherited`, is looked for by in the+ /// matched declarations cache, where its record may be one computed before.+ fn pseudo_element_matched_key<'k>(+ context: &PassContext<'_>,+ node: StyleNodeID,+ matches: &[ElementMatch],+ inherited: &PseudoElementInheritance<'k>,+ kind: u8,+ ) -> Option<MatchedKey<'k>> {+ if !context.uses_caches {+ return None;+ }+ let state = context.state;let facts = state.projection.facts(node)?;- // A parent that generates no box makes the box its child would be in an ancestor's.- let parent_display = parent_record.facts().display();- if parent_display.is_contents() {+ let records = context.records;+ // NB: Only where these are absent is what `inherited` names held by `inherited.record`, which+ // the entry holds to keep those addresses from going to others.+ if records.composition(inherited.parent).is_some()+ || records.sampled_custom_properties(inherited.parent).flatten().is_some()+ || records.sampled_pseudo_element_custom_properties(node, kind).is_some()+ {return None;}- let result_context = ResultContext {- parent_inherited_groups: std::array::from_fn(|group| parent_record.payloads[group].as_ptr() as usize),- parent_color: parent_record.payloads.current_color(),- parent_inherited_values: parent_record.payloads.inherited_values(),- parent_dependency_flags: parent_record.facts().publication_dependency_flags(),- parent_display,- custom_properties: custom_properties.map_or(0, |store| std::sync::Arc::as_ptr(store) as usize),- adjustment_facts: state.projection.adjustment_facts(node),- language: facts.language(),- directionality: facts.directionality(),- counter_style_environment: state.counter_style_environment_identity_of(node),- hash: 0,+ Some(MatchedKey::new(+ state,+ node,+ matches,+ MatchedContext {+ parent_inherited_groups: inherited.groups,+ parent_color: inherited.color,+ parent_inherited_values: inherited.inherited_values,+ parent_dependency_flags: inherited.dependency_flags,+ parent_display: inherited.record.facts().display(),+ parent_custom_properties: [+ custom_store_identity(inherited.handed_down.as_ref()),+ custom_store_identity(inherited.held.as_ref()),+ ],+ pseudo_kind: kind,+ adjustment_facts: state.projection.adjustment_facts(node),+ language: facts.language(),+ directionality: facts.directionality(),+ tree_scope: state.projection.tree_scope(node),+ counter_style_environment: state.counter_style_environment_identity_of(node),+ },+ inherited.record,+ false,+ ))+ }++ /// Whether a winning `font-family: monospace` recascaded the font size of `computed` over the+ /// whole ancestor chain, which the key of the matched declarations cache does not name.+ fn recascades_monospace_font_size(&self, computed: &super::compute::ComputedElement) -> bool {+ use crate::css::property_metadata::property_id::FONT_FAMILY;+ self.cascade.winners.iter().any(|winner| winner.property == FONT_FAMILY)+ && computed+ .groups+ .value(FONT_FAMILY)+ .optional_data()+ .is_some_and(crate::css::style_compute::font_family_is_monospace)+ }++ /// Whether `computed` read nothing of its element that the key and the conditions of the+ /// matched declarations cache do not name.+ fn reads_nothing_of_the_element(computed: &super::compute::ComputedElement) -> bool {+ !computed.element_dependent+ && !computed.reads.reads_sibling_position+ && !computed.reads.reads_attributes+ && computed.reads.container_units == 0+ && !computed.reads.display_none_is_animated+ }++ /// The record the matched declarations cache holds for the element `key` looks for.+ fn find_matched_declarations(+ &mut self,+ context: &PassContext<'_>,+ node: StyleNodeID,+ key: &MatchedKey<'_>,+ ) -> Option<std::sync::Arc<Record>> {+ let matches = match self.gated {+ true => &self.applied,+ false => &self.matches,};- Some(result_context.hashed(state, node, &self.cascade.winners))+ let found = context+ .matched_declarations()+ .find(+ context.state,+ node,+ Declared::Matched(matches),+ key,+ context.root_font(),+ )+ .map(|(record, _)| record.clone());+ if key.declares_own() {+ self.own_declaration_lookups.note_answer(found.is_some());+ }+ found+ }+}++/// The identity of a store of custom properties a parent holds, which an entry of the matched+/// declarations cache holds the parent's record for.+fn custom_store_identity(store: Option<&std::sync::Arc<crate::css::custom_properties::CustomPropertyStore>>) -> usize {+ store.map_or(0, |store| std::sync::Arc::as_ptr(store) as usize)+}++/// What a computation that read `reads` needs to hold still for an entry of the matched declarations+/// cache to answer for another element.+fn matched_conditions(context: &PassContext<'_>, reads: super::records::ComputationReads) -> MatchedConditions {+ MatchedConditions {+ root_font: (reads.reads_root_font != RootFontReads::None).then(|| context.root_font()),+ reads_parent_reset_values: reads.parent_reset_groups != 0,}}@@ -2168,52 +2343,13 @@ fn gate_verdict(.unwrap_or_else(|| undecided_verdict(conditions))}-/// Whether `record` holds `custom_winners` as the custom declarations it was computed from.-fn declares_the_custom_properties_of(- record: &Record,- custom_winners: &[(CustomDeclaration, crate::css::style_value::RetainedStyleValueData)],-) -> bool {- let declarations = record- .custom_declarations()- .map_or(&[][..], |declarations| &declarations[..]);- declarations.len() == custom_winners.len()- && declarations.iter().zip(custom_winners).all(|(declared, winner)| {- declared.0 == winner.0 && (declared.1.pointer() == winner.1.pointer() || declared.1 == winner.1)- })-}--/// What a pseudo-element's style is computed from, besides the facts its element's style already-/// holds.-#[derive(PartialEq, Eq, Hash)]-struct PseudoElementKey {- kind: u8,- inherited_groups: [usize; super::super::computed::ENGINE_INHERITED_GROUP_COUNT],- color: u32,- inherited_values: crate::css::computed_value_types::InheritedSetValues,- /// What the element's style depends on, part of which its pseudo-elements take on, as being in a- /// `display: none` subtree.- element_dependency_flags: u8,- display: [u8; 6],- custom_properties: usize,- winners: Vec<super::cascade::Winner>,- /// The pseudo-element's own custom declarations, by declaration and value address, which its- /// winners do not hold: a `::first-letter` whose longhands all lose still differs by these.- custom_winners: Vec<(CustomDeclaration, usize)>,- /// Where the winning `animation-name` was declared, which the winners do not tell apart for a- /// sheet several shadow roots adopt.- animation_name_scope: super::super::animations::DeclarationScope,- /// The record a highlight pseudo-element inherits from, or zero.- highlight_parent: usize,- /// The identity of the counter-style registry of the element's style scope, which a `::marker`- /// or generated content may resolve its counter styles against.- counter_style_environment: u64,-}-/// What a pseudo-element inherits from its originating element.-struct PseudoElementInheritance {+struct PseudoElementInheritance<'r> {/// The element inherited from: the originating element, or for a `::first-letter` the element/// containing the letter.parent: StyleNodeID,+ /// The record of that element.+ record: &'r std::sync::Arc<Record>,/// The inherited longhands that element holds as bits, and its effective zoom.inherited_values: crate::css::computed_value_types::InheritedSetValues,/// What a view of that element says its style depends on.@@ -2225,11 +2361,11 @@ struct PseudoElementInheritance {held: super::records::HeldCustomProperties,}-impl PseudoElementInheritance {+impl<'r> PseudoElementInheritance<'r> {// https://drafts.csswg.org/css-pseudo-4/#treelike// A pseudo-element inherits from its originating element, the animated values of the// composition the host lays over the element's record included, as a child does.- fn of(context: &PassContext<'_>, node: StyleNodeID, element: &Record) -> Self {+ fn of(context: &PassContext<'_>, node: StyleNodeID, element: &'r std::sync::Arc<Record>) -> Self {let composition = context.records.composition(node);let inherited_payloads: &crate::css::computed_values::StyleGroups = match &composition {Some(view) => view.payloads,@@ -2244,6 +2380,7 @@ impl PseudoElementInheritance {};Self {parent: node,+ record: element,inherited_values: inherited_payloads.inherited_values(),dependency_flags: composition.as_ref().map_or_else(|| element.facts().publication_dependency_flags(),@@ -2837,10 +2974,10 @@ pub(super) fn style_pseudo_element_inheriting_from(scratch.apply_container_gates(context, node, true);let inherited = match inheritance_parent {Some(parent) => {- let Some(parent_record) = context.records.get_shared(parent).cloned() else {+ let Some(parent_record) = context.records.get_shared(parent) else {return DemandedPseudoElement::Declined;};- PseudoElementInheritance::of(context, parent, &parent_record)+ PseudoElementInheritance::of(context, parent, parent_record)}None => PseudoElementInheritance::of(context, node, &element),};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.rsindex 6e1e845c325..31bab0f75d2 100644--- a/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal/cache_audit.rs+++ b/Libraries/LibWeb/Rust/src/css/style/pipeline/traversal/cache_audit.rs@@ -5,11 +5,11 @@*///! 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+//! with its caches on gives a record, whether through style sharing, the matched declarations 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+//! element's record and its pseudo-elements' records, the ones from the matched declarations 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.@@ -33,11 +33,11 @@ pub(in super::super) fn mode_from_environment() -> Mode {#[derive(Clone, Copy, Debug, PartialEq, Eq)]pub(super) enum Reuse {SharedStyle,- ReusedResult,+ MatchedDeclarations,MovedCustomProperties,/// A computation, reading the caches its thread kept of the computations before it.ComputationCaches,- /// The pseudo-element record cache, for a pseudo-element.+ /// The matched declarations cache, for a pseudo-element.PseudoElementRecord,}@@ -47,10 +47,10 @@ impl Reuse {fn name(self) -> &'static str {match self {Self::SharedStyle => "style sharing",- Self::ReusedResult => "the result cache",+ Self::MatchedDeclarations => "the matched declarations 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",+ Self::PseudoElementRecord => "the matched declarations cache, for a pseudo-element",}}}@@ -237,7 +237,7 @@ fn recompute(context: &PassContext<'_>, node: StyleNodeID) -> Option<Recomputed>if !scratch.cascade_element(&reference, node, state.backed_host_pseudo_element(node)) {return None;}- let (record, _) = scratch.compute(&reference, node).ok()?;+ let (record, _) = scratch.compute(&reference, node, None).ok()?;if is_document_element {note_root_font();}@@ -310,7 +310,7 @@ pub(super) mod tests {assert_eq!(audit.failures, Vec::<String>::new());for reuse in [Reuse::SharedStyle,- Reuse::ReusedResult,+ Reuse::MatchedDeclarations,Reuse::ComputationCaches,Reuse::PseudoElementRecord,] {@@ -383,16 +383,35 @@ pub(super) mod tests {}}+ #[test]+ fn a_matched_declarations_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 element record the pass keeps be the root's record.+ let wrong = context.records.get_shared(nodes[0]).unwrap();+ context.matched_declarations().poison_with(wrong, false);+ scratch.sharing = Default::default();+ });+ assert_eq!(audit.checked[Reuse::MatchedDeclarations as usize], 1);+ assert!(+ audit.failures[0].contains(&format!(+ "(node {}), from the matched declarations cache: live differs from cold in ",+ nodes[2].raw()+ )),+ "{:?}",+ audit.failures+ );+ }+#[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();- }+ // Have every pseudo-element record the pass keeps be the root's record.+ let wrong = context.records.get_shared(nodes[0]).unwrap();+ context.matched_declarations().poison_with(wrong, true);scratch.sharing = Default::default();});assert_eq!(audit.checked[Reuse::PseudoElementRecord as usize], 1);@@ -402,7 +421,7 @@ pub(super) mod tests {assert!(failure.starts_with("::before of <"), "{failure}");assert!(failure.contains(&format!(- "(node {}), from the pseudo-element record cache: live differs from cold in ",+ "(node {}), from the matched declarations cache, for a pseudo-element: live differs from cold in ",nodes[2].raw())),"{failure}"diff --git a/Meta/Linters/check_rust_address_keys.py b/Meta/Linters/check_rust_address_keys.pyindex c6654a56209..8793145dddf 100755--- a/Meta/Linters/check_rust_address_keys.py+++ b/Meta/Linters/check_rust_address_keys.py@@ -46,11 +46,10 @@ ALLOWED = {"css/style/pipeline/custom_properties.rs": 4,"css/style/pipeline/custom_property_moves.rs": 1,"css/style/pipeline/install.rs": 1,- "css/style/pipeline/records.rs": 3,- "css/style/pipeline/results.rs": 1,+ "css/style/pipeline/records.rs": 2,"css/style/pipeline/rules.rs": 2,"css/style/pipeline/sharing.rs": 1,- "css/style/pipeline/traversal.rs": 5,+ "css/style/pipeline/traversal.rs": 3,"css/style_compute/ffi_test_stubs.rs": 1,"layout/layout_node_arena.rs": 1,}diff --git a/Tests/LibWeb/Text/expected/css/style-engine/persistent-style-sharing-cssom-revision.txt b/Tests/LibWeb/Text/expected/css/style-engine/persistent-style-sharing-cssom-revision.txtindex 19fba01aea6..a3cfcd9f2de 100644--- a/Tests/LibWeb/Text/expected/css/style-engine/persistent-style-sharing-cssom-revision.txt+++ b/Tests/LibWeb/Text/expected/css/style-engine/persistent-style-sharing-cssom-revision.txt@@ -1,4 +1,4 @@-shared or reused across transactions: 0+shared or reused across transactions: 1initial colors: rgb(255, 0, 0), rgb(255, 0, 0)CSSOM mutation colors: rgb(0, 128, 0), rgb(0, 128, 0)inline mutation colors: rgb(0, 0, 255), rgb(0, 128, 0)diff --git a/Tests/LibWeb/Text/input/css/style-engine/persistent-style-sharing-cssom-revision.html b/Tests/LibWeb/Text/input/css/style-engine/persistent-style-sharing-cssom-revision.htmlindex 0e3a7d9f379..0502149eeea 100644--- a/Tests/LibWeb/Text/input/css/style-engine/persistent-style-sharing-cssom-revision.html+++ b/Tests/LibWeb/Text/input/css/style-engine/persistent-style-sharing-cssom-revision.html@@ -17,8 +17,7 @@internals.updateStyle();const counters = internals.styleCounters();- // FIXME: The arriving span should take the record of the one styled in an earlier pass- // (shared or reused >= 1), but the style engine shares records only within a pass.+ // NB: The arriving span takes the record of the one styled in an earlier pass.println(`shared or reused across transactions: ${counters.sharedElements + counters.reusedElements}`);println(`initial colors: ${getComputedStyle(first).color}, ${getComputedStyle(second).color}`);