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/. */
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.
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
16 //! The complicated part is determining that styles match. This is subject to
17 //! the following constraints:
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.
27 //! These constraints are satisfied in the following ways:
29 //! * We check that the parents of the target and the candidate have the same
30 //! computed style. This addresses constraint 1.
32 //! * We check that the target and candidate have the same inline style and
33 //! presentation hint declarations. This addresses constraint 3.
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
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
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.
67 use crate::applicable_declarations::ApplicableDeclarationBlock;
68 use crate::bloom::StyleBloom;
69 use crate::computed_value_flags::ComputedValueFlags;
70 use crate::context::{SharedStyleContext, StyleContext};
71 use crate::dom::{SendElement, TElement};
72 use crate::properties::ComputedValues;
73 use crate::rule_tree::StrongRuleNode;
74 use crate::selector_map::RelevantAttributes;
75 use crate::style_resolver::{PrimaryStyle, ResolvedElementStyles};
76 use crate::stylist::Stylist;
77 use crate::values::AtomIdent;
78 use atomic_refcell::{AtomicRefCell, AtomicRefMut};
79 use owning_ref::OwningHandle;
80 use selectors::matching::{NeedsSelectorFlags, SelectorCaches, VisitedHandlingMode};
82 use smallbitvec::SmallBitVec;
83 use smallvec::SmallVec;
84 use std::marker::PhantomData;
85 use std::mem::{self, ManuallyDrop};
87 use std::ptr::NonNull;
92 /// The amount of nodes that the style sharing candidate cache should hold at
95 /// The cache size was chosen by measuring style sharing and resulting
96 /// performance on a few pages; sizes up to about 32 were giving good sharing
97 /// improvements (e.g. 3x fewer styles having to be resolved than at size 8) and
98 /// slight performance improvements. Sizes larger than 32 haven't really been
100 pub const SHARING_CACHE_SIZE: usize = 32;
102 /// Opaque pointer type to compare ComputedValues identities.
103 #[derive(Clone, Debug, Eq, PartialEq)]
104 pub struct OpaqueComputedValues(NonNull<()>);
106 unsafe impl Send for OpaqueComputedValues {}
107 unsafe impl Sync for OpaqueComputedValues {}
109 impl OpaqueComputedValues {
110 fn from(cv: &ComputedValues) -> Self {
112 unsafe { NonNull::new_unchecked(cv as *const ComputedValues as *const () as *mut ()) };
113 OpaqueComputedValues(p)
116 fn eq(&self, cv: &ComputedValues) -> bool {
117 Self::from(cv) == *self
121 /// The results from the revalidation step.
123 /// Rather than either:
125 /// * Plainly rejecting sharing for elements with different attributes (which would be unfortunate
126 /// because a lot of elements have different attributes yet those attributes are not
129 /// * Having to give up on per-attribute bucketing, which would be unfortunate because it
130 /// increases the cost of revalidation for pages with lots of global attribute selectors (see
133 /// * We also store the style-relevant attributes for these elements, in order to guarantee that
134 /// we end up looking at the same selectors.
136 #[derive(Debug, Default)]
137 pub struct RevalidationResult {
138 /// A bit for each selector matched. This is sound because we guarantee we look up into the
139 /// same buckets via the pre-revalidation checks and relevant_attributes.
140 pub selectors_matched: SmallBitVec,
141 /// The set of attributes of this element that were relevant for its style.
142 pub relevant_attributes: RelevantAttributes,
145 impl PartialEq for RevalidationResult {
146 fn eq(&self, other: &Self) -> bool {
147 if self.relevant_attributes != other.relevant_attributes {
151 // This assert "ensures", to some extent, that the two candidates have matched the
152 // same rulehash buckets, and as such, that the bits we're comparing represent the
153 // same set of selectors.
154 debug_assert_eq!(self.selectors_matched.len(), other.selectors_matched.len());
155 self.selectors_matched == other.selectors_matched
159 /// Some data we want to avoid recomputing all the time while trying to share
161 #[derive(Debug, Default)]
162 pub struct ValidationData {
163 /// The class list of this element.
165 /// TODO(emilio): Maybe check whether rules for these classes apply to the
167 class_list: Option<SmallVec<[AtomIdent; 5]>>,
169 /// The part list of this element.
171 /// TODO(emilio): Maybe check whether rules with these part names apply to
173 part_list: Option<SmallVec<[AtomIdent; 5]>>,
175 /// The list of presentational attributes of the element.
176 pres_hints: Option<SmallVec<[ApplicableDeclarationBlock; 5]>>,
178 /// The pointer identity of the parent ComputedValues.
179 parent_style_identity: Option<OpaqueComputedValues>,
181 /// The cached result of matching this entry against the revalidation
183 revalidation_match_results: Option<RevalidationResult>,
186 impl ValidationData {
187 /// Move the cached data to a new instance, and return it.
188 pub fn take(&mut self) -> Self {
189 mem::replace(self, Self::default())
192 /// Get or compute the list of presentational attributes associated with
194 pub fn pres_hints<E>(&mut self, element: E) -> &[ApplicableDeclarationBlock]
198 self.pres_hints.get_or_insert_with(|| {
199 let mut pres_hints = SmallVec::new();
200 element.synthesize_presentational_hints_for_legacy_attributes(
201 VisitedHandlingMode::AllLinksUnvisited,
208 /// Get or compute the part-list associated with this element.
209 pub fn part_list<E>(&mut self, element: E) -> &[AtomIdent]
213 if !element.has_part_attr() {
216 self.part_list.get_or_insert_with(|| {
217 let mut list = SmallVec::<[_; 5]>::new();
218 element.each_part(|p| list.push(p.clone()));
219 // See below for the reasoning.
221 list.sort_unstable_by_key(|a| a.get_hash());
227 /// Get or compute the class-list associated with this element.
228 pub fn class_list<E>(&mut self, element: E) -> &[AtomIdent]
232 self.class_list.get_or_insert_with(|| {
233 let mut list = SmallVec::<[_; 5]>::new();
234 element.each_class(|c| list.push(c.clone()));
235 // Assuming there are a reasonable number of classes (we use the
236 // inline capacity as "reasonable number"), sort them to so that
237 // we don't mistakenly reject sharing candidates when one element
238 // has "foo bar" and the other has "bar foo".
240 list.sort_unstable_by_key(|a| a.get_hash());
246 /// Get or compute the parent style identity.
247 pub fn parent_style_identity<E>(&mut self, el: E) -> OpaqueComputedValues
251 self.parent_style_identity
252 .get_or_insert_with(|| {
253 let parent = el.inheritance_parent().unwrap();
255 OpaqueComputedValues::from(parent.borrow_data().unwrap().styles.primary());
261 /// Computes the revalidation results if needed, and returns it.
262 /// Inline so we know at compile time what bloom_known_valid is.
264 fn revalidation_match_results<E>(
268 bloom: &StyleBloom<E>,
269 selector_caches: &mut SelectorCaches,
270 bloom_known_valid: bool,
271 needs_selector_flags: NeedsSelectorFlags,
272 ) -> &RevalidationResult
276 self.revalidation_match_results.get_or_insert_with(|| {
277 // The bloom filter may already be set up for our element.
278 // If it is, use it. If not, we must be in a candidate
279 // (i.e. something in the cache), and the element is one
280 // of our cousins, not a sibling. In that case, we'll
281 // just do revalidation selector matching without a bloom
282 // filter, to avoid thrashing the filter.
283 let bloom_to_use = if bloom_known_valid {
284 debug_assert_eq!(bloom.current_parent(), element.traversal_parent());
287 if bloom.current_parent() == element.traversal_parent() {
293 stylist.match_revalidation_selectors(
297 needs_selector_flags,
303 /// Information regarding a style sharing candidate, that is, an entry in the
304 /// style sharing cache.
306 /// Note that this information is stored in TLS and cleared after the traversal,
307 /// and once here, the style information of the element is immutable, so it's
310 /// Important: If you change the members/layout here, You need to do the same for
311 /// FakeCandidate below.
313 pub struct StyleSharingCandidate<E: TElement> {
316 validation_data: ValidationData,
319 struct FakeCandidate {
321 _validation_data: ValidationData,
324 impl<E: TElement> Deref for StyleSharingCandidate<E> {
327 fn deref(&self) -> &Self::Target {
332 impl<E: TElement> StyleSharingCandidate<E> {
333 /// Get the classlist of this candidate.
334 fn class_list(&mut self) -> &[AtomIdent] {
335 self.validation_data.class_list(self.element)
338 /// Get the part list of this candidate.
339 fn part_list(&mut self) -> &[AtomIdent] {
340 self.validation_data.part_list(self.element)
343 /// Get the pres hints of this candidate.
344 fn pres_hints(&mut self) -> &[ApplicableDeclarationBlock] {
345 self.validation_data.pres_hints(self.element)
348 /// Get the parent style identity.
349 fn parent_style_identity(&mut self) -> OpaqueComputedValues {
350 self.validation_data.parent_style_identity(self.element)
353 /// Compute the bit vector of revalidation selector match results
354 /// for this candidate.
355 fn revalidation_match_results(
358 bloom: &StyleBloom<E>,
359 selector_caches: &mut SelectorCaches,
360 ) -> &RevalidationResult {
361 self.validation_data.revalidation_match_results(
366 /* bloom_known_valid = */ false,
367 // The candidate must already have the right bits already, if
369 NeedsSelectorFlags::No,
374 impl<E: TElement> PartialEq<StyleSharingCandidate<E>> for StyleSharingCandidate<E> {
375 fn eq(&self, other: &Self) -> bool {
376 self.element == other.element
380 /// An element we want to test against the style sharing cache.
381 pub struct StyleSharingTarget<E: TElement> {
383 validation_data: ValidationData,
386 impl<E: TElement> Deref for StyleSharingTarget<E> {
389 fn deref(&self) -> &Self::Target {
394 impl<E: TElement> StyleSharingTarget<E> {
395 /// Trivially construct a new StyleSharingTarget to test against the cache.
396 pub fn new(element: E) -> Self {
399 validation_data: ValidationData::default(),
403 fn class_list(&mut self) -> &[AtomIdent] {
404 self.validation_data.class_list(self.element)
407 fn part_list(&mut self) -> &[AtomIdent] {
408 self.validation_data.part_list(self.element)
411 /// Get the pres hints of this candidate.
412 fn pres_hints(&mut self) -> &[ApplicableDeclarationBlock] {
413 self.validation_data.pres_hints(self.element)
416 /// Get the parent style identity.
417 fn parent_style_identity(&mut self) -> OpaqueComputedValues {
418 self.validation_data.parent_style_identity(self.element)
421 fn revalidation_match_results(
424 bloom: &StyleBloom<E>,
425 selector_caches: &mut SelectorCaches,
426 ) -> &RevalidationResult {
427 // It's important to set the selector flags. Otherwise, if we succeed in
428 // sharing the style, we may not set the slow selector flags for the
429 // right elements (which may not necessarily be |element|), causing
430 // missed restyles after future DOM mutations.
432 // Gecko's test_bug534804.html exercises this. A minimal testcase is:
433 // <style> #e:empty + span { ... } </style>
439 // The style sharing cache will get a hit for the second span. When the
440 // child span is subsequently removed from the DOM, missing selector
441 // flags would cause us to miss the restyle on the second span.
442 self.validation_data.revalidation_match_results(
447 /* bloom_known_valid = */ true,
448 NeedsSelectorFlags::Yes,
452 /// Attempts to share a style with another node.
453 pub fn share_style_if_possible(
455 context: &mut StyleContext<E>,
456 ) -> Option<ResolvedElementStyles> {
457 let cache = &mut context.thread_local.sharing_cache;
458 let shared_context = &context.shared;
459 let bloom_filter = &context.thread_local.bloom_filter;
460 let selector_caches = &mut context.thread_local.selector_caches;
462 if cache.dom_depth != bloom_filter.matching_depth() {
464 "Can't share style, because DOM depth changed from {:?} to {:?}, element: {:?}",
466 bloom_filter.matching_depth(),
472 bloom_filter.current_parent(),
473 self.element.traversal_parent()
476 cache.share_style_if_possible(shared_context, bloom_filter, selector_caches, self)
479 /// Gets the validation data used to match against this target, if any.
480 pub fn take_validation_data(&mut self) -> ValidationData {
481 self.validation_data.take()
485 struct SharingCacheBase<Candidate> {
486 entries: LRUCache<Candidate, SHARING_CACHE_SIZE>,
489 impl<Candidate> Default for SharingCacheBase<Candidate> {
490 fn default() -> Self {
492 entries: LRUCache::default(),
497 impl<Candidate> SharingCacheBase<Candidate> {
498 fn clear(&mut self) {
499 self.entries.clear();
502 fn is_empty(&self) -> bool {
503 self.entries.len() == 0
507 impl<E: TElement> SharingCache<E> {
511 validation_data_holder: Option<&mut StyleSharingTarget<E>>,
513 let validation_data = match validation_data_holder {
514 Some(v) => v.take_validation_data(),
515 None => ValidationData::default(),
517 self.entries.insert(StyleSharingCandidate {
524 /// Style sharing caches are are large allocations, so we store them in thread-local
525 /// storage such that they can be reused across style traversals. Ideally, we'd just
526 /// stack-allocate these buffers with uninitialized memory, but right now rustc can't
527 /// avoid memmoving the entire cache during setup, which gets very expensive. See
528 /// issues like [1] and [2].
530 /// Given that the cache stores entries of type TElement, we transmute to usize
531 /// before storing in TLS. This is safe as long as we make sure to empty the cache
532 /// before we let it go.
534 /// [1] https://github.com/rust-lang/rust/issues/42763
535 /// [2] https://github.com/rust-lang/rust/issues/13707
536 type SharingCache<E> = SharingCacheBase<StyleSharingCandidate<E>>;
537 type TypelessSharingCache = SharingCacheBase<FakeCandidate>;
538 type StoredSharingCache = Arc<AtomicRefCell<TypelessSharingCache>>;
541 // See the comment on bloom.rs about why do we leak this.
542 static SHARING_CACHE_KEY: ManuallyDrop<StoredSharingCache> =
543 ManuallyDrop::new(Arc::new_leaked(Default::default()));
546 /// An LRU cache of the last few nodes seen, so that we can aggressively try to
547 /// reuse their styles.
549 /// Note that this cache is flushed every time we steal work from the queue, so
550 /// storing nodes here temporarily is safe.
551 pub struct StyleSharingCache<E: TElement> {
552 /// The LRU cache, with the type cast away to allow persisting the allocation.
553 cache_typeless: OwningHandle<StoredSharingCache, AtomicRefMut<'static, TypelessSharingCache>>,
554 /// Bind this structure to the lifetime of E, since that's what we effectively store.
555 marker: PhantomData<SendElement<E>>,
556 /// The DOM depth we're currently at. This is used as an optimization to
557 /// clear the cache when we change depths, since we know at that point
558 /// nothing in the cache will match.
562 impl<E: TElement> Drop for StyleSharingCache<E> {
568 impl<E: TElement> StyleSharingCache<E> {
570 fn cache(&self) -> &SharingCache<E> {
571 let base: &TypelessSharingCache = &*self.cache_typeless;
572 unsafe { mem::transmute(base) }
575 fn cache_mut(&mut self) -> &mut SharingCache<E> {
576 let base: &mut TypelessSharingCache = &mut *self.cache_typeless;
577 unsafe { mem::transmute(base) }
580 /// Create a new style sharing candidate cache.
582 // Forced out of line to limit stack frame sizes after extra inlining from
583 // https://github.com/rust-lang/rust/pull/43931
585 // See https://github.com/servo/servo/pull/18420#issuecomment-328769322
587 pub fn new() -> Self {
589 mem::size_of::<SharingCache<E>>(),
590 mem::size_of::<TypelessSharingCache>()
593 mem::align_of::<SharingCache<E>>(),
594 mem::align_of::<TypelessSharingCache>()
596 let cache_arc = SHARING_CACHE_KEY.with(|c| Arc::clone(&*c));
598 OwningHandle::new_with_fn(cache_arc, |x| unsafe { x.as_ref() }.unwrap().borrow_mut());
599 debug_assert!(cache.is_empty());
602 cache_typeless: cache,
608 /// Tries to insert an element in the style sharing cache.
610 /// Fails if we know it should never be in the cache.
612 /// NB: We pass a source for the validation data, rather than the data itself,
613 /// to avoid memmoving at each function call. See rust issue #42763.
614 pub fn insert_if_possible(
617 style: &PrimaryStyle,
618 validation_data_holder: Option<&mut StyleSharingTarget<E>>,
620 shared_context: &SharedStyleContext,
622 let parent = match element.traversal_parent() {
623 Some(element) => element,
625 debug!("Failing to insert to the cache: no parent element");
630 if !element.matches_user_and_content_rules() {
631 debug!("Failing to insert into the cache: no tree rules:");
635 // We can't share style across shadow hosts right now, because they may
636 // match different :host rules.
638 // TODO(emilio): We could share across the ones that don't have :host
639 // rules or have the same.
640 if element.shadow_root().is_some() {
641 debug!("Failing to insert into the cache: Shadow Host");
645 // If the element has running animations, we can't share style.
647 // This is distinct from the specifies_{animations,transitions} check below,
649 // * Animations can be triggered directly via the Web Animations API.
650 // * Our computed style can still be affected by animations after we no
651 // longer match any animation rules, since removing animations involves
652 // a sequential task and an additional traversal.
653 if element.has_animations(shared_context) {
654 debug!("Failing to insert to the cache: running animations");
658 // In addition to the above running animations check, we also need to
659 // check CSS animation and transition styles since it's possible that
660 // we are about to create CSS animations/transitions.
662 // These are things we don't check in the candidate match because they
663 // are either uncommon or expensive.
664 let ui_style = style.style().get_ui();
665 if ui_style.specifies_transitions() {
666 debug!("Failing to insert to the cache: transitions");
670 if ui_style.specifies_animations() {
671 debug!("Failing to insert to the cache: animations");
676 "Inserting into cache: {:?} with parent {:?}",
680 if self.dom_depth != dom_depth {
682 "Clearing cache because depth changed from {:?} to {:?}, element: {:?}",
683 self.dom_depth, dom_depth, element
686 self.dom_depth = dom_depth;
688 self.cache_mut().insert(
690 validation_data_holder,
694 /// Clear the style sharing candidate cache.
695 pub fn clear(&mut self) {
696 self.cache_mut().clear();
699 /// Attempts to share a style with another node.
700 fn share_style_if_possible(
702 shared_context: &SharedStyleContext,
703 bloom_filter: &StyleBloom<E>,
704 selector_caches: &mut SelectorCaches,
705 target: &mut StyleSharingTarget<E>,
706 ) -> Option<ResolvedElementStyles> {
707 if shared_context.options.disable_style_sharing_cache {
709 "{:?} Cannot share style: style sharing cache disabled",
715 if target.inheritance_parent().is_none() {
717 "{:?} Cannot share style: element has no parent",
723 if !target.matches_user_and_content_rules() {
724 debug!("{:?} Cannot share style: content rules", target.element);
728 self.cache_mut().entries.lookup(|candidate| {
729 Self::test_candidate(
741 target: &mut StyleSharingTarget<E>,
742 candidate: &mut StyleSharingCandidate<E>,
743 shared: &SharedStyleContext,
744 bloom: &StyleBloom<E>,
745 selector_caches: &mut SelectorCaches,
746 shared_context: &SharedStyleContext,
747 ) -> Option<ResolvedElementStyles> {
748 debug_assert!(target.matches_user_and_content_rules());
750 // Check that we have the same parent, or at least that the parents
751 // share styles and permit sharing across their children. The latter
752 // check allows us to share style between cousins if the parents
754 if !checks::parents_allow_sharing(target, candidate) {
755 trace!("Miss: Parent");
759 if target.local_name() != candidate.element.local_name() {
760 trace!("Miss: Local Name");
764 if target.namespace() != candidate.element.namespace() {
765 trace!("Miss: Namespace");
769 // We do not ignore visited state here, because Gecko needs to store
770 // extra bits on visited styles, so these contexts cannot be shared.
771 if target.element.state() != candidate.state() {
772 trace!("Miss: User and Author State");
776 if target.is_link() != candidate.element.is_link() {
777 trace!("Miss: Link");
781 // If two elements belong to different shadow trees, different rules may
782 // apply to them, from the respective trees.
783 if target.element.containing_shadow() != candidate.element.containing_shadow() {
784 trace!("Miss: Different containing shadow roots");
788 // If the elements are not assigned to the same slot they could match
789 // different ::slotted() rules in the slot scope.
791 // If two elements are assigned to different slots, even within the same
792 // shadow root, they could match different rules, due to the slot being
793 // assigned to yet another slot in another shadow root.
794 if target.element.assigned_slot() != candidate.element.assigned_slot() {
795 // TODO(emilio): We could have a look at whether the shadow roots
796 // actually have slotted rules and such.
797 trace!("Miss: Different assigned slots");
801 if target.element.shadow_root().is_some() {
802 trace!("Miss: Shadow host");
806 if target.element.has_animations(shared_context) {
807 trace!("Miss: Has Animations");
811 if target.matches_user_and_content_rules() !=
812 candidate.element.matches_user_and_content_rules()
814 trace!("Miss: User and Author Rules");
818 // It's possible that there are no styles for either id.
819 if checks::may_match_different_id_rules(shared, target.element, candidate.element) {
820 trace!("Miss: ID Attr");
824 if !checks::have_same_style_attribute(target, candidate) {
825 trace!("Miss: Style Attr");
829 if !checks::have_same_class(target, candidate) {
830 trace!("Miss: Class");
834 if !checks::have_same_presentational_hints(target, candidate) {
835 trace!("Miss: Pres Hints");
839 if !checks::have_same_parts(target, candidate) {
840 trace!("Miss: Shadow parts");
844 if !checks::revalidate(target, candidate, shared, bloom, selector_caches) {
845 trace!("Miss: Revalidation");
850 "Sharing allowed between {:?} and {:?}",
851 target.element, candidate.element
853 Some(candidate.element.borrow_data().unwrap().share_styles())
856 /// Attempts to find an element in the cache with the given primary rule
859 /// FIXME(emilio): re-measure this optimization, and remove if it's not very
860 /// useful... It's probably not worth the complexity / obscure bugs.
861 pub fn lookup_by_rules(
863 shared_context: &SharedStyleContext,
864 inherited: &ComputedValues,
865 rules: &StrongRuleNode,
866 visited_rules: Option<&StrongRuleNode>,
868 ) -> Option<PrimaryStyle> {
869 if shared_context.options.disable_style_sharing_cache {
873 self.cache_mut().entries.lookup(|candidate| {
874 debug_assert_ne!(candidate.element, target);
875 if !candidate.parent_style_identity().eq(inherited) {
878 let data = candidate.element.borrow_data().unwrap();
879 let style = data.styles.primary();
880 if style.rules.as_ref() != Some(&rules) {
883 if style.visited_rules() != visited_rules {
886 // NOTE(emilio): We only need to check name / namespace because we
887 // do name-dependent style adjustments, like the display: contents
888 // to display: none adjustment.
889 if target.namespace() != candidate.element.namespace() ||
890 target.local_name() != candidate.element.local_name()
894 // When using container units, inherited style + rules matched aren't enough to
895 // determine whether the style is the same. We could actually do a full container
896 // lookup but for now we just check that our actual traversal parent matches.
901 .intersects(ComputedValueFlags::USES_CONTAINER_UNITS) &&
902 candidate.element.traversal_parent() != target.traversal_parent()
906 // Rule nodes and styles are computed independent of the element's actual visitedness,
907 // but at the end of the cascade (in `adjust_for_visited`) we do store the
908 // RELEVANT_LINK_VISITED flag, so we can't share by rule node between visited and
909 // unvisited styles. We don't check for visitedness and just refuse to share for links
910 // entirely, so that visitedness doesn't affect timing.
911 if target.is_link() || candidate.element.is_link() {
915 Some(data.share_primary_style())