Truly independent web browser
LibWeb: Drop scope dispatch templates that no scope program uses
Andreas Kling0c807efbbe73
diff --git a/Libraries/LibWeb/Rust/src/css/style/catalog.rs b/Libraries/LibWeb/Rust/src/css/style/catalog.rsindex 6df9e637f67..188e2c67bd2 100644--- a/Libraries/LibWeb/Rust/src/css/style/catalog.rs+++ b/Libraries/LibWeb/Rust/src/css/style/catalog.rs@@ -2089,9 +2089,18 @@ impl super::intern_table::InternIdentity for ScopeProgramID {pub(super) struct ScopeProgram {pub(super) key: ScopeDispatchKey,pub(super) dispatch: Arc<RuleDispatch>,+ /// The shapes the dispatch is filed under among the templates, which stay while a program has them.+ pub(super) shapes: ScopeTemplateShapes,pub(super) scope_count: u32,}+/// The shapes one scope program's dispatch is filed under among the scope templates.+#[derive(Clone)]+pub(super) struct ScopeTemplateShapes {+ pub(super) dispatch: ScopeDispatchShape,+ pub(super) cascade: ScopeCascadeShape,+}+#[derive(Clone)]pub(super) struct ReplacedStyleRule {diff --git a/Libraries/LibWeb/Rust/src/css/style/index.rs b/Libraries/LibWeb/Rust/src/css/style/index.rsindex 675aaf52caa..640d229a4cb 100644--- a/Libraries/LibWeb/Rust/src/css/style/index.rs+++ b/Libraries/LibWeb/Rust/src/css/style/index.rs@@ -2318,6 +2318,16 @@ pub(super) struct AncestorDispatchTopology {residency: MemoryLease,}+impl AncestorDispatchTopology {+ pub(super) fn shape(&self) -> AncestorDispatchShape {+ let mut keys = vec![DispatchKey::Universal; self.key_indices.len()];+ for (&key, &index) in &self.key_indices {+ keys[index as usize] = key;+ }+ AncestorDispatchShape(keys)+ }+}+impl Clone for AncestorDispatchTopology {fn clone(&self) -> Self {Self {@@ -2595,12 +2605,7 @@ impl RuleDispatch {}pub(super) fn ancestor_dispatch_shape(&self) -> AncestorDispatchShape {- let key_indices = &self.topology.ancestors.key_indices;- let mut keys = vec![DispatchKey::Universal; key_indices.len()];- for (&key, &index) in key_indices {- keys[index as usize] = key;- }- AncestorDispatchShape(keys)+ self.topology.ancestors.shape()}pub(super) fn ancestor_topology(&self) -> Arc<AncestorDispatchTopology> {diff --git a/Libraries/LibWeb/Rust/src/css/style/inputs.rs b/Libraries/LibWeb/Rust/src/css/style/inputs.rsindex ebe155b5179..7f924a4c928 100644--- a/Libraries/LibWeb/Rust/src/css/style/inputs.rs+++ b/Libraries/LibWeb/Rust/src/css/style/inputs.rs@@ -2109,6 +2109,8 @@ impl StyleEngine {scope_dispatch_templates: HashMap::default(),scope_cascade_templates: HashMap::default(),ancestor_dispatch_templates: Default::default(),+ retired_scope_templates: Vec::new(),+ scope_templates_need_sweep: false,scope_program_by_scope: Column::default(),atoms: crate::fork::ForkShared::new(DocumentAtoms::for_live_engine()),fold_id_and_class_name_case: false,@@ -3534,6 +3536,8 @@ impl RetainedState {scope_dispatch_templates: _,scope_cascade_templates: _,ancestor_dispatch_templates: _,+ retired_scope_templates: _,+ scope_templates_need_sweep: _,scope_program_by_scope: _,atoms: _,html_element_namespace: _,diff --git a/Libraries/LibWeb/Rust/src/css/style/matching.rs b/Libraries/LibWeb/Rust/src/css/style/matching.rsindex ad858a7af1e..4c19b088924 100644--- a/Libraries/LibWeb/Rust/src/css/style/matching.rs+++ b/Libraries/LibWeb/Rust/src/css/style/matching.rs@@ -839,7 +839,10 @@ impl RetainedState {}/// Build one scope's selector dispatch and rank its static cascade priorities once.- pub(super) fn build_ranked_scope_dispatch(&mut self, scope: TreeScopeID) -> Arc<RuleDispatch> {+ pub(super) fn build_ranked_scope_dispatch(+ &mut self,+ scope: TreeScopeID,+ ) -> (Arc<RuleDispatch>, ScopeTemplateShapes) {let (mut shape, mut rules) = scope_dispatch_shape_and_rules(&self.program, &self.programs, scope);let document_sheet_mode = if scope == TreeScopeID::DOCUMENT {DocumentSheetMode::None@@ -989,15 +992,127 @@ impl RetainedState {dispatch_pools().dispatches.templates.insert(key, dispatch.downgrade());}self.scope_cascade_templates- .entry(cascade_shape)+ .entry(cascade_shape.clone()).or_insert_with(|| Arc::clone(&dispatch));self.scope_dispatch_templates- .entry(shape)+ .entry(shape.clone()).or_insert_with(|| Arc::clone(&dispatch));self.ancestor_dispatch_templates.entry(ancestor_shape).or_insert_with(|| dispatch.ancestor_topology());- dispatch+ self.scope_templates_need_sweep = true;+ let shapes = ScopeTemplateShapes {+ dispatch: shape,+ cascade: cascade_shape,+ };+ (dispatch, shapes)+ }++ /// Drops the templates no live scope program has the shape of. Each style transaction+ /// prepares its scopes first, so the templates a rebuild after a program change seeds from+ /// have served by the time it ends. Sheets that arrive one at a time give every intermediate+ /// sheet set its own shape, and each of those templates would otherwise keep a complete+ /// dispatch alive for the rest of the document's life.+ ///+ /// The templates of the last removed program whose shape no live shape has or extends, the way+ /// sheets arriving after it do, stay too, so that a page switching between two sheet sets+ /// rebinds them. A template kept for a live shape is replaced by a live dispatch of that+ /// shape, as an equivalent template that keeps no other dispatch alive.+ // NB: The shapes' interior mutability is the memory charge of their shared storage, which hashing and comparing+ // them does not read.+ #[allow(clippy::mutable_key_type)]+ pub(super) fn drop_unused_scope_templates(&mut self) {+ if !std::mem::take(&mut self.scope_templates_need_sweep) {+ return;+ }+ let mut live_dispatches = HashMap::<&ScopeDispatchShape, &Arc<RuleDispatch>>::default();+ let mut live_cascades = HashMap::<&ScopeCascadeShape, &Arc<RuleDispatch>>::default();+ let mut live_ancestors = HashMap::<AncestorDispatchShape, Arc<index::AncestorDispatchTopology>>::default();+ for program in self.scope_programs.iter().flatten() {+ live_dispatches+ .entry(&program.shapes.dispatch)+ .or_insert(&program.dispatch);+ live_cascades+ .entry(&program.shapes.cascade)+ .or_insert(&program.dispatch);+ live_ancestors+ .entry(program.dispatch.ancestor_dispatch_shape())+ .or_insert_with(|| program.dispatch.ancestor_topology());+ }+ // NB: A program removed while another of its shape replaces it, as an unrelated change does, keeps nothing+ // the live templates do not, so an earlier removal keeps its templates instead.+ let retired_index = self.retired_scope_templates.iter().rposition(|(shapes, _)| {+ !live_dispatches+ .keys()+ .any(|live| live.0.len() >= shapes.dispatch.0.len() && live.0.starts_with(&shapes.dispatch.0))+ });+ let retired = retired_index.map(|index| &self.retired_scope_templates[index]);+ let retired_ancestor_shape = retired.map(|(_, ancestors)| ancestors.shape());+ self.scope_dispatch_templates+ .retain(|shape, template| match live_dispatches.get(shape) {+ Some(live) => {+ if !Arc::ptr_eq(live, template) {+ *template = Arc::clone(live);+ }+ true+ }+ None => retired.is_some_and(|(shapes, _)| shapes.dispatch == *shape),+ });+ self.scope_cascade_templates+ .retain(|shape, template| match live_cascades.get(shape) {+ Some(live) => {+ if !Arc::ptr_eq(live, template) {+ *template = Arc::clone(live);+ }+ true+ }+ None => retired.is_some_and(|(shapes, _)| shapes.cascade == *shape),+ });+ let ancestor_template_is_current =+ |shape: &AncestorDispatchShape, template: &Arc<index::AncestorDispatchTopology>| match live_ancestors+ .get(shape)+ {+ Some(live) => Arc::ptr_eq(live, template),+ None => retired_ancestor_shape.as_ref() == Some(shape),+ };+ // NB: The table is shared copy-on-write with forks; only a change may unshare it.+ if !self+ .ancestor_dispatch_templates+ .iter()+ .all(|(shape, template)| ancestor_template_is_current(shape, template))+ {+ self.ancestor_dispatch_templates+ .retain(|shape, template| match live_ancestors.get(shape) {+ Some(live) => {+ *template = Arc::clone(live);+ true+ }+ None => retired_ancestor_shape.as_ref() == Some(shape),+ });+ }+ let kept = retired_index.and_then(|index| self.retired_scope_templates.drain(..).nth(index));+ self.retired_scope_templates.clear();+ self.retired_scope_templates.extend(kept);+ dispatch_pools()+ .dispatches+ .templates+ .retain(|_, template| template.is_alive());+ }++ /// Remove a scope program no concrete scope resolves to any more, keeping its templates as+ /// the retired ones.+ pub(super) fn remove_scope_program(&mut self, id: ScopeProgramID) {+ let mut caches = self.prefix_caches.borrow_mut();+ caches.states.remove(id);+ caches.answers.remove_program(&mut self.match_answers, id);+ drop(caches);+ let program = self.scope_programs[id].take().unwrap();+ let hash = intern_table::content_hash(&program.key);+ self.scope_programs.remove_identity(hash, id);+ self.vacant_scope_programs.push(id);+ self.retired_scope_templates+ .push((program.shapes, program.dispatch.ancestor_topology()));+ self.scope_templates_need_sweep = true;}pub(super) fn scope_dispatch_key(&self, scope: TreeScopeID) -> ScopeDispatchKey {@@ -1045,13 +1160,7 @@ impl RetainedState {if program.scope_count != 0 {return;}- let mut caches = self.prefix_caches.borrow_mut();- caches.states.remove(id);- caches.answers.remove_program(&mut self.match_answers, id);- let program = self.scope_programs[id].take().unwrap();- let hash = intern_table::content_hash(&program.key);- self.scope_programs.remove_identity(hash, id);- self.vacant_scope_programs.push(id);+ self.remove_scope_program(id);}pub(super) fn intern_scope_program(&mut self, scope: TreeScopeID, key: ScopeDispatchKey) -> ScopeProgramID {@@ -1067,10 +1176,11 @@ impl RetainedState {let id = self.vacant_scope_programs.pop().unwrap_or_else(|| {ScopeProgramID(u32::try_from(self.scope_programs.len()).expect("scope program identity space exhausted"))});- let dispatch = self.build_ranked_scope_dispatch(scope);+ let (dispatch, shapes) = self.build_ranked_scope_dispatch(scope);let program = ScopeProgram {key,dispatch,+ shapes,scope_count: 1,};self.scope_programs.insert(hash, id, Some(program));@@ -1867,7 +1977,7 @@ impl RetainedState {);}let truth = Arc::clone(self.selector_truth_sets.get(identity));- let dispatch = self.build_ranked_scope_dispatch(tree_scope);+ let (dispatch, _) = self.build_ranked_scope_dispatch(tree_scope);let mut derived = RuleMatches::new();append_selector_truth_matches(&mut derived,diff --git a/Libraries/LibWeb/Rust/src/css/style/mod.rs b/Libraries/LibWeb/Rust/src/css/style/mod.rsindex 881200a5c71..7bea133ecff 100644--- a/Libraries/LibWeb/Rust/src/css/style/mod.rs+++ b/Libraries/LibWeb/Rust/src/css/style/mod.rs@@ -1085,6 +1085,12 @@ pub struct RetainedState {/// unchanged. Keep only the table so sharing it cannot retain an obsolete selector dispatch.ancestor_dispatch_templates:crate::fork::ForkShared<HashMap<AncestorDispatchShape, Arc<index::AncestorDispatchTopology>>>,+ /// The shapes of the scope programs removed since the unused templates were last dropped, oldest first, and the+ /// ancestor table of each one's dispatch. The templates of the last one no live program has the shape of outlive+ /// it, so a page that switches back to the sheet set it ranked rebinds them instead of building its dispatch again.+ retired_scope_templates: Vec<(ScopeTemplateShapes, Arc<index::AncestorDispatchTopology>)>,+ /// Whether a scope program was removed or a template was filed since the unused templates were last dropped.+ scope_templates_need_sweep: bool,/// The shared program each concrete tree scope resolved to. Program changes clear the table,/// while a depth change replaces only this scope's identity. It uses the same direct tree-scope/// index as the root column.diff --git a/Libraries/LibWeb/Rust/src/css/style/ordering.rs b/Libraries/LibWeb/Rust/src/css/style/ordering.rsindex f029845d187..94d2fc40035 100644--- a/Libraries/LibWeb/Rust/src/css/style/ordering.rs+++ b/Libraries/LibWeb/Rust/src/css/style/ordering.rs@@ -2052,6 +2052,20 @@ impl RetainedState {referenced[program.0 as usize] = true;}self.match_answers.mark_referenced_selector_programs(&mut referenced);+ // NB: A scope program's shape names selector programs, and the templates follow the shapes of live scope+ // programs. Keep the selector programs of those scopes resolve to, and drop below the ones no scope+ // resolves to that name a recycled selector program, so that no live shape names a recycled identity.+ for program in self.scope_programs.iter().flatten() {+ if program.scope_count == 0 {+ continue;+ }+ for &(selector_program, _) in program.shapes.dispatch.0.iter() {+ if referenced.len() <= selector_program.0 as usize {+ referenced.resize(selector_program.0 as usize + 1, false);+ }+ referenced[selector_program.0 as usize] = true;+ }+ }if !self.programs.has_unreferenced_programs(&referenced) {self.selector_programs_need_sweep = false;return;@@ -2088,8 +2102,28 @@ impl RetainedState {.iter().all(|&(program, _)| referenced.get(program.0 as usize).copied().unwrap_or(false))});+ let names_swept_program = |shapes: &ScopeTemplateShapes| {+ shapes+ .dispatch+ .0+ .iter()+ .any(|&(program, _)| !referenced.get(program.0 as usize).copied().unwrap_or(false))+ };+ let stale_scope_programs = (0..self.scope_programs.len())+ .filter(|&index| {+ self.scope_programs[index]+ .as_ref()+ .is_some_and(|program| names_swept_program(&program.shapes))+ })+ .map(|index| ScopeProgramID(u32::try_from(index).expect("scope program identity space exhausted")))+ .collect::<Vec<_>>();+ for id in stale_scope_programs {+ self.remove_scope_program(id);+ }self.scope_cascade_templates.clear();self.ancestor_dispatch_templates.clear();+ // NB: The retired shapes may name swept selector programs, whose identities are recycled.+ self.retired_scope_templates.clear();self.programs.sweep_unreferenced(&referenced);self.programs.settle_memory(&mut self.memory);self.selector_programs_need_sweep = false;@@ -2231,6 +2265,7 @@ impl StyleEngine {self.host.program_staging.clear();self.host.environment_move_changed_names.clear();self.sweep_selector_programs();+ self.retained.drop_unused_scope_templates();self.shed_routing_for_detached_sheets();}diff --git a/Libraries/LibWeb/Rust/src/css/style/program_updates.rs b/Libraries/LibWeb/Rust/src/css/style/program_updates.rsindex 8d60292e5d9..caca5d29079 100644--- a/Libraries/LibWeb/Rust/src/css/style/program_updates.rs+++ b/Libraries/LibWeb/Rust/src/css/style/program_updates.rs@@ -167,14 +167,7 @@ impl RetainedState {continue;}let id = ScopeProgramID(u32::try_from(index).expect("scope program identity space exhausted"));- let mut caches = self.prefix_caches.borrow_mut();- caches.states.remove(id);- caches.answers.remove_program(&mut self.match_answers, id);- drop(caches);- let program = self.scope_programs[id].take().unwrap();- self.scope_programs- .remove_identity(intern_table::content_hash(&program.key), id);- self.vacant_scope_programs.push(id);+ self.remove_scope_program(id);}for program in self.scope_programs.iter_mut().flatten() {program.scope_count = 0;diff --git a/Libraries/LibWeb/Rust/src/css/style/tests.rs b/Libraries/LibWeb/Rust/src/css/style/tests.rsindex f2a2883a719..1ca0eb5dad3 100644--- a/Libraries/LibWeb/Rust/src/css/style/tests.rs+++ b/Libraries/LibWeb/Rust/src/css/style/tests.rs@@ -10301,6 +10301,125 @@ fn equivalent_sheet_programs_share_dispatch_topology() {);}+#[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();