Skip to main content

style/sharing/
mod.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! Code related to the style sharing cache, an optimization that allows similar
6//! nodes to share style without having to run selector matching twice.
7//!
8//! The basic setup is as follows.  We have an LRU cache of style sharing
9//! candidates.  When we try to style a target element, we first check whether
10//! we can quickly determine that styles match something in this cache, and if
11//! so we just use the cached style information.  This check is done with a
12//! StyleBloom filter set up for the target element, which may not be a correct
13//! state for the cached candidate element if they're cousins instead of
14//! siblings.
15//!
16//! The complicated part is determining that styles match.  This is subject to
17//! the following constraints:
18//!
19//! 1) The target and candidate must be inheriting the same styles.
20//! 2) The target and candidate must have exactly the same rules matching them.
21//! 3) The target and candidate must have exactly the same non-selector-based
22//!    style information (inline styles, presentation hints).
23//! 4) The target and candidate must have exactly the same rules matching their
24//!    pseudo-elements, because an element's style data points to the style
25//!    data for its pseudo-elements.
26//!
27//! These constraints are satisfied in the following ways:
28//!
29//! * We check that the parents of the target and the candidate have the same
30//!   computed style.  This addresses constraint 1.
31//!
32//! * We check that the target and candidate have the same inline style and
33//!   presentation hint declarations.  This addresses constraint 3.
34//!
35//! * We ensure that a target matches a candidate only if they have the same
36//!   matching result for all selectors that target either elements or the
37//!   originating elements of pseudo-elements.  This addresses constraint 4
38//!   (because it prevents a target that has pseudo-element styles from matching
39//!   a candidate that has different pseudo-element styles) as well as
40//!   constraint 2.
41//!
42//! The actual checks that ensure that elements match the same rules are
43//! conceptually split up into two pieces.  First, we do various checks on
44//! elements that make sure that the set of possible rules in all selector maps
45//! in the stylist (for normal styling and for pseudo-elements) that might match
46//! the two elements is the same.  For example, we enforce that the target and
47//! candidate must have the same localname and namespace.  Second, we have a
48//! selector map of "revalidation selectors" that the stylist maintains that we
49//! actually match against the target and candidate and then check whether the
50//! two sets of results were the same.  Due to the up-front selector map checks,
51//! we know that the target and candidate will be matched against the same exact
52//! set of revalidation selectors, so the match result arrays can be compared
53//! directly.
54//!
55//! It's very important that a selector be added to the set of revalidation
56//! selectors any time there are two elements that could pass all the up-front
57//! checks but match differently against some ComplexSelector in the selector.
58//! If that happens, then they can have descendants that might themselves pass
59//! the up-front checks but would have different matching results for the
60//! selector in question.  In this case, "descendants" includes pseudo-elements,
61//! so there is a single selector map of revalidation selectors that includes
62//! both selectors targeting elements and selectors targeting pseudo-element
63//! originating elements.  We ensure that the pseudo-element parts of all these
64//! selectors are effectively stripped off, so that matching them all against
65//! elements makes sense.
66
67use crate::bloom::StyleBloom;
68use crate::computed_value_flags::ComputedValueFlags;
69use crate::context::{CascadeInputs, SharedStyleContext, StyleContext};
70use crate::dom::{SendElement, TElement, TNode};
71use crate::properties::ComputedValues;
72use crate::rule_tree::StyleSource;
73use crate::selector_map::RelevantAttributes;
74use crate::style_resolver::{PrimaryStyle, ResolvedElementStyles};
75use crate::stylist::Stylist;
76use crate::values::AtomIdent;
77use atomic_refcell::{AtomicRefCell, AtomicRefMut};
78use selectors::matching::{NeedsSelectorFlags, SelectorCaches, VisitedHandlingMode};
79use smallbitvec::SmallBitVec;
80use smallvec::SmallVec;
81use std::marker::PhantomData;
82use std::mem;
83use std::ops::Deref;
84use std::ptr::NonNull;
85use thin_vec::ThinVec;
86use uluru::LRUCache;
87
88mod checks;
89
90/// The amount of nodes that the style sharing candidate cache should hold at most.
91///
92/// The cache size was chosen by measuring style sharing and resulting performance on a few pages;
93/// sizes up to about 32 were giving good sharing improvements (e.g. 3x fewer styles having to be
94/// resolved than at size 8) and slight performance improvements.  Sizes larger than 32 haven't
95/// really been tested.
96pub const SHARING_CACHE_SIZE: usize = 32;
97
98/// The max amount of DOM depths we keep around to share styles across. See bug 2052731.
99const SHARING_MAX_LEVELS: usize = 8;
100
101/// Opaque pointer type to compare ComputedValues identities.
102#[derive(Clone, Debug, Eq, PartialEq)]
103pub struct OpaqueComputedValues(NonNull<()>);
104
105unsafe impl Send for OpaqueComputedValues {}
106unsafe impl Sync for OpaqueComputedValues {}
107
108impl OpaqueComputedValues {
109    fn from(cv: &ComputedValues) -> Self {
110        let p =
111            unsafe { NonNull::new_unchecked(cv as *const ComputedValues as *const () as *mut ()) };
112        OpaqueComputedValues(p)
113    }
114
115    fn eq(&self, cv: &ComputedValues) -> bool {
116        Self::from(cv) == *self
117    }
118}
119
120/// The results from the revalidation step.
121///
122/// Rather than either:
123///
124///  * Plainly rejecting sharing for elements with different attributes (which would be unfortunate
125///    because a lot of elements have different attributes yet those attributes are not
126///    style-relevant).
127///
128///  * Having to give up on per-attribute bucketing, which would be unfortunate because it
129///    increases the cost of revalidation for pages with lots of global attribute selectors (see
130///    bug 1868316).
131///
132///  * We also store the style-relevant attributes for these elements, in order to guarantee that
133///    we end up looking at the same selectors.
134///
135#[derive(Debug, Default)]
136pub struct RevalidationResult {
137    /// A bit for each selector matched. This is sound because we guarantee we look up into the
138    /// same buckets via the pre-revalidation checks and relevant_attributes.
139    pub selectors_matched: SmallBitVec,
140    /// The set of attributes of this element that were relevant for its style.
141    pub relevant_attributes: RelevantAttributes,
142}
143
144/// The results from trying to revalidate scopes this element is in.
145#[derive(Debug, Default, PartialEq)]
146pub struct ScopeRevalidationResult {
147    /// A bit for each scope activated.
148    pub scopes_matched: SmallBitVec,
149}
150
151impl PartialEq for RevalidationResult {
152    fn eq(&self, other: &Self) -> bool {
153        if self.relevant_attributes != other.relevant_attributes {
154            return false;
155        }
156
157        // This assert "ensures", to some extent, that the two candidates have matched the
158        // same rulehash buckets, and as such, that the bits we're comparing represent the
159        // same set of selectors.
160        debug_assert_eq!(self.selectors_matched.len(), other.selectors_matched.len());
161        self.selectors_matched == other.selectors_matched
162    }
163}
164
165/// We use this as an inline capacity for the class_list member below, but also as a reasonable cap
166/// to avoid sorting too large class lists.
167const REASONABLE_CLASS_LIST_SIZE: usize = 5;
168
169/// Some data we want to avoid recomputing all the time while trying to share style.
170#[derive(Debug, Default)]
171pub struct ValidationData {
172    /// The class list of this element.
173    ///
174    /// TODO(emilio): Maybe check whether rules for these classes apply to the element?
175    /// TODO(emilio): Maybe this should be another ThinVec... But classes are definitely more common
176    /// than everything else on this struct.
177    class_list: Option<SmallVec<[AtomIdent; REASONABLE_CLASS_LIST_SIZE]>>,
178
179    /// The part list of this element.
180    ///
181    /// TODO(emilio): Maybe check whether rules with these part names apply to
182    /// the element?
183    part_list: Option<ThinVec<AtomIdent>>,
184
185    /// The list of presentational attributes of the element.
186    ///
187    /// We only need the declaration blocks, since all the other fields of the applicable
188    /// declaration are the same for all presentational hints.
189    pres_hints: Option<ThinVec<StyleSource>>,
190
191    /// The pointer identity of the parent ComputedValues.
192    parent_style_identity: Option<OpaqueComputedValues>,
193
194    /// The cached result of matching this entry against the revalidation
195    /// selectors.
196    revalidation_match_results: Option<RevalidationResult>,
197}
198
199impl ValidationData {
200    /// Move the cached data to a new instance, and return it.
201    pub fn take(&mut self) -> Self {
202        std::mem::take(self)
203    }
204
205    /// Get or compute the list of presentational attributes associated with
206    /// this element.
207    pub fn pres_hints<E>(&mut self, element: E) -> &[StyleSource]
208    where
209        E: TElement,
210    {
211        self.pres_hints.get_or_insert_with(|| {
212            // This should basically never spill.
213            let mut pres_hints = SmallVec::<[_; 5]>::new();
214            element.synthesize_presentational_hints_for_legacy_attributes(
215                VisitedHandlingMode::AllLinksUnvisited,
216                &mut pres_hints,
217            );
218            ThinVec::from_iter(pres_hints.drain(..).map(|d| d.source.to_owned()))
219        })
220    }
221
222    /// Get or compute the part-list associated with this element.
223    pub fn part_list<E>(&mut self, element: E) -> &[AtomIdent]
224    where
225        E: TElement,
226    {
227        if !element.has_part_attr() {
228            return &[];
229        }
230        self.part_list.get_or_insert_with(|| {
231            let mut list = ThinVec::new();
232            element.each_part(|p| list.push(p.clone()));
233            // See below for the reasoning.
234            if list.len() <= REASONABLE_CLASS_LIST_SIZE {
235                list.sort_unstable_by_key(|a| a.get_hash());
236            }
237            list
238        })
239    }
240
241    /// Get or compute the class-list associated with this element.
242    pub fn class_list<E>(&mut self, element: E) -> &[AtomIdent]
243    where
244        E: TElement,
245    {
246        self.class_list.get_or_insert_with(|| {
247            let mut list = SmallVec::<[_; REASONABLE_CLASS_LIST_SIZE]>::new();
248            element.each_class(|c| list.push(c.clone()));
249            // Assuming there are a reasonable number of classes, sort them to so that we don't
250            // mistakenly reject sharing candidates when one element has "foo bar" and the other has
251            // "bar foo".
252            if list.len() <= REASONABLE_CLASS_LIST_SIZE {
253                list.sort_unstable_by_key(|a| a.get_hash());
254            }
255            list
256        })
257    }
258
259    /// Get or compute the parent style identity.
260    pub fn parent_style_identity<E>(&mut self, el: E) -> OpaqueComputedValues
261    where
262        E: TElement,
263    {
264        self.parent_style_identity
265            .get_or_insert_with(|| {
266                let parent = el.inheritance_parent().unwrap();
267
268                OpaqueComputedValues::from(parent.borrow_data().unwrap().styles.primary())
269            })
270            .clone()
271    }
272
273    /// Computes the revalidation results if needed, and returns it.
274    /// Inline so we know at compile time what bloom_known_valid is.
275    #[inline]
276    fn revalidation_match_results<E>(
277        &mut self,
278        element: E,
279        stylist: &Stylist,
280        bloom: &StyleBloom<E>,
281        selector_caches: &mut SelectorCaches,
282        bloom_known_valid: bool,
283        needs_selector_flags: NeedsSelectorFlags,
284    ) -> &RevalidationResult
285    where
286        E: TElement,
287    {
288        self.revalidation_match_results.get_or_insert_with(|| {
289            // The bloom filter may already be set up for our element.
290            // If it is, use it.  If not, we must be in a candidate
291            // (i.e. something in the cache), and the element is one
292            // of our cousins, not a sibling.  In that case, we'll
293            // just do revalidation selector matching without a bloom
294            // filter, to avoid thrashing the filter.
295            let bloom_to_use = if bloom_known_valid {
296                debug_assert_eq!(bloom.current_parent(), element.traversal_parent());
297                Some(bloom.filter())
298            } else if bloom.current_parent() == element.traversal_parent() {
299                Some(bloom.filter())
300            } else {
301                None
302            };
303            stylist.match_revalidation_selectors(
304                element,
305                bloom_to_use,
306                selector_caches,
307                needs_selector_flags,
308            )
309        })
310    }
311}
312
313/// Information regarding a style sharing candidate, that is, an entry in the
314/// style sharing cache.
315///
316/// Note that this information is stored in TLS and cleared after the traversal,
317/// and once here, the style information of the element is immutable, so it's
318/// safe to access.
319#[derive(Debug)]
320pub struct StyleSharingCandidate<E> {
321    /// The element.
322    element: E,
323    validation_data: ValidationData,
324    considered_nontrivial_scoped_style: bool,
325}
326
327impl<E: TElement> Deref for StyleSharingCandidate<E> {
328    type Target = E;
329
330    fn deref(&self) -> &Self::Target {
331        &self.element
332    }
333}
334
335impl<E: TElement> StyleSharingCandidate<E> {
336    /// Get the classlist of this candidate.
337    fn class_list(&mut self) -> &[AtomIdent] {
338        self.validation_data.class_list(self.element)
339    }
340
341    /// Get the part list of this candidate.
342    fn part_list(&mut self) -> &[AtomIdent] {
343        self.validation_data.part_list(self.element)
344    }
345
346    /// Get the pres hints of this candidate.
347    fn pres_hints(&mut self) -> &[StyleSource] {
348        self.validation_data.pres_hints(self.element)
349    }
350
351    /// Get the parent style identity.
352    fn parent_style_identity(&mut self) -> OpaqueComputedValues {
353        self.validation_data.parent_style_identity(self.element)
354    }
355
356    /// Compute the bit vector of revalidation selector match results
357    /// for this candidate.
358    fn revalidation_match_results(
359        &mut self,
360        stylist: &Stylist,
361        bloom: &StyleBloom<E>,
362        selector_caches: &mut SelectorCaches,
363    ) -> &RevalidationResult {
364        self.validation_data.revalidation_match_results(
365            self.element,
366            stylist,
367            bloom,
368            selector_caches,
369            /* bloom_known_valid = */ false,
370            // The candidate must already have the right bits already, if
371            // needed.
372            NeedsSelectorFlags::No,
373        )
374    }
375
376    fn scope_revalidation_results(
377        &mut self,
378        stylist: &Stylist,
379        selector_caches: &mut SelectorCaches,
380    ) -> ScopeRevalidationResult {
381        stylist.revalidate_scopes(&self.element, selector_caches, NeedsSelectorFlags::No)
382    }
383}
384
385impl<E: TElement> PartialEq<StyleSharingCandidate<E>> for StyleSharingCandidate<E> {
386    fn eq(&self, other: &Self) -> bool {
387        self.element == other.element
388    }
389}
390
391/// An element we want to test against the style sharing cache.
392pub struct StyleSharingTarget<E: TElement> {
393    element: E,
394    validation_data: ValidationData,
395}
396
397impl<E: TElement> Deref for StyleSharingTarget<E> {
398    type Target = E;
399
400    fn deref(&self) -> &Self::Target {
401        &self.element
402    }
403}
404
405impl<E: TElement> StyleSharingTarget<E> {
406    /// Trivially construct a new StyleSharingTarget to test against the cache.
407    pub fn new(element: E) -> Self {
408        Self {
409            element,
410            validation_data: ValidationData::default(),
411        }
412    }
413
414    fn class_list(&mut self) -> &[AtomIdent] {
415        self.validation_data.class_list(self.element)
416    }
417
418    fn part_list(&mut self) -> &[AtomIdent] {
419        self.validation_data.part_list(self.element)
420    }
421
422    /// Get the pres hints of this candidate.
423    fn pres_hints(&mut self) -> &[StyleSource] {
424        self.validation_data.pres_hints(self.element)
425    }
426
427    /// Get the parent style identity.
428    fn parent_style_identity(&mut self) -> OpaqueComputedValues {
429        self.validation_data.parent_style_identity(self.element)
430    }
431
432    fn revalidation_match_results(
433        &mut self,
434        stylist: &Stylist,
435        bloom: &StyleBloom<E>,
436        selector_caches: &mut SelectorCaches,
437    ) -> &RevalidationResult {
438        // It's important to set the selector flags. Otherwise, if we succeed in
439        // sharing the style, we may not set the slow selector flags for the
440        // right elements (which may not necessarily be |element|), causing
441        // missed restyles after future DOM mutations.
442        //
443        // Gecko's test_bug534804.html exercises this. A minimal testcase is:
444        // <style> #e:empty + span { ... } </style>
445        // <span id="e">
446        //   <span></span>
447        // </span>
448        // <span></span>
449        //
450        // The style sharing cache will get a hit for the second span. When the
451        // child span is subsequently removed from the DOM, missing selector
452        // flags would cause us to miss the restyle on the second span.
453        self.validation_data.revalidation_match_results(
454            self.element,
455            stylist,
456            bloom,
457            selector_caches,
458            /* bloom_known_valid = */ true,
459            NeedsSelectorFlags::Yes,
460        )
461    }
462
463    fn scope_revalidation_results(
464        &mut self,
465        stylist: &Stylist,
466        selector_caches: &mut SelectorCaches,
467    ) -> ScopeRevalidationResult {
468        stylist.revalidate_scopes(&self.element, selector_caches, NeedsSelectorFlags::Yes)
469    }
470
471    /// Attempts to share a style with another node.
472    pub fn share_style_if_possible(
473        &mut self,
474        context: &mut StyleContext<E>,
475    ) -> Option<ResolvedElementStyles> {
476        let cache = &mut context.thread_local.sharing_cache;
477        let shared_context = &context.shared;
478        let bloom_filter = &context.thread_local.bloom_filter;
479        let selector_caches = &mut context.thread_local.selector_caches;
480
481        debug_assert_eq!(
482            bloom_filter.current_parent(),
483            self.element.traversal_parent()
484        );
485
486        cache.share_style_if_possible(shared_context, bloom_filter, selector_caches, self)
487    }
488
489    /// Gets the validation data used to match against this target, if any.
490    pub fn take_validation_data(&mut self) -> ValidationData {
491        self.validation_data.take()
492    }
493}
494
495struct SharingCacheBase<Candidate> {
496    /// The DOM depth of the candidates in this cache, if any.
497    dom_depth: usize,
498    entries: LRUCache<Candidate, SHARING_CACHE_SIZE>,
499}
500
501impl<Candidate> Default for SharingCacheBase<Candidate> {
502    fn default() -> Self {
503        Self {
504            dom_depth: 0,
505            entries: LRUCache::default(),
506        }
507    }
508}
509
510impl<Candidate> SharingCacheBase<Candidate> {
511    fn clear(&mut self) {
512        self.entries.clear();
513        self.dom_depth = 0
514    }
515
516    fn is_empty(&self) -> bool {
517        self.entries.len() == 0
518    }
519}
520
521impl<E: TElement> SharingCache<E> {
522    fn insert(
523        &mut self,
524        element: E,
525        validation_data_holder: Option<&mut StyleSharingTarget<E>>,
526        considered_nontrivial_scoped_style: bool,
527    ) {
528        let validation_data = match validation_data_holder {
529            Some(v) => v.take_validation_data(),
530            None => ValidationData::default(),
531        };
532        self.entries.insert(StyleSharingCandidate {
533            element,
534            validation_data,
535            considered_nontrivial_scoped_style,
536        });
537    }
538}
539
540/// Style sharing caches are are large allocations, so we store them in thread-local
541/// storage such that they can be reused across style traversals. Ideally, we'd just
542/// stack-allocate these buffers with uninitialized memory, but right now rustc can't
543/// avoid memmoving the entire cache during setup, which gets very expensive. See
544/// issues like [1] and [2].
545///
546/// Given that the cache stores entries of type TElement, we transmute to usize
547/// before storing in TLS. This is safe as long as we make sure to empty the cache
548/// before we let it go.
549///
550/// [1] https://github.com/rust-lang/rust/issues/42763
551/// [2] https://github.com/rust-lang/rust/issues/13707
552type SharingCache<E> = SharingCacheBase<StyleSharingCandidate<E>>;
553type TypelessSharingCache = SharingCacheBase<StyleSharingCandidate<usize>>;
554
555thread_local! {
556    // See the comment on bloom.rs about why do we leak this.
557    static SHARING_CACHE_KEY: &'static AtomicRefCell<[TypelessSharingCache; SHARING_MAX_LEVELS]> =
558        Box::leak(Default::default());
559}
560
561/// A set of LRU caches of the last few nodes seen, one per DOM depth, so that we can try to
562/// aggressively try to share their styles.
563///
564/// We key the candidates by DOM depth, because sharing requires an identical inheritance parent
565/// (see `test_candidate`), which in practice means the candidates worth testing are the ones at the
566/// target's own depth.
567///
568/// Note that these caches only live for the duration of one traversal so storing nodes here
569/// temporarily is safe.
570pub struct StyleSharingCache<E: TElement> {
571    /// The per-depth LRU caches, with the type cast away to allow persisting the allocation across
572    /// traversals.
573    cache_typeless: AtomicRefMut<'static, [TypelessSharingCache; SHARING_MAX_LEVELS]>,
574    /// Bind this structure to the lifetime of E, since that's what we effectively store.
575    marker: PhantomData<SendElement<E>>,
576}
577
578impl<E: TElement> Drop for StyleSharingCache<E> {
579    fn drop(&mut self) {
580        self.clear();
581    }
582}
583
584impl<E: TElement> Default for StyleSharingCache<E> {
585    fn default() -> Self {
586        Self::new()
587    }
588}
589
590impl<E: TElement> StyleSharingCache<E> {
591    fn cache_mut_at(&mut self, index: usize) -> &mut SharingCache<E> {
592        let base: &mut TypelessSharingCache = &mut self.cache_typeless[index % SHARING_MAX_LEVELS];
593        unsafe { mem::transmute(base) }
594    }
595
596    /// Create a new style sharing candidate cache.
597    ///
598    /// Forced out of line to limit stack frame sizes after extra inlining from
599    /// https://github.com/rust-lang/rust/pull/43931
600    ///
601    /// See https://github.com/servo/servo/pull/18420#issuecomment-328769322
602    #[inline(never)]
603    pub fn new() -> Self {
604        assert_eq!(
605            mem::size_of::<SharingCache<E>>(),
606            mem::size_of::<TypelessSharingCache>()
607        );
608        assert_eq!(
609            mem::align_of::<SharingCache<E>>(),
610            mem::align_of::<TypelessSharingCache>()
611        );
612        let cache = SHARING_CACHE_KEY.with(|c| c.borrow_mut());
613        debug_assert!(cache.iter().all(|c| c.is_empty()));
614        StyleSharingCache {
615            cache_typeless: cache,
616            marker: PhantomData,
617        }
618    }
619
620    /// Tries to insert an element in the style sharing cache.
621    ///
622    /// Fails if we know it should never be in the cache.
623    ///
624    /// NB: We pass a source for the validation data, rather than the data itself,
625    /// to avoid memmoving at each function call. See rust issue #42763.
626    pub fn insert_if_possible(
627        &mut self,
628        element: &E,
629        style: &PrimaryStyle,
630        validation_data_holder: Option<&mut StyleSharingTarget<E>>,
631        dom_depth: usize,
632        shared_context: &SharedStyleContext,
633    ) {
634        let parent = match element.traversal_parent() {
635            Some(element) => element,
636            None => {
637                debug!("Failing to insert to the cache: no parent element");
638                return;
639            },
640        };
641
642        if !element.matches_user_and_content_rules() {
643            debug!("Failing to insert into the cache: no tree rules:");
644            return;
645        }
646
647        if element.has_unique_presentational_hints() {
648            debug!("Failing to insert into the cache: unique presentational hints");
649            return;
650        }
651
652        // If the element has running animations, we can't share style.
653        //
654        // This is distinct from the specifies_{animations,transitions} check below,
655        // because:
656        //   * Animations can be triggered directly via the Web Animations API.
657        //   * Our computed style can still be affected by animations after we no
658        //     longer match any animation rules, since removing animations involves
659        //     a sequential task and an additional traversal.
660        if element.has_animations(shared_context) {
661            debug!("Failing to insert to the cache: running animations");
662            return;
663        }
664
665        if element.smil_override().is_some() {
666            debug!("Failing to insert to the cache: SMIL");
667            return;
668        }
669
670        debug!(
671            "Inserting into cache: {:?} with parent {:?}",
672            element, parent
673        );
674        debug_assert_eq!(element.as_node().depth(), dom_depth);
675
676        let cache = self.cache_mut_at(dom_depth);
677        if cache.dom_depth != dom_depth {
678            debug!(
679                "Clearing cache because depth changed from {:?} to {:?}, element: {:?}",
680                cache.dom_depth, dom_depth, element
681            );
682            cache.clear();
683            cache.dom_depth = dom_depth;
684        }
685        cache.insert(
686            *element,
687            validation_data_holder,
688            style
689                .style()
690                .flags
691                .intersects(ComputedValueFlags::CONSIDERED_NONTRIVIAL_SCOPED_STYLE),
692        );
693    }
694
695    /// Clear the style sharing candidate cache (all depths).
696    pub fn clear(&mut self) {
697        for c in &mut *self.cache_typeless {
698            c.clear();
699        }
700    }
701
702    /// Attempts to share a style with another node.
703    fn share_style_if_possible(
704        &mut self,
705        shared_context: &SharedStyleContext,
706        bloom_filter: &StyleBloom<E>,
707        selector_caches: &mut SelectorCaches,
708        target: &mut StyleSharingTarget<E>,
709    ) -> Option<ResolvedElementStyles> {
710        if shared_context.options.disable_style_sharing_cache {
711            debug!(
712                "{:?} Cannot share style: style sharing cache disabled",
713                target.element
714            );
715            return None;
716        }
717
718        if target.inheritance_parent().is_none() {
719            debug!(
720                "{:?} Cannot share style: element has no parent",
721                target.element
722            );
723            return None;
724        }
725
726        if !target.matches_user_and_content_rules() {
727            debug!("{:?} Cannot share style: content rules", target.element);
728            return None;
729        }
730
731        if target.element.has_unique_presentational_hints() {
732            debug!(
733                "{:?} Cannot share style: unique presentational hints",
734                target.element
735            );
736            return None;
737        }
738
739        let dom_depth = bloom_filter.matching_depth();
740        debug_assert_eq!(target.element.as_node().depth(), dom_depth);
741        let cache = self.cache_mut_at(dom_depth);
742        if cache.dom_depth != dom_depth {
743            debug!(
744                "{:?} Cannot share style: cache holds depth {:?}, not {:?}",
745                target.element, cache.dom_depth, dom_depth
746            );
747            return None;
748        }
749
750        cache.entries.lookup(|candidate| {
751            Self::test_candidate(
752                target,
753                candidate,
754                shared_context,
755                bloom_filter,
756                selector_caches,
757                shared_context,
758            )
759        })
760    }
761
762    fn test_candidate(
763        target: &mut StyleSharingTarget<E>,
764        candidate: &mut StyleSharingCandidate<E>,
765        shared: &SharedStyleContext,
766        bloom: &StyleBloom<E>,
767        selector_caches: &mut SelectorCaches,
768        shared_context: &SharedStyleContext,
769    ) -> Option<ResolvedElementStyles> {
770        debug_assert!(target.matches_user_and_content_rules());
771        debug_assert!(candidate.element.matches_user_and_content_rules());
772
773        // Check that we have the same parent, or at least that the parents
774        // share styles and permit sharing across their children. The latter
775        // check allows us to share style between cousins if the parents
776        // shared style.
777        if !checks::parents_allow_sharing(target, candidate) {
778            trace!("Miss: Parent");
779            return None;
780        }
781
782        if target.local_name() != candidate.element.local_name() {
783            trace!("Miss: Local Name");
784            return None;
785        }
786
787        if target.namespace() != candidate.element.namespace() {
788            trace!("Miss: Namespace");
789            return None;
790        }
791
792        // We do not ignore visited state here, because Gecko needs to store
793        // extra bits on visited styles, so these contexts cannot be shared.
794        if target.element.state() != candidate.state() {
795            trace!("Miss: User and Author State");
796            return None;
797        }
798
799        if target.is_link() != candidate.element.is_link() {
800            trace!("Miss: Link");
801            return None;
802        }
803
804        // If two elements belong to different shadow trees, different rules may apply to them, from
805        // the respective trees, so check their cascade data pointers.
806        if !checks::shadow_root_style_data_equals(
807            target.element.containing_shadow(),
808            candidate.element.containing_shadow(),
809        ) {
810            trace!("Miss: Different containing shadow root style data");
811            return None;
812        }
813
814        // Shadow hosts can share style when they have matching CascadeData pointers, which ensures
815        // they match the same :host rules.
816        if !checks::shadow_root_style_data_equals(
817            target.element.shadow_root(),
818            candidate.element.shadow_root(),
819        ) {
820            trace!("Miss: Different shadow root style data");
821            return None;
822        }
823
824        // If the elements are not assigned to the same slot they could match
825        // different ::slotted() rules in the slot scope.
826        //
827        // If two elements are assigned to different slots, even within the same
828        // shadow root, they could match different rules, due to the slot being
829        // assigned to yet another slot in another shadow root.
830        if target.element.assigned_slot() != candidate.element.assigned_slot() {
831            // TODO(emilio): We could have a look at whether the shadow roots
832            // actually have slotted rules and such.
833            trace!("Miss: Different assigned slots");
834            return None;
835        }
836
837        if target.implemented_pseudo_element() != candidate.implemented_pseudo_element() {
838            trace!("Miss: Element backed pseudo-element");
839            return None;
840        }
841
842        if target.element.has_animations(shared_context)
843            || candidate.element.has_animations(shared_context)
844        {
845            trace!("Miss: Has Animations");
846            return None;
847        }
848
849        if target.element.smil_override().is_some() {
850            trace!("Miss: SMIL");
851            return None;
852        }
853
854        // It's possible that there are no styles for either id.
855        if checks::may_match_different_id_rules(shared, target.element, candidate.element) {
856            trace!("Miss: ID Attr");
857            return None;
858        }
859
860        if !checks::have_same_style_attribute(target, candidate, shared_context) {
861            trace!("Miss: Style Attr");
862            return None;
863        }
864
865        if !checks::have_same_class(target, candidate) {
866            trace!("Miss: Class");
867            return None;
868        }
869
870        if !checks::have_same_presentational_hints(target, candidate) {
871            trace!("Miss: Pres Hints");
872            return None;
873        }
874
875        if !checks::have_same_parts(target, candidate) {
876            trace!("Miss: Shadow parts");
877            return None;
878        }
879
880        if !checks::have_same_referenced_attrs(target, candidate) {
881            trace!("Miss: Attr references");
882            return None;
883        }
884
885        if !checks::have_shareable_element_dependent_functions(target, candidate) {
886            trace!("Miss: Element-dependent functions");
887            return None;
888        }
889
890        if !checks::revalidate(target, candidate, shared, bloom, selector_caches) {
891            trace!("Miss: Revalidation");
892            return None;
893        }
894
895        // While the scoped style rules may be different (e.g. `@scope { .foo + .foo { /* .. */} }`),
896        // we rely on revalidation to handle that.
897        if candidate.considered_nontrivial_scoped_style
898            && !checks::revalidate_scope(target, candidate, shared, selector_caches)
899        {
900            trace!("Miss: Active Scopes");
901            return None;
902        }
903
904        debug!(
905            "Sharing allowed between {:?} and {:?}",
906            target.element, candidate.element
907        );
908        Some(candidate.element.borrow_data().unwrap().share_styles())
909    }
910
911    /// Attempts to find an element in the cache with the given primary rule
912    /// node and parent.
913    ///
914    /// FIXME(emilio): re-measure this optimization, and remove if it's not very
915    /// useful... It's probably not worth the complexity / obscure bugs.
916    pub fn lookup_by_rules(
917        &mut self,
918        shared_context: &SharedStyleContext,
919        inherited: &ComputedValues,
920        inputs: &CascadeInputs,
921        target: E,
922        dom_depth: usize,
923    ) -> Option<PrimaryStyle> {
924        debug_assert_eq!(target.as_node().depth(), dom_depth);
925        if shared_context.options.disable_style_sharing_cache {
926            return None;
927        }
928
929        let cache = self.cache_mut_at(dom_depth);
930        if cache.dom_depth != dom_depth {
931            return None;
932        }
933
934        cache.entries.lookup(|candidate| {
935            debug_assert_ne!(candidate.element, target);
936            if !candidate.parent_style_identity().eq(inherited) {
937                return None;
938            }
939            let data = candidate.element.borrow_data().unwrap();
940            let style = data.styles.primary();
941            if style.rules.as_ref() != Some(inputs.rules.as_ref().unwrap()) {
942                return None;
943            }
944            if style.visited_rules() != inputs.visited_rules.as_ref() {
945                return None;
946            }
947            let sharing_target = StyleSharingTarget::new(target);
948            if !checks::have_same_referenced_attrs(&sharing_target, candidate) {
949                return None;
950            }
951            if !checks::have_shareable_element_dependent_functions(&sharing_target, candidate) {
952                return None;
953            }
954            // NOTE(emilio): We only need to check name / namespace because we
955            // do name-dependent style adjustments, like the display: contents
956            // to display: none adjustment.
957            if target.namespace() != candidate.element.namespace()
958                || target.local_name() != candidate.element.local_name()
959            {
960                return None;
961            }
962            // When using container units, inherited style + rules matched aren't enough to
963            // determine whether the style is the same. We could actually do a full container
964            // lookup but for now we just check that our actual traversal parent matches.
965            if data
966                .styles
967                .primary()
968                .flags
969                .intersects(ComputedValueFlags::USES_CONTAINER_UNITS)
970                && candidate.element.traversal_parent() != target.traversal_parent()
971            {
972                return None;
973            }
974            // Rule nodes and styles are computed independent of the element's actual visitedness,
975            // but at the end of the cascade (in `adjust_for_visited`) we do store the
976            // RELEVANT_LINK_VISITED flag, so we can't share by rule node between visited and
977            // unvisited styles. We don't check for visitedness and just refuse to share for links
978            // entirely, so that visitedness doesn't affect timing.
979            if target.is_link() || candidate.element.is_link() {
980                return None;
981            }
982
983            let target_depends_on_style_queries = inputs
984                .flags
985                .contains(ComputedValueFlags::DEPENDS_ON_CONTAINER_STYLE_QUERY);
986            let candidate_depends_on_style_queries = style
987                .flags
988                .contains(ComputedValueFlags::DEPENDS_ON_CONTAINER_STYLE_QUERY);
989
990            if target_depends_on_style_queries != candidate_depends_on_style_queries {
991                // If we're considering sharing across two elements, target
992                // depends on style queries and candidate doesn't, right
993                // now we can share it, but by cloning the candidate style
994                // if we adjust the flags.
995                // If we're considering sharing across two elements, target
996                // does not depend on style queries and candidate does, we
997                // can share them with the same flags, but that would
998                // overinvalidate if we already know we don't need to keep
999                // `DEPENDS_ON_CONTAINER_STYLE_QUERY`.
1000                let mut new_flags = inputs.flags | style.flags;
1001                new_flags.set(
1002                    ComputedValueFlags::DEPENDS_ON_CONTAINER_STYLE_QUERY,
1003                    target_depends_on_style_queries,
1004                );
1005
1006                return Some(PrimaryStyle {
1007                    style: data.clone_style_with_flags(new_flags),
1008                    reused_via_rule_node: true,
1009                });
1010            }
1011
1012            Some(data.share_primary_style())
1013        })
1014    }
1015}