Truly independent web browser
LibWeb: Allocate less for each selector that is parsed
Andreas Klingaa22793da8a5
diff --git a/Libraries/LibWeb/Rust/src/css/selector_arena.rs b/Libraries/LibWeb/Rust/src/css/selector_arena.rsindex 4927bcfc2a9..8f5cb2cf8b2 100644--- a/Libraries/LibWeb/Rust/src/css/selector_arena.rs+++ b/Libraries/LibWeb/Rust/src/css/selector_arena.rs@@ -1869,35 +1869,47 @@ impl Builder {return None;}self.nesting = nesting;- // NB: The parser finished every nested list before the list naming it; they go first.- let selectors: Vec<Vec<(Combinator, bool, Vec<Component>)>> = list- .iter()- .map(|selector| {- selector- .compound_selectors()- .iter()- .map(|compound| {- let components = compound- .simple_selectors- .iter()- .map(|simple| self.component(simple))- .collect::<Vec<_>>();- (compound.combinator, compound.is_implicit_universal_anchor, components)- })- .collect()- })- .collect();- let start = ListStart(index_u32(self.components.len()));- let count = selectors.len();- for (index, compounds) in selectors.into_iter().enumerate() {- let leading = compounds.first().map_or(Combinator::None, |compound| compound.0);- let compound_count = compounds.len();- for (position, (combinator, implicit_anchor, mut components)) in compounds.into_iter().rev().enumerate() {- assert!(!components.is_empty(), "a compound holds a simple selector");- if implicit_anchor {- components[0].bits = components[0].bits.with(IMPLICIT, true);+ // NB: The parser finished every nested list before the list naming it; they go first. The components of the+ // list wait here until each nested list is in the arena.+ let mut components = SmallVec::<[Component; 16]>::new();+ // Where each compound ends in `components`, with its combinator, and how many compounds each selector has.+ let mut compounds = SmallVec::<[(Combinator, u32); 8]>::new();+ let mut compound_counts = SmallVec::<[u32; 4]>::new();+ for selector in list {+ let selector_compounds = selector.compound_selectors();+ for compound in &selector_compounds {+ assert!(+ !compound.simple_selectors.is_empty(),+ "a compound holds a simple selector"+ );+ let first = components.len();+ for simple in compound.simple_selectors {+ let component = self.component(simple);+ components.push(component);+ }+ if compound.is_implicit_universal_anchor {+ components[first].bits = components[first].bits.with(IMPLICIT, true);}- let leftmost = position + 1 == compound_count;+ compounds.push((compound.combinator, index_u32(components.len())));+ }+ compound_counts.push(index_u32(selector_compounds.len()));+ }+ let start = ListStart(index_u32(self.components.len()));+ let count = compound_counts.len();+ let mut first_compound = 0;+ for (index, &compound_count) in compound_counts.iter().enumerate() {+ let compound_count = compound_count as usize;+ let selector_compounds = &compounds[first_compound..first_compound + compound_count];+ let leading = selector_compounds+ .first()+ .map_or(Combinator::None, |compound| compound.0);+ for position in (0..compound_count).rev() {+ let (combinator, end) = selector_compounds[position];+ let compound_start = match first_compound + position {+ 0 => 0,+ previous => compounds[previous - 1].1 as usize,+ };+ let leftmost = position == 0;let relation = match leftmost {true if leading != Combinator::None => Relation::of(leading),true => Relation::Leftmost,@@ -1910,12 +1922,13 @@ impl Builder {Relation::of(combinator)}};- let last = components.len() - 1;+ let last = end as usize - 1;components[last].bits = components[last].bits.with_relation(relation);if relation == Relation::Leftmost && index + 1 == count {components[last].bits = components[last].bits.with(LAST_IN_LIST, true);}- self.components.extend(components);+ self.components+ .extend_from_slice(&components[compound_start..end as usize]);}if leading != Combinator::None {let bits = ComponentBits::new(ComponentKind::RelativeAnchor)@@ -1924,6 +1937,7 @@ impl Builder {.with(LAST_IN_LIST, index + 1 == count);self.components.push(Component { bits, data: 0 });}+ first_compound += compound_count;}Some(start)}diff --git a/Libraries/LibWeb/Rust/src/css/selector_parser.rs b/Libraries/LibWeb/Rust/src/css/selector_parser.rsindex 2c4b71c96bf..63537e02144 100644--- a/Libraries/LibWeb/Rust/src/css/selector_parser.rs+++ b/Libraries/LibWeb/Rust/src/css/selector_parser.rs@@ -7,6 +7,7 @@//! CSS selector parsing.use crate::css::ffi_support::OwnedBox;+use smallvec::SmallVec;use std::sync::Arc;use super::css_tokenizer::{TokenizerInput, filter_code_points};@@ -67,6 +68,16 @@ fn lowercase(value: &[u16]) -> SelectorString {.into()}+/// The values of `values` in a box, which one allocation makes.+fn boxed<T, const N: usize>(mut values: SmallVec<[T; N]>) -> Box<[T]>+where+ [T; N]: smallvec::Array<Item = T>,+{+ let mut result = Vec::with_capacity(values.len());+ result.extend(values.drain(..));+ result.into_boxed_slice()+}+fn pseudo_class_selector(pseudo_class: PseudoClassType) -> PseudoClassSelector {PseudoClassSelector {pseudo_class,@@ -350,7 +361,7 @@ impl<'a> SelectorParser<'a> {self.nesting_limit_exceeded = true;return Err(());}- let mut selectors = Vec::new();+ let mut selectors = SmallVec::<[Arc<CompiledSelector>; 4]>::new();let mut rest = values;let mut is_first = true;while let Some(selector_values) = rest.split_at_comma(is_first) {@@ -382,7 +393,7 @@ impl<'a> SelectorParser<'a> {if selectors.is_empty() && parsing_mode != SelectorParsingMode::Forgiving {return Err(());}- Ok(selectors.into_boxed_slice())+ Ok(boxed(selectors))}fn parse_complex_selector(@@ -410,7 +421,8 @@ impl<'a> SelectorParser<'a> {return Err(());}first.combinator = first_combinator.unwrap_or(Combinator::None);- let mut compounds = vec![first];+ let mut compounds = SmallVec::<[CompoundSelector; 4]>::new();+ compounds.push(first);while !stream.is_empty() {let Some(combinator) = self.parse_combinator(&mut stream) else {@@ -507,7 +519,7 @@ impl<'a> SelectorParser<'a> {return Err(());}}- Ok(CompiledSelector::new(compounds.into_boxed_slice()))+ Ok(CompiledSelector::from_compounds(compounds))}fn parse_qualified_name(&self, stream: &mut Values<'_>, allow_wildcard: bool) -> Option<QualifiedName> {@@ -1083,12 +1095,15 @@ impl<'a> SelectorParser<'a> {Ok(CompoundSelector {combinator: Combinator::None,is_implicit_universal_anchor: false,- simple_selectors: simple_selectors?.into_boxed_slice(),+ simple_selectors: boxed(simple_selectors?),})}- fn parse_compound_simple_selectors(&mut self, stream: &mut Values<'_>) -> Result<Vec<SimpleSelector>, ()> {- let mut simple_selectors = Vec::new();+ fn parse_compound_simple_selectors(+ &mut self,+ stream: &mut Values<'_>,+ ) -> Result<SmallVec<[SimpleSelector; 4]>, ()> {+ let mut simple_selectors = SmallVec::new();while let Some(simple_selector) = self.parse_simple_selector(stream)? {if matches!(simple_selector,@@ -1146,7 +1161,7 @@ fn contains_pseudo_element(selector: &CompiledSelector) -> bool {})}-fn normalize_pseudo_element_transitions(compounds: Vec<CompoundSelector>) -> Vec<CompoundSelector> {+fn normalize_pseudo_element_transitions(compounds: SmallVec<[CompoundSelector; 4]>) -> SmallVec<[CompoundSelector; 4]> {if !compounds.iter().any(|compound| {compound.simple_selectors@@ -1156,7 +1171,7 @@ fn normalize_pseudo_element_transitions(compounds: Vec<CompoundSelector>) -> Vecreturn compounds;}- let mut normalized = Vec::new();+ let mut normalized = SmallVec::new();for compound in compounds {let mut combinator = compound.combinator;let mut current = Vec::new();@@ -1378,14 +1393,13 @@ fn parse_pseudo_element_selector(return Err(());}let pseudo_element_type = pseudo_element.pseudo_element;- let selector = CompiledSelector::new(- normalize_pseudo_element_transitions(vec![CompoundSelector {- combinator: Combinator::None,- is_implicit_universal_anchor: false,- simple_selectors: Box::new([simple]),- }])- .into_boxed_slice(),- );+ let mut compounds = SmallVec::new();+ compounds.push(CompoundSelector {+ combinator: Combinator::None,+ is_implicit_universal_anchor: false,+ simple_selectors: Box::new([simple]),+ });+ let selector = CompiledSelector::from_compounds(normalize_pseudo_element_transitions(compounds));let list = SelectorListRef::pack(&[selector]);let selector = list.owned().next().expect("the list holds the selector");Ok((selector, pseudo_element_type))diff --git a/Libraries/LibWeb/Rust/src/css/selector_tree.rs b/Libraries/LibWeb/Rust/src/css/selector_tree.rsindex fe0e0f8c4b6..21431c6282f 100644--- a/Libraries/LibWeb/Rust/src/css/selector_tree.rs+++ b/Libraries/LibWeb/Rust/src/css/selector_tree.rs@@ -144,6 +144,10 @@ pub struct CompiledSelector {impl CompiledSelector {pub(crate) fn new(compound_selectors: Box<[CompoundSelector]>) -> Arc<Self> {+ Self::from_compounds(compound_selectors.into_vec().into())+ }++ pub(crate) fn from_compounds(compound_selectors: SmallVec<[CompoundSelector; 4]>) -> Arc<Self> {let count = compound_selectors.iter().map(|compound| compound.simple_selectors.len() + 1)