Skip to main content

style/
stylist.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//! Selector matching.
6
7use crate::AllocErr;
8use crate::ArcSlice;
9use crate::FxHashMap;
10use crate::applicable_declarations::{
11    ApplicableDeclarationBlock, ApplicableDeclarationList, CascadePriority, ScopeProximity,
12};
13use crate::computed_value_flags::ComputedValueFlags;
14use crate::context::{CascadeInputs, QuirksMode, TreeCountingCaches};
15use crate::custom_properties::ComputedCustomProperties;
16use crate::custom_properties::{SpecifiedValue, parse_name};
17use crate::derives::*;
18use crate::device::Device;
19use crate::dom::TElement;
20use crate::dom::TShadowRoot;
21#[cfg(feature = "gecko")]
22use crate::gecko_bindings::structs::{ServoStyleSetSizes, StyleRuleInclusion};
23use crate::invalidation::element::invalidation_map::{
24    AdditionalRelativeSelectorInvalidationMap, Dependency, DependencyInvalidationKind,
25    InvalidationMap, ScopeDependencyInvalidationKind, note_selector_for_invalidation,
26};
27use crate::invalidation::media_queries::{
28    EffectiveMediaQueryResults, MediaListKey, ToMediaListKey,
29};
30use crate::invalidation::stylesheets::{RuleChangeKind, StylesheetInvalidationSet};
31use crate::parser::ParserContext;
32use crate::properties::StyleBuilder;
33use crate::properties::{
34    self, AnimationDeclarations, CascadeMode, ComputedValues, FirstLineReparenting,
35    PropertyDeclarationBlock, PropertyIdRef,
36};
37use crate::properties_and_values::registry::{
38    PropertyRegistration, ScriptRegistry as CustomPropertyScriptRegistry,
39};
40use crate::properties_and_values::rule::{
41    Descriptors as PropertyDescriptors, Inherits, PropertyRegistrationError, PropertyRuleName,
42};
43use crate::properties_and_values::syntax::Descriptor;
44use crate::rule_cache::{RuleCache, RuleCacheConditions};
45use crate::rule_collector::RuleCollector;
46use crate::rule_tree::{
47    CascadeLevel, CascadeOrigin, RuleCascadeFlags, RuleTree, StrongRuleNode, StyleSource,
48    StyleSourceBorrow,
49};
50use crate::selector_map::{
51    BucketMatches, PrecomputedHashMap, PrecomputedHashSet, SelectorMap, SelectorMapEntry,
52};
53use crate::selector_parser::{NonTSPseudoClass, PerPseudoElementMap, PseudoElement, SelectorImpl};
54use crate::shared_lock::{Locked, SharedRwLockReadGuard, StylesheetGuards};
55use crate::sharing::{RevalidationResult, ScopeRevalidationResult};
56use crate::stylesheet_set::{DataValidity, DocumentStylesheetSet, SheetRebuildKind};
57use crate::stylesheet_set::{DocumentStylesheetFlusher, SheetCollectionFlusher};
58use crate::stylesheets::UrlExtraData;
59use crate::stylesheets::container_rule::{ContainerAttributeDependencyKind, ContainerCondition};
60use crate::stylesheets::import_rule::ImportLayer;
61use crate::stylesheets::keyframes_rule::KeyframesAnimation;
62use crate::stylesheets::layer_rule::{LayerName, LayerOrder};
63use crate::stylesheets::scope_rule::{
64    ImplicitScopeRoot, ScopeRootCandidate, ScopeSubjectMap, ScopeTarget, collect_scope_roots,
65    element_is_outside_of_scope, scope_selector_list_is_trivial,
66};
67use crate::stylesheets::{
68    CounterStyleRule, CssRule, CssRuleRef, EffectiveRulesIterator, FontFaceRule,
69    FontFeatureValuesRule, FontPaletteValuesRule, Origin, OriginSet, PagePseudoClassFlags,
70    PageRule, PerOrigin, PerOriginIter, PositionTryRule, StylesheetContents, StylesheetInDocument,
71    ViewTransitionRule,
72};
73use crate::stylesheets::{CustomMediaEvaluator, CustomMediaMap};
74use crate::substitution::AttrTaint;
75use crate::values::specified::position::PositionTryFallbacksItem;
76use crate::values::specified::position::PositionTryFallbacksTryTactic;
77use crate::values::{AtomIdent, Parser, SourceLocation, computed};
78use crate::{Atom, LocalName, Namespace, ShrinkIfNeeded, WeakAtom};
79use dom::{DocumentState, ElementState};
80#[cfg(feature = "gecko")]
81use malloc_size_of::MallocUnconditionalShallowSizeOf;
82use malloc_size_of::{MallocShallowSizeOf, MallocSizeOf, MallocSizeOfOps};
83use selectors::attr::{CaseSensitivity, NamespaceConstraint};
84use selectors::bloom::BloomFilter;
85use selectors::matching::{
86    MatchingContext, MatchingMode, NeedsSelectorFlags, SelectorCaches, SubjectOrPseudoElement,
87    matches_complex_selector, matches_selector, selector_may_match,
88};
89use selectors::matching::{MatchingForInvalidation, VisitedHandlingMode};
90use selectors::parser::{
91    AncestorHashes, Combinator, Component, MatchesFeaturelessHost, Selector, SelectorIter,
92    SelectorList,
93};
94use selectors::visitor::{SelectorListKind, SelectorVisitor};
95use servo_arc::{Arc, ArcBorrow, ThinArc};
96use smallvec::SmallVec;
97use std::cmp::Ordering;
98use std::hash::{Hash, Hasher};
99use std::mem;
100use std::sync::{LazyLock, Mutex};
101use style_traits::ParsingMode;
102
103/// The type of the stylesheets that the stylist contains.
104#[cfg(feature = "servo")]
105pub type StylistSheet = crate::stylesheets::DocumentStyleSheet;
106
107/// The type of the stylesheets that the stylist contains.
108#[cfg(feature = "gecko")]
109pub type StylistSheet = crate::gecko::data::GeckoStyleSheet;
110
111#[derive(Debug, Clone)]
112struct StylesheetContentsPtr(Arc<StylesheetContents>);
113
114impl PartialEq for StylesheetContentsPtr {
115    #[inline]
116    fn eq(&self, other: &Self) -> bool {
117        Arc::ptr_eq(&self.0, &other.0)
118    }
119}
120
121impl Eq for StylesheetContentsPtr {}
122
123impl Hash for StylesheetContentsPtr {
124    fn hash<H: Hasher>(&self, state: &mut H) {
125        let contents: &StylesheetContents = &self.0;
126        (contents as *const StylesheetContents).hash(state)
127    }
128}
129
130type StyleSheetContentList = Vec<StylesheetContentsPtr>;
131
132/// The @position-try rules that have changed.
133#[derive(Default, Debug, MallocSizeOf)]
134pub struct CascadeDataDifference {
135    /// Whether layer order has changed. Note that this only concerns itself with reordering, not
136    /// addition or removal.
137    pub layer_order_changed: bool,
138    /// The set of changed @position-try rule names.
139    pub changed_position_try_names: PrecomputedHashSet<Atom>,
140}
141
142impl CascadeDataDifference {
143    /// Merges another difference into `self`.
144    pub fn merge_with(&mut self, other: Self) {
145        self.layer_order_changed |= other.layer_order_changed;
146        self.changed_position_try_names
147            .extend(other.changed_position_try_names)
148    }
149
150    /// Returns whether we're empty.
151    pub fn is_empty(&self) -> bool {
152        !self.layer_order_changed && self.changed_position_try_names.is_empty()
153    }
154
155    fn update(&mut self, old_data: &CascadeData, new_data: &CascadeData) {
156        self.update_layers(&old_data.layers, &new_data.layers);
157        self.update_position_try(
158            &old_data.extra_data.position_try_rules,
159            &new_data.extra_data.position_try_rules,
160        );
161    }
162
163    fn update_layers(&mut self, old: &CascadeLayers, new: &CascadeLayers) {
164        if self.layer_order_changed {
165            return;
166        }
167        for (name, new_id) in &new.layer_id_by_name {
168            let Some(old_id) = old.layer_id_by_name.get(name) else {
169                // This is a new layer, as long as the old orders match it just means we've been
170                // added to the end, no layer order has actually changed.
171                // Similarly, if there's an old layer that doesn't exist in the new data, it means
172                // it's been removed, which also doesn't change the order of the remaining layers.
173                continue;
174            };
175            let new_order = new.layer_by_id[new_id.0 as usize].order;
176            let old_order = old.layer_by_id[old_id.0 as usize].order;
177            if new_order != old_order {
178                self.layer_order_changed = true;
179                return;
180            }
181        }
182    }
183
184    fn update_position_try(&mut self, old_data: &PositionTryMap, new_data: &PositionTryMap) {
185        let mut any_different_key = false;
186        let different_len = old_data.len() != new_data.len();
187        for (name, rules) in old_data.iter() {
188            let changed = match new_data.get(name) {
189                Some(new_rule) => !Arc::ptr_eq(&rules.last().unwrap().0, new_rule),
190                None => {
191                    any_different_key = true;
192                    true
193                },
194            };
195            if changed {
196                self.changed_position_try_names.insert(name.clone());
197            }
198        }
199
200        if any_different_key || different_len {
201            for name in new_data.keys() {
202                // If the key exists in both, we've already checked it above.
203                if !old_data.contains_key(name) {
204                    self.changed_position_try_names.insert(name.clone());
205                }
206            }
207        }
208    }
209}
210
211/// A key in the cascade data cache.
212#[derive(Debug, Hash, Default, PartialEq, Eq)]
213struct CascadeDataCacheKey {
214    media_query_results: Vec<MediaListKey>,
215    contents: StyleSheetContentList,
216}
217
218unsafe impl Send for CascadeDataCacheKey {}
219unsafe impl Sync for CascadeDataCacheKey {}
220
221trait CascadeDataCacheEntry: Sized {
222    /// Rebuilds the cascade data for the new stylesheet collection. The
223    /// collection is guaranteed to be dirty.
224    fn rebuild<S>(
225        device: &Device,
226        quirks_mode: QuirksMode,
227        collection: SheetCollectionFlusher<S>,
228        guard: &SharedRwLockReadGuard,
229        old_entry: &Self,
230        difference: &mut CascadeDataDifference,
231    ) -> Result<Arc<Self>, AllocErr>
232    where
233        S: StylesheetInDocument + PartialEq + 'static;
234    /// Measures heap memory usage.
235    #[cfg(feature = "gecko")]
236    fn add_size_of(&self, ops: &mut MallocSizeOfOps, sizes: &mut ServoStyleSetSizes);
237}
238
239struct CascadeDataCache<Entry> {
240    entries: FxHashMap<CascadeDataCacheKey, Arc<Entry>>,
241}
242
243impl<Entry> CascadeDataCache<Entry>
244where
245    Entry: CascadeDataCacheEntry,
246{
247    fn new() -> Self {
248        Self {
249            entries: Default::default(),
250        }
251    }
252
253    fn len(&self) -> usize {
254        self.entries.len()
255    }
256
257    // FIXME(emilio): This may need to be keyed on quirks-mode too, though for
258    // UA sheets there aren't class / id selectors on those sheets, usually, so
259    // it's probably ok... For the other cache the quirks mode shouldn't differ
260    // so also should be fine.
261    fn lookup<S>(
262        &mut self,
263        device: &Device,
264        quirks_mode: QuirksMode,
265        collection: SheetCollectionFlusher<S>,
266        guard: &SharedRwLockReadGuard,
267        old_entry: &Entry,
268        difference: &mut CascadeDataDifference,
269    ) -> Result<Option<Arc<Entry>>, AllocErr>
270    where
271        S: StylesheetInDocument + PartialEq + 'static,
272    {
273        use hashbrown::hash_map::Entry as HashMapEntry;
274        debug!("StyleSheetCache::lookup({})", self.len());
275
276        if !collection.dirty() {
277            return Ok(None);
278        }
279
280        let mut key = CascadeDataCacheKey::default();
281        let mut custom_media_map = CustomMediaMap::default();
282        for sheet in collection.sheets() {
283            CascadeData::collect_applicable_media_query_results_into(
284                device,
285                sheet,
286                guard,
287                &mut key.media_query_results,
288                &mut key.contents,
289                &mut custom_media_map,
290            )
291        }
292
293        let new_entry;
294        match self.entries.entry(key) {
295            HashMapEntry::Vacant(e) => {
296                debug!("> Picking the slow path (not in the cache)");
297                new_entry = Entry::rebuild(
298                    device,
299                    quirks_mode,
300                    collection,
301                    guard,
302                    old_entry,
303                    difference,
304                )?;
305                e.insert(new_entry.clone());
306            },
307            HashMapEntry::Occupied(mut e) => {
308                // Avoid reusing our old entry (this can happen if we get
309                // invalidated due to CSSOM mutations and our old stylesheet
310                // contents were already unique, for example).
311                if !std::ptr::eq(&**e.get(), old_entry) {
312                    if log_enabled!(log::Level::Debug) {
313                        debug!("cache hit for:");
314                        for sheet in collection.sheets() {
315                            debug!(" > {:?}", sheet);
316                        }
317                    }
318                    // The line below ensures the "committed" bit is updated
319                    // properly.
320                    collection.each(|_, _, _| true);
321                    return Ok(Some(e.get().clone()));
322                }
323
324                debug!("> Picking the slow path due to same entry as old");
325                new_entry = Entry::rebuild(
326                    device,
327                    quirks_mode,
328                    collection,
329                    guard,
330                    old_entry,
331                    difference,
332                )?;
333                e.insert(new_entry.clone());
334            },
335        }
336
337        Ok(Some(new_entry))
338    }
339
340    /// Returns all the cascade datas that are not being used (that is, that are
341    /// held alive just by this cache).
342    ///
343    /// We return them instead of dropping in place because some of them may
344    /// keep alive some other documents (like the SVG documents kept alive by
345    /// URL references), and thus we don't want to drop them while locking the
346    /// cache to not deadlock.
347    fn take_unused(&mut self) -> SmallVec<[Arc<Entry>; 3]> {
348        let mut unused = SmallVec::new();
349        self.entries.retain(|_key, value| {
350            // is_unique() returns false for static references, but we never
351            // have static references to UserAgentCascadeDatas.  If we did, it
352            // may not make sense to put them in the cache in the first place.
353            if !value.is_unique() {
354                return true;
355            }
356            unused.push(value.clone());
357            false
358        });
359        unused
360    }
361
362    fn take_all(&mut self) -> FxHashMap<CascadeDataCacheKey, Arc<Entry>> {
363        mem::take(&mut self.entries)
364    }
365
366    #[cfg(feature = "gecko")]
367    fn add_size_of(&self, ops: &mut MallocSizeOfOps, sizes: &mut ServoStyleSetSizes) {
368        sizes.mOther += self.entries.shallow_size_of(ops);
369        for (_key, arc) in self.entries.iter() {
370            // These are primary Arc references that can be measured
371            // unconditionally.
372            sizes.mOther += arc.unconditional_shallow_size_of(ops);
373            arc.add_size_of(ops, sizes);
374        }
375    }
376}
377
378/// Measure heap usage of UA_CASCADE_DATA_CACHE.
379#[cfg(feature = "gecko")]
380pub fn add_size_of_ua_cache(ops: &mut MallocSizeOfOps, sizes: &mut ServoStyleSetSizes) {
381    UA_CASCADE_DATA_CACHE
382        .lock()
383        .unwrap()
384        .add_size_of(ops, sizes);
385}
386
387/// A cache of computed user-agent data, to be shared across documents.
388static UA_CASCADE_DATA_CACHE: LazyLock<Mutex<UserAgentCascadeDataCache>> =
389    LazyLock::new(|| Mutex::new(UserAgentCascadeDataCache::new()));
390
391impl CascadeDataCacheEntry for UserAgentCascadeData {
392    fn rebuild<S>(
393        device: &Device,
394        quirks_mode: QuirksMode,
395        collection: SheetCollectionFlusher<S>,
396        guard: &SharedRwLockReadGuard,
397        old: &Self,
398        difference: &mut CascadeDataDifference,
399    ) -> Result<Arc<Self>, AllocErr>
400    where
401        S: StylesheetInDocument + PartialEq + 'static,
402    {
403        // TODO: Maybe we should support incremental rebuilds, though they seem uncommon and
404        // rebuild() doesn't deal with precomputed_pseudo_element_decls for now so...
405        let mut new_data = servo_arc::UniqueArc::new(Self {
406            cascade_data: CascadeData::new(),
407            precomputed_pseudo_element_decls: PrecomputedPseudoElementDeclarations::default(),
408        });
409
410        let mut prev_sheet = None;
411        for (index, sheet) in collection.sheets().enumerate() {
412            let new_data = &mut *new_data;
413            new_data.cascade_data.add_stylesheet(
414                device,
415                quirks_mode,
416                sheet,
417                index,
418                guard,
419                SheetRebuildKind::Full,
420                Some(&mut new_data.precomputed_pseudo_element_decls),
421                None,
422                &mut prev_sheet,
423            )?;
424        }
425
426        new_data.cascade_data.did_finish_rebuild();
427        difference.update(&old.cascade_data, &new_data.cascade_data);
428
429        Ok(new_data.shareable())
430    }
431
432    #[cfg(feature = "gecko")]
433    fn add_size_of(&self, ops: &mut MallocSizeOfOps, sizes: &mut ServoStyleSetSizes) {
434        self.cascade_data.add_size_of(ops, sizes);
435        sizes.mPrecomputedPseudos += self.precomputed_pseudo_element_decls.size_of(ops);
436    }
437}
438
439type UserAgentCascadeDataCache = CascadeDataCache<UserAgentCascadeData>;
440
441/// The declarations for the precomputed pseudo-elements.
442///
443/// We don't need the rest of the fields of `ApplicableDeclarationBlock`: These are never sorted
444/// (they're in document order, and their selectors are all universal), and they're all UA rules in
445/// the root layer.
446type PrecomputedPseudoElementDeclarations = PerPseudoElementMap<Vec<StyleSource>>;
447
448#[derive(Default)]
449struct UserAgentCascadeData {
450    cascade_data: CascadeData,
451
452    /// Applicable declarations for a given non-eagerly cascaded pseudo-element.
453    ///
454    /// These are eagerly computed once, and then used to resolve the new
455    /// computed values on the fly on layout.
456    ///
457    /// These are only filled from UA stylesheets.
458    precomputed_pseudo_element_decls: PrecomputedPseudoElementDeclarations,
459}
460
461/// The empty UA cascade data for un-filled stylists.
462static EMPTY_UA_CASCADE_DATA: LazyLock<Arc<UserAgentCascadeData>> = LazyLock::new(|| {
463    let arc = Arc::new(UserAgentCascadeData::default());
464    arc.mark_as_intentionally_leaked();
465    arc
466});
467
468/// All the computed information for all the stylesheets that apply to the
469/// document.
470#[derive(MallocSizeOf)]
471pub struct DocumentCascadeData {
472    #[ignore_malloc_size_of = "Arc, owned by UserAgentCascadeDataCache or empty"]
473    user_agent: Arc<UserAgentCascadeData>,
474    user: CascadeData,
475    author: CascadeData,
476    per_origin: PerOrigin<()>,
477}
478
479impl Default for DocumentCascadeData {
480    fn default() -> Self {
481        Self {
482            user_agent: EMPTY_UA_CASCADE_DATA.clone(),
483            user: Default::default(),
484            author: Default::default(),
485            per_origin: Default::default(),
486        }
487    }
488}
489
490/// An iterator over the cascade data of a given document.
491pub struct DocumentCascadeDataIter<'a> {
492    iter: PerOriginIter<'a, ()>,
493    cascade_data: &'a DocumentCascadeData,
494}
495
496impl<'a> Iterator for DocumentCascadeDataIter<'a> {
497    type Item = (&'a CascadeData, Origin);
498
499    fn next(&mut self) -> Option<Self::Item> {
500        let (_, origin) = self.iter.next()?;
501        Some((self.cascade_data.borrow_for_origin(origin), origin))
502    }
503}
504
505impl DocumentCascadeData {
506    /// Borrows the cascade data for a given origin.
507    #[inline]
508    pub fn borrow_for_origin(&self, origin: Origin) -> &CascadeData {
509        match origin {
510            Origin::UserAgent => &self.user_agent.cascade_data,
511            Origin::Author => &self.author,
512            Origin::User => &self.user,
513        }
514    }
515
516    fn iter_origins(&self) -> DocumentCascadeDataIter<'_> {
517        DocumentCascadeDataIter {
518            iter: self.per_origin.iter_origins(),
519            cascade_data: self,
520        }
521    }
522
523    fn iter_origins_rev(&self) -> DocumentCascadeDataIter<'_> {
524        DocumentCascadeDataIter {
525            iter: self.per_origin.iter_origins_rev(),
526            cascade_data: self,
527        }
528    }
529
530    fn custom_media_for_sheet(
531        &self,
532        s: &StylistSheet,
533        guard: &SharedRwLockReadGuard,
534    ) -> &CustomMediaMap {
535        let origin = s.contents(guard).origin;
536        &self.borrow_for_origin(origin).custom_media
537    }
538
539    /// Rebuild the cascade data for the given document stylesheets, and
540    /// optionally with a set of user agent stylesheets.  Returns Err(..)
541    /// to signify OOM.
542    fn rebuild<'a, S>(
543        &mut self,
544        device: &Device,
545        quirks_mode: QuirksMode,
546        mut flusher: DocumentStylesheetFlusher<'a, S>,
547        guards: &StylesheetGuards,
548        difference: &mut CascadeDataDifference,
549    ) -> Result<(), AllocErr>
550    where
551        S: StylesheetInDocument + PartialEq + 'static,
552    {
553        // First do UA sheets.
554        {
555            let origin_flusher = flusher.flush_origin(Origin::UserAgent);
556            // Dirty check is just a minor optimization (no need to grab the
557            // lock if nothing has changed).
558            if origin_flusher.dirty() {
559                let mut ua_cache = UA_CASCADE_DATA_CACHE.lock().unwrap();
560                let new_data = ua_cache.lookup(
561                    device,
562                    quirks_mode,
563                    origin_flusher,
564                    guards.ua_or_user,
565                    &self.user_agent,
566                    difference,
567                )?;
568                if let Some(new_data) = new_data {
569                    self.user_agent = new_data;
570                }
571                let _unused_entries = ua_cache.take_unused();
572                // See the comments in take_unused() as for why the following line.
573                std::mem::drop(ua_cache);
574            }
575        }
576
577        // Now do the user sheets.
578        self.user.rebuild(
579            device,
580            quirks_mode,
581            flusher.flush_origin(Origin::User),
582            guards.ua_or_user,
583            difference,
584        )?;
585
586        // And now the author sheets.
587        self.author.rebuild(
588            device,
589            quirks_mode,
590            flusher.flush_origin(Origin::Author),
591            guards.author,
592            difference,
593        )?;
594
595        Ok(())
596    }
597
598    /// Measures heap usage.
599    #[cfg(feature = "gecko")]
600    pub fn add_size_of(&self, ops: &mut MallocSizeOfOps, sizes: &mut ServoStyleSetSizes) {
601        self.user.add_size_of(ops, sizes);
602        self.author.add_size_of(ops, sizes);
603    }
604}
605
606/// Whether author styles are enabled.
607///
608/// This is used to support Gecko.
609#[allow(missing_docs)]
610#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq)]
611pub enum AuthorStylesEnabled {
612    Yes,
613    No,
614}
615
616/// A wrapper over a DocumentStylesheetSet that can be `Sync`, since it's only
617/// used and exposed via mutable methods in the `Stylist`.
618#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
619#[derive(Deref, DerefMut)]
620struct StylistStylesheetSet(DocumentStylesheetSet<StylistSheet>);
621// Read above to see why this is fine.
622unsafe impl Sync for StylistStylesheetSet {}
623
624impl StylistStylesheetSet {
625    fn new() -> Self {
626        StylistStylesheetSet(DocumentStylesheetSet::new())
627    }
628}
629
630/// This structure holds all the selectors and device characteristics
631/// for a given document. The selectors are converted into `Rule`s
632/// and sorted into `SelectorMap`s keyed off stylesheet origin and
633/// pseudo-element (see `CascadeData`).
634///
635/// This structure is effectively created once per pipeline, in the
636/// LayoutThread corresponding to that pipeline.
637#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
638pub struct Stylist {
639    /// Device that the stylist is currently evaluating against.
640    ///
641    /// This field deserves a bigger comment due to the different use that Gecko
642    /// and Servo give to it (that we should eventually unify).
643    ///
644    /// With Gecko, the device is never changed. Gecko manually tracks whether
645    /// the device data should be reconstructed, and "resets" the state of the
646    /// device.
647    ///
648    /// On Servo, on the other hand, the device is a really cheap representation
649    /// that is recreated each time some constraint changes and calling
650    /// `set_device`.
651    device: Device,
652
653    /// The list of stylesheets.
654    stylesheets: StylistStylesheetSet,
655
656    /// A cache of CascadeDatas for AuthorStylesheetSets (i.e., shadow DOM).
657    #[cfg_attr(feature = "servo", ignore_malloc_size_of = "XXX: how to handle this?")]
658    author_data_cache: CascadeDataCache<CascadeData>,
659
660    /// If true, the quirks-mode stylesheet is applied.
661    #[cfg_attr(feature = "servo", ignore_malloc_size_of = "defined in selectors")]
662    quirks_mode: QuirksMode,
663
664    /// Selector maps for all of the style sheets in the stylist, after
665    /// evalutaing media rules against the current device, split out per
666    /// cascade level.
667    cascade_data: DocumentCascadeData,
668
669    /// Whether author styles are enabled.
670    author_styles_enabled: AuthorStylesEnabled,
671
672    /// The rule tree, that stores the results of selector matching.
673    rule_tree: RuleTree,
674
675    /// The set of registered custom properties from script.
676    /// <https://drafts.css-houdini.org/css-properties-values-api-1/#dom-window-registeredpropertyset-slot>
677    script_custom_properties: CustomPropertyScriptRegistry,
678
679    /// Initial values for registered custom properties.
680    #[cfg_attr(feature = "servo", ignore_malloc_size_of = "Arc")]
681    initial_values_for_custom_properties: ComputedCustomProperties,
682
683    /// Flags set from computing registered custom property initial values.
684    initial_values_for_custom_properties_flags: ComputedValueFlags,
685
686    /// The total number of times the stylist has been rebuilt.
687    num_rebuilds: usize,
688}
689
690/// What cascade levels to include when styling elements.
691#[derive(Clone, Copy, PartialEq)]
692pub enum RuleInclusion {
693    /// Include rules for style sheets at all cascade levels.  This is the
694    /// normal rule inclusion mode.
695    All,
696    /// Only include rules from UA and user level sheets.  Used to implement
697    /// `getDefaultComputedStyle`.
698    DefaultOnly,
699}
700
701#[cfg(feature = "gecko")]
702impl From<StyleRuleInclusion> for RuleInclusion {
703    fn from(value: StyleRuleInclusion) -> Self {
704        match value {
705            StyleRuleInclusion::All => RuleInclusion::All,
706            StyleRuleInclusion::DefaultOnly => RuleInclusion::DefaultOnly,
707        }
708    }
709}
710
711/// `:scope` selector, depending on the use case, can match a shadow host.
712/// If used outside of `@scope`, it cannot possibly match the host.
713/// Even when inside of `@scope`, it's conditional if the selector will
714/// match the shadow host.
715#[derive(Clone, Copy, Eq, PartialEq, Default)]
716enum ScopeMatchesShadowHost {
717    #[default]
718    NotApplicable,
719    No,
720    Yes,
721}
722
723impl ScopeMatchesShadowHost {
724    fn nest_for_scope(&mut self, matches_shadow_host: bool) {
725        match *self {
726            Self::NotApplicable => {
727                // We're at the outermost `@scope`.
728                *self = if matches_shadow_host {
729                    Self::Yes
730                } else {
731                    Self::No
732                };
733            },
734            Self::Yes if !matches_shadow_host => {
735                // Inner `@scope` will not be able to match the shadow host.
736                *self = Self::No;
737            },
738            _ => (),
739        }
740    }
741}
742
743/// Nested declarations have effectively two behaviors:
744///  * Inside style rules (where they behave as the containing selector).
745///  * Inside @scope (where they behave as :where(:scope)).
746/// It is a bit unfortunate ideally we wouldn't need this, because scope also pushes to the
747/// ancestor_selector_lists, but the behavior isn't quite the same as wrapping in `&`, see
748/// https://github.com/w3c/csswg-drafts/issues/10431
749#[derive(Copy, Clone)]
750enum NestedDeclarationsContext {
751    Style,
752    Scope,
753}
754
755/// A struct containing state related to scope rules
756struct ContainingScopeRuleState {
757    id: ScopeConditionId,
758    inner_dependencies: Vec<Dependency>,
759    matches_shadow_host: ScopeMatchesShadowHost,
760}
761
762impl Default for ContainingScopeRuleState {
763    fn default() -> Self {
764        Self {
765            id: ScopeConditionId::none(),
766            inner_dependencies: Vec::new(),
767            matches_shadow_host: Default::default(),
768        }
769    }
770}
771
772impl ContainingScopeRuleState {
773    fn save(&self) -> SavedContainingScopeRuleState {
774        SavedContainingScopeRuleState {
775            id: self.id,
776            matches_shadow_host: self.matches_shadow_host,
777            inner_dependencies_len: self.inner_dependencies.len(),
778        }
779    }
780
781    fn restore(
782        &mut self,
783        saved: &SavedContainingScopeRuleState,
784    ) -> Option<(Vec<Dependency>, ScopeConditionId)> {
785        debug_assert!(self.inner_dependencies.len() >= saved.inner_dependencies_len);
786
787        if self.id == saved.id {
788            return None;
789        }
790
791        let scope_id = self.id;
792        let inner_deps = self
793            .inner_dependencies
794            .drain(saved.inner_dependencies_len..)
795            .collect();
796
797        self.id = saved.id;
798        self.matches_shadow_host = saved.matches_shadow_host;
799
800        Some((inner_deps, scope_id))
801    }
802}
803
804struct SavedContainingScopeRuleState {
805    id: ScopeConditionId,
806    matches_shadow_host: ScopeMatchesShadowHost,
807    inner_dependencies_len: usize,
808}
809
810/// A struct containing state from ancestor rules like @layer / @import /
811/// @container / nesting / @scope.
812struct ContainingRuleState {
813    layer_name: LayerName,
814    layer_id: LayerId,
815    container_condition_id: ContainerConditionId,
816    cascade_flags: RuleCascadeFlags,
817    containing_scope_rule_state: ContainingScopeRuleState,
818    ancestor_selector_lists: SmallVec<[SelectorList<SelectorImpl>; 2]>,
819    nested_declarations_context: NestedDeclarationsContext,
820    /// Set by an `@scope` rule with no start selector, whose root belongs to the
821    /// sheet rather than to its shared contents. Latches for the whole sheet, so
822    /// it is deliberately not part of the saved/restored state.
823    saw_implicit_scope_root: bool,
824}
825
826impl Default for ContainingRuleState {
827    fn default() -> Self {
828        Self {
829            layer_name: LayerName::new_empty(),
830            layer_id: LayerId::root(),
831            container_condition_id: ContainerConditionId::none(),
832            cascade_flags: RuleCascadeFlags::empty(),
833            ancestor_selector_lists: Default::default(),
834            containing_scope_rule_state: Default::default(),
835            nested_declarations_context: NestedDeclarationsContext::Style,
836            saw_implicit_scope_root: false,
837        }
838    }
839}
840
841struct SavedContainingRuleState {
842    ancestor_selector_lists_len: usize,
843    layer_name_len: usize,
844    layer_id: LayerId,
845    container_condition_id: ContainerConditionId,
846    cascade_flags: RuleCascadeFlags,
847    saved_containing_scope_rule_state: SavedContainingScopeRuleState,
848    nested_declarations_context: NestedDeclarationsContext,
849}
850
851impl ContainingRuleState {
852    fn save(&self) -> SavedContainingRuleState {
853        SavedContainingRuleState {
854            ancestor_selector_lists_len: self.ancestor_selector_lists.len(),
855            layer_name_len: self.layer_name.0.len(),
856            layer_id: self.layer_id,
857            container_condition_id: self.container_condition_id,
858            cascade_flags: self.cascade_flags,
859            saved_containing_scope_rule_state: self.containing_scope_rule_state.save(),
860            nested_declarations_context: self.nested_declarations_context,
861        }
862    }
863
864    fn restore(
865        &mut self,
866        saved: &SavedContainingRuleState,
867    ) -> Option<(Vec<Dependency>, ScopeConditionId)> {
868        debug_assert!(self.layer_name.0.len() >= saved.layer_name_len);
869        debug_assert!(self.ancestor_selector_lists.len() >= saved.ancestor_selector_lists_len);
870
871        self.ancestor_selector_lists
872            .truncate(saved.ancestor_selector_lists_len);
873        self.layer_name.0.truncate(saved.layer_name_len);
874        self.layer_id = saved.layer_id;
875        self.container_condition_id = saved.container_condition_id;
876        self.cascade_flags = saved.cascade_flags;
877        self.nested_declarations_context = saved.nested_declarations_context;
878
879        self.containing_scope_rule_state
880            .restore(&saved.saved_containing_scope_rule_state)
881    }
882
883    fn scope_is_effective(&self) -> bool {
884        self.containing_scope_rule_state.id != ScopeConditionId::none()
885    }
886
887    fn cascade_flags(&self) -> RuleCascadeFlags {
888        self.cascade_flags
889    }
890}
891
892type ReplacedSelectors = SmallVec<[Selector<SelectorImpl>; 4]>;
893
894impl Stylist {
895    /// Construct a new `Stylist`, using given `Device` and `QuirksMode`.
896    /// If more members are added here, think about whether they should
897    /// be reset in clear().
898    #[inline]
899    pub fn new(device: Device, quirks_mode: QuirksMode) -> Self {
900        Self {
901            device,
902            quirks_mode,
903            stylesheets: StylistStylesheetSet::new(),
904            author_data_cache: CascadeDataCache::new(),
905            cascade_data: Default::default(),
906            author_styles_enabled: AuthorStylesEnabled::Yes,
907            rule_tree: RuleTree::new(),
908            script_custom_properties: Default::default(),
909            initial_values_for_custom_properties: Default::default(),
910            initial_values_for_custom_properties_flags: Default::default(),
911            num_rebuilds: 0,
912        }
913    }
914
915    /// Returns the document cascade data.
916    #[inline]
917    pub fn cascade_data(&self) -> &DocumentCascadeData {
918        &self.cascade_data
919    }
920
921    /// Returns whether author styles are enabled or not.
922    #[inline]
923    pub fn author_styles_enabled(&self) -> AuthorStylesEnabled {
924        self.author_styles_enabled
925    }
926
927    /// Iterate through all the cascade datas from the document.
928    #[inline]
929    pub fn iter_origins(&self) -> DocumentCascadeDataIter<'_> {
930        self.cascade_data.iter_origins()
931    }
932
933    /// Does what the name says, to prevent author_data_cache to grow without
934    /// bound.
935    pub fn remove_unique_author_data_cache_entries(&mut self) {
936        self.author_data_cache.take_unused();
937    }
938
939    /// Returns the custom property registration for this property's name.
940    /// https://drafts.css-houdini.org/css-properties-values-api-1/#determining-registration
941    pub fn get_custom_property_registration(&self, name: &Atom) -> &PropertyDescriptors {
942        if let Some(registration) = self.custom_property_script_registry().get(name) {
943            return &registration.descriptors;
944        }
945        for (data, _) in self.iter_origins() {
946            if let Some(registration) = data.custom_property_registrations.get(name) {
947                return &registration.descriptors;
948            }
949        }
950        PropertyDescriptors::unregistered()
951    }
952
953    /// Returns custom properties with their registered initial values.
954    pub fn get_custom_property_initial_values(&self) -> &ComputedCustomProperties {
955        &self.initial_values_for_custom_properties
956    }
957
958    /// Returns flags set from computing the registered custom property initial values.
959    pub fn get_custom_property_initial_values_flags(&self) -> ComputedValueFlags {
960        self.initial_values_for_custom_properties_flags
961    }
962
963    /// Rebuild custom properties with their registered initial values.
964    /// https://drafts.css-houdini.org/css-properties-values-api-1/#determining-registration
965    pub fn rebuild_initial_values_for_custom_properties(&mut self) {
966        let mut initial_values = ComputedCustomProperties::default();
967        let initial_values_flags;
968        {
969            let mut seen_names = PrecomputedHashSet::default();
970            let mut rule_cache_conditions = RuleCacheConditions::default();
971            let mut tree_counting_caches = TreeCountingCaches::default();
972            let context = computed::Context::new_for_initial_at_property_value(
973                self,
974                &mut rule_cache_conditions,
975                &mut tree_counting_caches,
976            );
977
978            for (k, v) in self.custom_property_script_registry().properties().iter() {
979                seen_names.insert(k.clone());
980                let Ok(value) = v.compute_initial_value(&context) else {
981                    continue;
982                };
983                let map = if v.descriptors.inherits() {
984                    &mut initial_values.inherited
985                } else {
986                    &mut initial_values.non_inherited
987                };
988                map.insert(k, value);
989            }
990            for (data, _) in self.iter_origins() {
991                for (k, v) in data.custom_property_registrations.iter() {
992                    if seen_names.insert(k.clone()) {
993                        let last_value = &v.last().unwrap().0;
994                        let Ok(value) = last_value.compute_initial_value(&context) else {
995                            continue;
996                        };
997                        let map = if last_value.descriptors.inherits() {
998                            &mut initial_values.inherited
999                        } else {
1000                            &mut initial_values.non_inherited
1001                        };
1002                        map.insert(k, value);
1003                    }
1004                }
1005            }
1006            initial_values_flags = context.builder.flags();
1007        }
1008        self.initial_values_for_custom_properties_flags = initial_values_flags;
1009        self.initial_values_for_custom_properties = initial_values;
1010    }
1011
1012    /// Rebuilds (if needed) the CascadeData given a sheet collection.
1013    pub fn rebuild_author_data<S>(
1014        &mut self,
1015        old_data: &CascadeData,
1016        collection: SheetCollectionFlusher<S>,
1017        guard: &SharedRwLockReadGuard,
1018        difference: &mut CascadeDataDifference,
1019    ) -> Result<Option<Arc<CascadeData>>, AllocErr>
1020    where
1021        S: StylesheetInDocument + PartialEq + 'static,
1022    {
1023        self.author_data_cache.lookup(
1024            &self.device,
1025            self.quirks_mode,
1026            collection,
1027            guard,
1028            old_data,
1029            difference,
1030        )
1031    }
1032
1033    /// Iterate over the extra data in origin order.
1034    #[inline]
1035    pub fn iter_extra_data_origins(&self) -> ExtraStyleDataIterator<'_> {
1036        ExtraStyleDataIterator(self.cascade_data.iter_origins())
1037    }
1038
1039    /// Iterate over the extra data in reverse origin order.
1040    #[inline]
1041    pub fn iter_extra_data_origins_rev(&self) -> ExtraStyleDataIterator<'_> {
1042        ExtraStyleDataIterator(self.cascade_data.iter_origins_rev())
1043    }
1044
1045    /// Returns the number of selectors.
1046    pub fn num_selectors(&self) -> usize {
1047        self.cascade_data
1048            .iter_origins()
1049            .map(|(d, _)| d.num_selectors)
1050            .sum()
1051    }
1052
1053    /// Returns the number of declarations.
1054    pub fn num_declarations(&self) -> usize {
1055        self.cascade_data
1056            .iter_origins()
1057            .map(|(d, _)| d.num_declarations)
1058            .sum()
1059    }
1060
1061    /// Returns the number of times the stylist has been rebuilt.
1062    pub fn num_rebuilds(&self) -> usize {
1063        self.num_rebuilds
1064    }
1065
1066    /// Returns the number of revalidation_selectors.
1067    pub fn num_revalidation_selectors(&self) -> usize {
1068        self.cascade_data
1069            .iter_origins()
1070            .map(|(data, _)| data.selectors_for_cache_revalidation.len())
1071            .sum()
1072    }
1073
1074    /// Returns the number of entries in invalidation maps.
1075    pub fn num_invalidations(&self) -> usize {
1076        self.cascade_data
1077            .iter_origins()
1078            .map(|(data, _)| {
1079                data.invalidation_map.len() + data.relative_selector_invalidation_map.len()
1080            })
1081            .sum()
1082    }
1083
1084    /// Returns whether the given DocumentState bit is relied upon by a selector
1085    /// of some rule.
1086    pub fn has_document_state_dependency(&self, state: DocumentState) -> bool {
1087        self.cascade_data
1088            .iter_origins()
1089            .any(|(d, _)| d.document_state_dependencies.intersects(state))
1090    }
1091
1092    /// Flush the list of stylesheets if they changed, ensuring the stylist is
1093    /// up-to-date.
1094    pub fn flush(&mut self, guards: &StylesheetGuards) -> StylesheetInvalidationSet {
1095        if !self.stylesheets.has_changed() {
1096            return Default::default();
1097        }
1098
1099        self.num_rebuilds += 1;
1100
1101        let cascade_data = &self.cascade_data;
1102        let (flusher, mut invalidations) = self.stylesheets.flush(&self.device, guards, |origin| {
1103            &cascade_data.borrow_for_origin(origin).custom_media
1104        });
1105
1106        self.cascade_data
1107            .rebuild(
1108                &self.device,
1109                self.quirks_mode,
1110                flusher,
1111                guards,
1112                &mut invalidations.cascade_data_difference,
1113            )
1114            .unwrap_or_else(|_| {
1115                warn!("OOM in Stylist::flush");
1116            });
1117
1118        self.rebuild_initial_values_for_custom_properties();
1119        invalidations
1120    }
1121
1122    /// Marks a given stylesheet origin as dirty, due to, for example, changes
1123    /// in the declarations that affect a given rule.
1124    ///
1125    /// FIXME(emilio): Eventually it'd be nice for this to become more
1126    /// fine-grained.
1127    pub fn force_stylesheet_origins_dirty(&mut self, origins: OriginSet) {
1128        self.stylesheets.force_dirty(origins)
1129    }
1130
1131    /// Sets whether author style is enabled or not.
1132    pub fn set_author_styles_enabled(&mut self, enabled: AuthorStylesEnabled) {
1133        self.author_styles_enabled = enabled;
1134    }
1135
1136    /// Returns whether we've recorded any stylesheet change so far.
1137    pub fn stylesheets_have_changed(&self) -> bool {
1138        self.stylesheets.has_changed()
1139    }
1140
1141    /// Insert a given stylesheet before another stylesheet in the document.
1142    pub fn insert_stylesheet_before(
1143        &mut self,
1144        sheet: StylistSheet,
1145        before_sheet: StylistSheet,
1146        guard: &SharedRwLockReadGuard,
1147    ) {
1148        self.stylesheets
1149            .insert_stylesheet_before(sheet, before_sheet, guard)
1150    }
1151
1152    /// Appends a new stylesheet to the current set.
1153    pub fn append_stylesheet(&mut self, sheet: StylistSheet, guard: &SharedRwLockReadGuard) {
1154        self.stylesheets.append_stylesheet(sheet, guard)
1155    }
1156
1157    /// Remove a given stylesheet to the current set.
1158    pub fn remove_stylesheet(&mut self, sheet: StylistSheet, guard: &SharedRwLockReadGuard) {
1159        let custom_media = self.cascade_data.custom_media_for_sheet(&sheet, guard);
1160        self.stylesheets
1161            .remove_stylesheet(Some(&self.device), custom_media, sheet, guard)
1162    }
1163
1164    /// Notify of a change of a given rule.
1165    pub fn rule_changed(
1166        &mut self,
1167        sheet: &StylistSheet,
1168        rule: &CssRule,
1169        guard: &SharedRwLockReadGuard,
1170        change_kind: RuleChangeKind,
1171        ancestors: &[CssRuleRef],
1172    ) {
1173        let custom_media = self.cascade_data.custom_media_for_sheet(sheet, guard);
1174        self.stylesheets.rule_changed(
1175            Some(&self.device),
1176            custom_media,
1177            sheet,
1178            rule,
1179            guard,
1180            change_kind,
1181            ancestors,
1182        )
1183    }
1184
1185    /// Get the total stylesheet count for a given origin.
1186    #[inline]
1187    pub fn sheet_count(&self, origin: Origin) -> usize {
1188        self.stylesheets.sheet_count(origin)
1189    }
1190
1191    /// Get the index-th stylesheet for a given origin.
1192    #[inline]
1193    pub fn sheet_at(&self, origin: Origin, index: usize) -> Option<&StylistSheet> {
1194        self.stylesheets.get(origin, index)
1195    }
1196
1197    /// Returns whether for any of the applicable style rule data a given
1198    /// condition is true.
1199    pub fn any_applicable_rule_data<E, F>(&self, element: E, mut f: F) -> bool
1200    where
1201        E: TElement,
1202        F: FnMut(&CascadeData) -> bool,
1203    {
1204        if f(&self.cascade_data.user_agent.cascade_data) {
1205            return true;
1206        }
1207
1208        let mut maybe = false;
1209
1210        let doc_author_rules_apply =
1211            element.each_applicable_non_document_style_rule_data(|data, _| {
1212                maybe = maybe || f(data);
1213            });
1214
1215        if maybe || f(&self.cascade_data.user) {
1216            return true;
1217        }
1218
1219        doc_author_rules_apply && f(&self.cascade_data.author)
1220    }
1221
1222    /// Execute callback for all applicable style rule data.
1223    pub fn for_each_cascade_data_with_scope<'a, E, F>(&'a self, element: E, mut f: F)
1224    where
1225        E: TElement + 'a,
1226        F: FnMut(&'a CascadeData, Option<E>),
1227    {
1228        f(&self.cascade_data.user_agent.cascade_data, None);
1229        element.each_applicable_non_document_style_rule_data(|data, scope| {
1230            f(data, Some(scope));
1231        });
1232        f(&self.cascade_data.user, None);
1233        f(&self.cascade_data.author, None);
1234    }
1235
1236    /// Computes the style for a given "precomputed" pseudo-element, taking the
1237    /// universal rules and applying them.
1238    pub fn precomputed_values_for_pseudo<E>(
1239        &self,
1240        guards: &StylesheetGuards,
1241        pseudo: &PseudoElement,
1242        parent: Option<&ComputedValues>,
1243    ) -> Arc<ComputedValues>
1244    where
1245        E: TElement,
1246    {
1247        debug_assert!(pseudo.is_precomputed());
1248
1249        let rule_node = self.rule_node_for_precomputed_pseudo(guards, pseudo, &[]);
1250
1251        self.precomputed_values_for_pseudo_with_rule_node::<E>(guards, pseudo, parent, rule_node)
1252    }
1253
1254    /// Computes the style for a given "precomputed" pseudo-element with
1255    /// given rule node.
1256    ///
1257    /// TODO(emilio): The type parameter could go away with a void type
1258    /// implementing TElement.
1259    pub fn precomputed_values_for_pseudo_with_rule_node<E>(
1260        &self,
1261        guards: &StylesheetGuards,
1262        pseudo: &PseudoElement,
1263        parent: Option<&ComputedValues>,
1264        rules: StrongRuleNode,
1265    ) -> Arc<ComputedValues>
1266    where
1267        E: TElement,
1268    {
1269        self.compute_pseudo_element_style_with_inputs::<E>(
1270            CascadeInputs {
1271                rules: Some(rules),
1272                visited_rules: None,
1273                flags: Default::default(),
1274                included_cascade_flags: RuleCascadeFlags::empty(),
1275            },
1276            pseudo,
1277            guards,
1278            parent,
1279            /* element */ None,
1280        )
1281    }
1282
1283    /// Returns the rule node for a given precomputed pseudo-element.
1284    ///
1285    /// If we want to include extra declarations to this precomputed
1286    /// pseudo-element, we can provide a vector of ApplicableDeclarationBlocks
1287    /// to extra_declarations. This is useful for @page rules.
1288    pub fn rule_node_for_precomputed_pseudo(
1289        &self,
1290        guards: &StylesheetGuards,
1291        pseudo: &PseudoElement,
1292        extra_declarations: &[ApplicableDeclarationBlock],
1293    ) -> StrongRuleNode {
1294        let declarations = match self
1295            .cascade_data
1296            .user_agent
1297            .precomputed_pseudo_element_decls
1298            .get(pseudo)
1299        {
1300            Some(declarations) => &**declarations,
1301            None => &[],
1302        };
1303
1304        let cascade_priority = CascadePriority::new(
1305            CascadeLevel::new(CascadeOrigin::UA),
1306            LayerOrder::root(),
1307            RuleCascadeFlags::empty(),
1308        );
1309        self.rule_tree.insert_ordered_rules_with_important(
1310            declarations
1311                .iter()
1312                .map(|source| (source.borrow(), cascade_priority))
1313                .chain(extra_declarations.iter().map(|d| d.for_rule_tree())),
1314            guards,
1315        )
1316    }
1317
1318    /// Returns the style for an anonymous box of the given type.
1319    ///
1320    /// TODO(emilio): The type parameter could go away with a void type
1321    /// implementing TElement.
1322    #[cfg(feature = "servo")]
1323    pub fn style_for_anonymous<E>(
1324        &self,
1325        guards: &StylesheetGuards,
1326        pseudo: &PseudoElement,
1327        parent_style: &ComputedValues,
1328    ) -> Arc<ComputedValues>
1329    where
1330        E: TElement,
1331    {
1332        self.precomputed_values_for_pseudo::<E>(guards, &pseudo, Some(parent_style))
1333    }
1334
1335    /// Computes a pseudo-element style lazily during layout.
1336    ///
1337    /// This can only be done for a certain set of pseudo-elements, like
1338    /// :selection.
1339    ///
1340    /// Check the documentation on lazy pseudo-elements in
1341    /// docs/components/style.md
1342    pub fn lazily_compute_pseudo_element_style<E>(
1343        &self,
1344        guards: &StylesheetGuards,
1345        element: E,
1346        pseudo: &PseudoElement,
1347        rule_inclusion: RuleInclusion,
1348        originating_element_style: &ComputedValues,
1349        is_probe: bool,
1350        matching_fn: Option<&dyn Fn(&PseudoElement) -> bool>,
1351    ) -> Option<Arc<ComputedValues>>
1352    where
1353        E: TElement,
1354    {
1355        let cascade_inputs = self.lazy_pseudo_rules(
1356            guards,
1357            element,
1358            originating_element_style,
1359            pseudo,
1360            is_probe,
1361            rule_inclusion,
1362            matching_fn,
1363        )?;
1364
1365        Some(self.compute_pseudo_element_style_with_inputs(
1366            cascade_inputs,
1367            pseudo,
1368            guards,
1369            Some(originating_element_style),
1370            Some(element),
1371        ))
1372    }
1373
1374    /// Computes a pseudo-element style lazily using the given CascadeInputs.
1375    /// This can be used for truly lazy pseudo-elements or to avoid redoing
1376    /// selector matching for eager pseudo-elements when we need to recompute
1377    /// their style with a new parent style.
1378    pub fn compute_pseudo_element_style_with_inputs<E>(
1379        &self,
1380        inputs: CascadeInputs,
1381        pseudo: &PseudoElement,
1382        guards: &StylesheetGuards,
1383        parent_style: Option<&ComputedValues>,
1384        element: Option<E>,
1385    ) -> Arc<ComputedValues>
1386    where
1387        E: TElement,
1388    {
1389        // FIXME(emilio): The lack of layout_parent_style here could be
1390        // worrying, but we're probably dropping the display fixup for
1391        // pseudos other than before and after, so it's probably ok.
1392        //
1393        // (Though the flags don't indicate so!)
1394        //
1395        // It'd be fine to assert that this isn't called with a parent style
1396        // where display contents is in effect, but in practice this is hard to
1397        // do for stuff like :-moz-fieldset-content with a
1398        // <fieldset style="display: contents">. That is, the computed value of
1399        // display for the fieldset is "contents", even though it's not the used
1400        // value, so we don't need to adjust in a different way anyway.
1401        self.cascade_style_and_visited(
1402            element,
1403            Some(pseudo),
1404            &inputs,
1405            guards,
1406            parent_style,
1407            parent_style,
1408            FirstLineReparenting::No,
1409            &PositionTryFallbacksTryTactic::default(),
1410            /* rule_cache = */ None,
1411            &mut RuleCacheConditions::default(),
1412            &mut TreeCountingCaches::default(),
1413        )
1414    }
1415
1416    /// Computes a fallback style lazily given the current and parent styles, and name.
1417    pub fn resolve_position_try<E>(
1418        &self,
1419        style: &ComputedValues,
1420        guards: &StylesheetGuards,
1421        scope: CascadeLevel,
1422        element: E,
1423        fallback_item: &PositionTryFallbacksItem,
1424    ) -> Option<Arc<ComputedValues>>
1425    where
1426        E: TElement,
1427    {
1428        let name_and_try_tactic = match *fallback_item {
1429            PositionTryFallbacksItem::PositionArea(area) => {
1430                // We don't bother passing the parent_style argument here since
1431                // we probably don't need it. If we do, we could wrap this up in
1432                // a style_resolver::with_default_parent_styles call, as below.
1433                let mut builder =
1434                    StyleBuilder::for_derived_style(&self.device, Some(self), style, None);
1435                builder.rules = style.rules.clone();
1436                builder.mutate_position().set_position_area(area);
1437                return Some(builder.build());
1438            },
1439            PositionTryFallbacksItem::IdentAndOrTactic(ref name_and_try_tactic) => {
1440                name_and_try_tactic
1441            },
1442        };
1443
1444        let fallback_rule = if !name_and_try_tactic.ident.is_empty() {
1445            Some(self.lookup_position_try(&name_and_try_tactic.ident.0, scope, element)?)
1446        } else {
1447            None
1448        };
1449        let fallback_block = fallback_rule
1450            .as_ref()
1451            .map(|r| &r.read_with(guards.author).block);
1452        let pseudo = style
1453            .pseudo()
1454            .or_else(|| element.implemented_pseudo_element());
1455        let inputs = {
1456            let mut inputs = CascadeInputs::new_from_style(style);
1457            // @position-try doesn't care about any :visited-dependent property.
1458            inputs.visited_rules = None;
1459            let rules = inputs.rules.as_ref().unwrap_or(self.rule_tree.root());
1460            let mut important_rules_changed = false;
1461            if let Some(fallback_block) = fallback_block {
1462                let new_rules = self.rule_tree.update_rule_at_level(
1463                    CascadeLevel::new(CascadeOrigin::PositionFallback),
1464                    LayerOrder::root(),
1465                    Some(fallback_block.borrow_arc()),
1466                    rules,
1467                    guards,
1468                    &mut important_rules_changed,
1469                );
1470                if new_rules.is_some() {
1471                    inputs.rules = new_rules;
1472                } else {
1473                    // This will return an identical style to `style`. We could consider optimizing
1474                    // this a bit more but for now just perform the cascade, this can only happen with
1475                    // the same position-try name repeated multiple times anyways.
1476                }
1477            }
1478            inputs
1479        };
1480        crate::style_resolver::with_default_parent_styles(
1481            element,
1482            |parent_style, layout_parent_style| {
1483                Some(self.cascade_style_and_visited(
1484                    Some(element),
1485                    pseudo.as_ref(),
1486                    &inputs,
1487                    guards,
1488                    parent_style,
1489                    layout_parent_style,
1490                    FirstLineReparenting::No,
1491                    &name_and_try_tactic.try_tactic,
1492                    /* rule_cache = */ None,
1493                    &mut RuleCacheConditions::default(),
1494                    &mut TreeCountingCaches::default(),
1495                ))
1496            },
1497        )
1498    }
1499
1500    /// Computes a style using the given CascadeInputs.  This can be used to
1501    /// compute a style any time we know what rules apply and just need to use
1502    /// the given parent styles.
1503    ///
1504    /// parent_style is the style to inherit from for properties affected by
1505    /// first-line ancestors.
1506    ///
1507    /// parent_style_ignoring_first_line is the style to inherit from for
1508    /// properties not affected by first-line ancestors.
1509    ///
1510    /// layout_parent_style is the style used for some property fixups.  It's
1511    /// the style of the nearest ancestor with a layout box.
1512    pub fn cascade_style_and_visited<E>(
1513        &self,
1514        element: Option<E>,
1515        pseudo: Option<&PseudoElement>,
1516        inputs: &CascadeInputs,
1517        guards: &StylesheetGuards,
1518        parent_style: Option<&ComputedValues>,
1519        layout_parent_style: Option<&ComputedValues>,
1520        first_line_reparenting: FirstLineReparenting,
1521        try_tactic: &PositionTryFallbacksTryTactic,
1522        rule_cache: Option<&RuleCache>,
1523        rule_cache_conditions: &mut RuleCacheConditions,
1524        tree_counting_caches: &mut TreeCountingCaches,
1525    ) -> Arc<ComputedValues>
1526    where
1527        E: TElement,
1528    {
1529        debug_assert!(pseudo.is_some() || element.is_some(), "Huh?");
1530
1531        // We need to compute visited values if we have visited rules or if our
1532        // parent has visited values.
1533        let visited_rules = match inputs.visited_rules.as_ref() {
1534            Some(rules) => Some(rules),
1535            None => {
1536                if parent_style.and_then(|s| s.visited_style()).is_some() {
1537                    Some(inputs.rules.as_ref().unwrap_or(self.rule_tree.root()))
1538                } else {
1539                    None
1540                }
1541            },
1542        };
1543
1544        let mut implemented_pseudo = None;
1545        // Read the comment on `precomputed_values_for_pseudo` to see why it's
1546        // difficult to assert that display: contents nodes never arrive here
1547        // (tl;dr: It doesn't apply for replaced elements and such, but the
1548        // computed value is still "contents").
1549        //
1550        // FIXME(emilio): We should assert that it holds if pseudo.is_none()!
1551        properties::cascade::<E>(
1552            self,
1553            pseudo.or_else(|| {
1554                implemented_pseudo = element.unwrap().implemented_pseudo_element();
1555                implemented_pseudo.as_ref()
1556            }),
1557            inputs.rules.as_ref().unwrap_or(self.rule_tree.root()),
1558            guards,
1559            parent_style,
1560            layout_parent_style,
1561            first_line_reparenting,
1562            try_tactic,
1563            visited_rules,
1564            inputs.flags,
1565            inputs.included_cascade_flags,
1566            rule_cache,
1567            rule_cache_conditions,
1568            element,
1569            tree_counting_caches,
1570        )
1571    }
1572
1573    /// Computes the cascade inputs for a lazily-cascaded pseudo-element.
1574    ///
1575    /// See the documentation on lazy pseudo-elements in
1576    /// docs/components/style.md
1577    fn lazy_pseudo_rules<E>(
1578        &self,
1579        guards: &StylesheetGuards,
1580        element: E,
1581        originating_element_style: &ComputedValues,
1582        pseudo: &PseudoElement,
1583        is_probe: bool,
1584        rule_inclusion: RuleInclusion,
1585        matching_fn: Option<&dyn Fn(&PseudoElement) -> bool>,
1586    ) -> Option<CascadeInputs>
1587    where
1588        E: TElement,
1589    {
1590        debug_assert!(pseudo.is_lazy());
1591
1592        let mut selector_caches = SelectorCaches::default();
1593        // No need to bother setting the selector flags when we're computing
1594        // default styles.
1595        let needs_selector_flags = if rule_inclusion == RuleInclusion::DefaultOnly {
1596            NeedsSelectorFlags::No
1597        } else {
1598            NeedsSelectorFlags::Yes
1599        };
1600
1601        let animation_declarations = AnimationDeclarations::default();
1602        let mut declarations = ApplicableDeclarationList::new();
1603        let mut matching_context = MatchingContext::<'_, E::Impl>::new(
1604            MatchingMode::ForStatelessPseudoElement,
1605            None,
1606            &mut selector_caches,
1607            self.quirks_mode,
1608            needs_selector_flags,
1609            MatchingForInvalidation::No,
1610        );
1611
1612        matching_context.pseudo_element_matching_fn = matching_fn;
1613        matching_context.extra_data.originating_element_style = Some(originating_element_style);
1614
1615        self.push_applicable_declarations(
1616            element,
1617            Some(pseudo),
1618            None,
1619            None,
1620            &animation_declarations,
1621            rule_inclusion,
1622            &mut declarations,
1623            &mut matching_context,
1624        );
1625
1626        if declarations.is_empty() && is_probe {
1627            return None;
1628        }
1629
1630        let rules = self.rule_tree.compute_rule_node(&mut declarations, guards);
1631
1632        let mut visited_rules = None;
1633        if originating_element_style.visited_style().is_some() {
1634            let mut declarations = ApplicableDeclarationList::new();
1635            let mut selector_caches = SelectorCaches::default();
1636
1637            let mut matching_context = MatchingContext::<'_, E::Impl>::new_for_visited(
1638                MatchingMode::ForStatelessPseudoElement,
1639                None,
1640                &mut selector_caches,
1641                VisitedHandlingMode::RelevantLinkVisited,
1642                self.quirks_mode,
1643                needs_selector_flags,
1644                MatchingForInvalidation::No,
1645            );
1646            matching_context.pseudo_element_matching_fn = matching_fn;
1647            matching_context.extra_data.originating_element_style = Some(originating_element_style);
1648
1649            self.push_applicable_declarations(
1650                element,
1651                Some(pseudo),
1652                None,
1653                None,
1654                &animation_declarations,
1655                rule_inclusion,
1656                &mut declarations,
1657                &mut matching_context,
1658            );
1659            if !declarations.is_empty() {
1660                let rule_node = self.rule_tree.insert_ordered_rules_with_important(
1661                    declarations.drain(..).map(|a| a.for_rule_tree()),
1662                    guards,
1663                );
1664                if rule_node != *self.rule_tree.root() {
1665                    visited_rules = Some(rule_node);
1666                }
1667            }
1668        }
1669
1670        Some(CascadeInputs {
1671            rules: Some(rules),
1672            visited_rules,
1673            flags: matching_context.extra_data.cascade_input_flags,
1674            included_cascade_flags: RuleCascadeFlags::empty(),
1675        })
1676    }
1677
1678    /// Set a given device, which may change the styles that apply to the
1679    /// document.
1680    ///
1681    /// Returns the sheet origins that were actually affected.
1682    ///
1683    /// This means that we may need to rebuild style data even if the
1684    /// stylesheets haven't changed.
1685    ///
1686    /// Also, the device that arrives here may need to take the viewport rules
1687    /// into account.
1688    pub fn set_device(&mut self, device: Device, guards: &StylesheetGuards) -> OriginSet {
1689        self.device = device;
1690        self.media_features_change_changed_style(guards, &self.device)
1691    }
1692
1693    /// Returns whether, given a media feature change, any previously-applicable
1694    /// style has become non-applicable, or vice-versa for each origin, using
1695    /// `device`.
1696    pub fn media_features_change_changed_style(
1697        &self,
1698        guards: &StylesheetGuards,
1699        device: &Device,
1700    ) -> OriginSet {
1701        debug!("Stylist::media_features_change_changed_style {:?}", device);
1702
1703        let mut origins = OriginSet::empty();
1704        let stylesheets = self.stylesheets.iter();
1705
1706        for (stylesheet, origin) in stylesheets {
1707            if origins.contains(origin.into()) {
1708                continue;
1709            }
1710
1711            let guard = guards.for_origin(origin);
1712            let origin_cascade_data = self.cascade_data.borrow_for_origin(origin);
1713
1714            let affected_changed = !origin_cascade_data.media_feature_affected_matches(
1715                stylesheet,
1716                guard,
1717                device,
1718                self.quirks_mode,
1719            );
1720
1721            if affected_changed {
1722                origins |= origin;
1723            }
1724        }
1725
1726        origins
1727    }
1728
1729    /// Returns the Quirks Mode of the document.
1730    pub fn quirks_mode(&self) -> QuirksMode {
1731        self.quirks_mode
1732    }
1733
1734    /// Sets the quirks mode of the document.
1735    pub fn set_quirks_mode(&mut self, quirks_mode: QuirksMode) {
1736        if self.quirks_mode == quirks_mode {
1737            return;
1738        }
1739        self.quirks_mode = quirks_mode;
1740        self.force_stylesheet_origins_dirty(OriginSet::all());
1741    }
1742
1743    /// Returns the applicable CSS declarations for the given element.
1744    pub fn push_applicable_declarations<'a, E>(
1745        &'a self,
1746        element: E,
1747        pseudo_element: Option<&PseudoElement>,
1748        style_attribute: Option<ArcBorrow<'a, Locked<PropertyDeclarationBlock>>>,
1749        smil_override: Option<ArcBorrow<'a, Locked<PropertyDeclarationBlock>>>,
1750        animation_declarations: &'a AnimationDeclarations,
1751        rule_inclusion: RuleInclusion,
1752        applicable_declarations: &mut ApplicableDeclarationList<'a>,
1753        context: &mut MatchingContext<E::Impl>,
1754    ) where
1755        E: TElement + 'a,
1756    {
1757        let mut cur = element;
1758        let mut pseudos = SmallVec::<[_; 2]>::new();
1759        if let Some(pseudo) = pseudo_element {
1760            pseudos.push(pseudo.clone());
1761        }
1762        while let Some(p) = cur.implemented_pseudo_element() {
1763            pseudos.push(p);
1764            let Some(parent_pseudo) = cur.pseudo_element_originating_element() else {
1765                break;
1766            };
1767            cur = parent_pseudo;
1768        }
1769        RuleCollector::new(
1770            self,
1771            element,
1772            cur,
1773            &pseudos,
1774            style_attribute,
1775            smil_override,
1776            animation_declarations,
1777            rule_inclusion,
1778            applicable_declarations,
1779            context,
1780        )
1781        .collect_all();
1782    }
1783
1784    /// Given an id, returns whether there might be any rules for that id in any
1785    /// of our rule maps.
1786    #[inline]
1787    pub fn may_have_rules_for_id<E>(&self, id: &WeakAtom, element: E) -> bool
1788    where
1789        E: TElement,
1790    {
1791        // If id needs to be compared case-insensitively, the logic below
1792        // wouldn't work. Just conservatively assume it may have such rules.
1793        match self.quirks_mode().classes_and_ids_case_sensitivity() {
1794            CaseSensitivity::AsciiCaseInsensitive => return true,
1795            CaseSensitivity::CaseSensitive => {},
1796        }
1797
1798        self.any_applicable_rule_data(element, |data| data.mapped_ids.contains(id))
1799    }
1800
1801    /// Looks up a CascadeData-dependent rule for a given element.
1802    ///
1803    /// NOTE(emilio): This is a best-effort thing, the right fix is a bit TBD because it involves
1804    /// "recording" which tree the name came from, see [1][2].
1805    ///
1806    /// [1]: https://github.com/w3c/csswg-drafts/issues/1995
1807    /// [2]: https://bugzil.la/1458189
1808    #[inline]
1809    fn lookup_element_dependent_at_rule<'a, T, F, E>(
1810        &'a self,
1811        element: E,
1812        find_in: F,
1813    ) -> Option<&'a T>
1814    where
1815        E: TElement + 'a,
1816        F: Fn(&'a CascadeData) -> Option<&'a T>,
1817    {
1818        macro_rules! try_find_in {
1819            ($data:expr) => {
1820                if let Some(thing) = find_in(&$data) {
1821                    return Some(thing);
1822                }
1823            };
1824        }
1825
1826        let mut result = None;
1827        let doc_rules_apply =
1828            element.each_applicable_non_document_style_rule_data(|data, _host| {
1829                if result.is_none() {
1830                    result = find_in(data);
1831                }
1832            });
1833
1834        if result.is_some() {
1835            return result;
1836        }
1837
1838        if doc_rules_apply {
1839            try_find_in!(self.cascade_data.author);
1840        }
1841        try_find_in!(self.cascade_data.user);
1842        try_find_in!(self.cascade_data.user_agent.cascade_data);
1843
1844        None
1845    }
1846
1847    /// Returns the registered `@keyframes` animation for the specified name.
1848    #[inline]
1849    pub fn lookup_keyframes<'a, E>(
1850        &'a self,
1851        name: &Atom,
1852        element: E,
1853    ) -> Option<&'a KeyframesAnimation>
1854    where
1855        E: TElement + 'a,
1856    {
1857        self.lookup_element_dependent_at_rule(element, |data| data.animations.get(name))
1858    }
1859
1860    /// Returns the last @view-transition rule
1861    /// <https://drafts.csswg.org/css-view-transitions-2/#resolve-view-transition-rule>
1862    #[inline]
1863    pub fn last_view_transition_rule(&self) -> Option<&Arc<ViewTransitionRule>> {
1864        // Iterate the effective rules sorted by origin and level
1865        self.iter_extra_data_origins()
1866            .flat_map(|(d, _)| d.view_transitions.iter())
1867            .last()
1868            .map(|(rule, _)| rule)
1869    }
1870
1871    /// Returns the registered `@position-try-rule` animation for the specified name.
1872    #[inline]
1873    fn lookup_position_try<'a, E>(
1874        &'a self,
1875        name: &Atom,
1876        scope: CascadeLevel,
1877        element: E,
1878    ) -> Option<&'a Arc<Locked<PositionTryRule>>>
1879    where
1880        E: TElement + 'a,
1881    {
1882        let mut shadow_root = scope.get_shadow_root_for_scoped(element);
1883        // https://drafts.csswg.org/css-shadow/#tree-scoped-name-global
1884        // "First search only the tree-scoped names associated with the same root as the tree-scoped reference."
1885        while let Some(r) = shadow_root {
1886            if let Some(rule) = r
1887                .style_data()
1888                .and_then(|data| data.extra_data.position_try_rules.get(name))
1889            {
1890                return Some(rule);
1891            }
1892            // "If no relevant tree-scoped name is found, and the root is a shadow root, then repeat this search in the root’s host’s node tree (recursively)."
1893            shadow_root = r.host().containing_shadow();
1894        }
1895
1896        for (data, _) in self.iter_extra_data_origins() {
1897            if let Some(r) = data.position_try_rules.get(name) {
1898                return Some(r);
1899            }
1900        }
1901        None
1902    }
1903
1904    /// Computes the match results of a given element against the set of
1905    /// revalidation selectors.
1906    pub fn match_revalidation_selectors<E>(
1907        &self,
1908        element: E,
1909        bloom: Option<&BloomFilter>,
1910        selector_caches: &mut SelectorCaches,
1911        needs_selector_flags: NeedsSelectorFlags,
1912    ) -> RevalidationResult
1913    where
1914        E: TElement,
1915    {
1916        let mut matching_context = MatchingContext::new_for_revalidation(
1917            bloom,
1918            selector_caches,
1919            self.quirks_mode,
1920            needs_selector_flags,
1921        );
1922
1923        // Note that, by the time we're revalidating, we're guaranteed that the
1924        // candidate and the entry have the same id, classes, and local name.
1925        // This means we're guaranteed to get the same rulehash buckets for all
1926        // the lookups, which means that the bitvecs are comparable. We verify
1927        // this in the caller by asserting that the bitvecs are same-length.
1928        let mut result = RevalidationResult::default();
1929        let mut relevant_attributes = &mut result.relevant_attributes;
1930        let selectors_matched = &mut result.selectors_matched;
1931
1932        let matches_document_rules =
1933            element.each_applicable_non_document_style_rule_data(|data, host| {
1934                matching_context.with_shadow_host(Some(host), |matching_context| {
1935                    data.selectors_for_cache_revalidation.lookup(
1936                        element,
1937                        self.quirks_mode,
1938                        Some(&mut relevant_attributes),
1939                        |selector_and_hashes| {
1940                            selectors_matched.push(matches_selector(
1941                                &selector_and_hashes.selector,
1942                                selector_and_hashes.selector_offset,
1943                                Some(&selector_and_hashes.hashes),
1944                                element,
1945                                matching_context,
1946                            ));
1947                            true
1948                        },
1949                    );
1950                })
1951            });
1952
1953        for (data, origin) in self.cascade_data.iter_origins() {
1954            if origin == Origin::Author && !matches_document_rules {
1955                continue;
1956            }
1957
1958            data.selectors_for_cache_revalidation.lookup(
1959                element,
1960                self.quirks_mode,
1961                Some(&mut relevant_attributes),
1962                |selector_and_hashes| {
1963                    selectors_matched.push(matches_selector(
1964                        &selector_and_hashes.selector,
1965                        selector_and_hashes.selector_offset,
1966                        Some(&selector_and_hashes.hashes),
1967                        element,
1968                        &mut matching_context,
1969                    ));
1970                    true
1971                },
1972            );
1973        }
1974
1975        result
1976    }
1977
1978    /// Computes currently active scopes for the given element for revalidation purposes.
1979    pub fn revalidate_scopes<E: TElement>(
1980        &self,
1981        element: &E,
1982        selector_caches: &mut SelectorCaches,
1983        needs_selector_flags: NeedsSelectorFlags,
1984    ) -> ScopeRevalidationResult {
1985        let mut matching_context = MatchingContext::new(
1986            MatchingMode::Normal,
1987            None,
1988            selector_caches,
1989            self.quirks_mode,
1990            needs_selector_flags,
1991            MatchingForInvalidation::No,
1992        );
1993
1994        let mut result = ScopeRevalidationResult::default();
1995        let matches_document_rules =
1996            element.each_applicable_non_document_style_rule_data(|data, host| {
1997                matching_context.with_shadow_host(Some(host), |matching_context| {
1998                    data.revalidate_scopes(element, matching_context, &mut result);
1999                })
2000            });
2001
2002        for (data, origin) in self.cascade_data.iter_origins() {
2003            if origin == Origin::Author && !matches_document_rules {
2004                continue;
2005            }
2006
2007            data.revalidate_scopes(element, &mut matching_context, &mut result);
2008        }
2009
2010        result
2011    }
2012
2013    /// Computes styles for a given declaration with parent_style.
2014    ///
2015    /// FIXME(emilio): the lack of pseudo / cascade flags look quite dubious,
2016    /// hopefully this is only used for some canvas font stuff.
2017    ///
2018    /// TODO(emilio): The type parameter can go away when
2019    /// https://github.com/rust-lang/rust/issues/35121 is fixed.
2020    pub fn compute_for_declarations<E>(
2021        &self,
2022        guards: &StylesheetGuards,
2023        parent_style: &ComputedValues,
2024        declarations: Arc<Locked<PropertyDeclarationBlock>>,
2025    ) -> Arc<ComputedValues>
2026    where
2027        E: TElement,
2028    {
2029        let block = declarations.read_with(guards.author);
2030
2031        // We don't bother inserting these declarations in the rule tree, since
2032        // it'd be quite useless and slow.
2033        //
2034        // TODO(emilio): Now that we fixed bug 1493420, we should consider
2035        // reversing this as it shouldn't be slow anymore, and should avoid
2036        // generating two instantiations of apply_declarations.
2037        properties::apply_declarations::<E, _>(
2038            self,
2039            /* pseudo = */ None,
2040            self.rule_tree.root(),
2041            guards,
2042            block.declaration_importance_iter().map(|(declaration, _)| {
2043                (
2044                    declaration,
2045                    CascadePriority::new(
2046                        CascadeLevel::same_tree_author_normal(),
2047                        LayerOrder::root(),
2048                        RuleCascadeFlags::empty(),
2049                    ),
2050                )
2051            }),
2052            Some(parent_style),
2053            Some(parent_style),
2054            FirstLineReparenting::No,
2055            &PositionTryFallbacksTryTactic::default(),
2056            CascadeMode::Unvisited {
2057                visited_rules: None,
2058            },
2059            Default::default(),
2060            RuleCascadeFlags::empty(),
2061            /* rule_cache = */ None,
2062            &mut Default::default(),
2063            /* element = */ None,
2064            &mut TreeCountingCaches::default(),
2065        )
2066    }
2067
2068    /// Accessor for a shared reference to the device.
2069    #[inline]
2070    pub fn device(&self) -> &Device {
2071        &self.device
2072    }
2073
2074    /// Accessor for a mutable reference to the device.
2075    #[inline]
2076    pub fn device_mut(&mut self) -> &mut Device {
2077        &mut self.device
2078    }
2079
2080    /// Accessor for a shared reference to the rule tree.
2081    #[inline]
2082    pub fn rule_tree(&self) -> &RuleTree {
2083        &self.rule_tree
2084    }
2085
2086    /// Returns the script-registered custom property registry.
2087    #[inline]
2088    pub fn custom_property_script_registry(&self) -> &CustomPropertyScriptRegistry {
2089        &self.script_custom_properties
2090    }
2091
2092    /// Returns the script-registered custom property registry, as a mutable ref.
2093    #[inline]
2094    pub fn custom_property_script_registry_mut(&mut self) -> &mut CustomPropertyScriptRegistry {
2095        &mut self.script_custom_properties
2096    }
2097
2098    /// Measures heap usage.
2099    #[cfg(feature = "gecko")]
2100    pub fn add_size_of(&self, ops: &mut MallocSizeOfOps, sizes: &mut ServoStyleSetSizes) {
2101        self.cascade_data.add_size_of(ops, sizes);
2102        self.author_data_cache.add_size_of(ops, sizes);
2103        sizes.mRuleTree += self.rule_tree.size_of(ops);
2104
2105        // We may measure other fields in the future if DMD says it's worth it.
2106    }
2107
2108    /// Shutdown the static data that this module stores.
2109    pub fn shutdown() {
2110        let _entries = UA_CASCADE_DATA_CACHE.lock().unwrap().take_all();
2111    }
2112}
2113
2114#[allow(missing_docs)]
2115#[repr(u8)]
2116pub enum RegisterCustomPropertyResult {
2117    SuccessfullyRegistered,
2118    InvalidName,
2119    AlreadyRegistered,
2120    InvalidSyntax,
2121    NoInitialValue,
2122    InvalidInitialValue,
2123    InitialValueNotComputationallyIndependent,
2124}
2125
2126impl Stylist {
2127    /// <https://drafts.css-houdini.org/css-properties-values-api-1/#the-registerproperty-function>
2128    pub fn register_custom_property(
2129        &mut self,
2130        url_data: &UrlExtraData,
2131        name: &str,
2132        syntax: &str,
2133        inherits: bool,
2134        initial_value: Option<&str>,
2135    ) -> RegisterCustomPropertyResult {
2136        use RegisterCustomPropertyResult::*;
2137
2138        // If name is not a custom property name string, throw a SyntaxError and exit this algorithm.
2139        let Ok(name) = parse_name(name).map(Atom::from) else {
2140            return InvalidName;
2141        };
2142
2143        // If property set already contains an entry with name as its property name (compared
2144        // codepoint-wise), throw an InvalidModificationError and exit this algorithm.
2145        if self.custom_property_script_registry().get(&name).is_some() {
2146            return AlreadyRegistered;
2147        }
2148        // Attempt to consume a syntax definition from syntax. If it returns failure, throw a
2149        // SyntaxError. Otherwise, let syntax definition be the returned syntax definition.
2150        let Ok(syntax) = Descriptor::from_str(syntax, /* preserve_specified = */ false) else {
2151            return InvalidSyntax;
2152        };
2153
2154        let initial_value = match initial_value {
2155            Some(value) => {
2156                let parser_context = ParserContext::new(
2157                    Origin::Author,
2158                    url_data,
2159                    None,
2160                    ParsingMode::DISALLOW_COMPUTATIONALLY_DEPENDENT,
2161                    self.quirks_mode,
2162                    /* namespaces = */ Default::default(),
2163                    None,
2164                    None,
2165                    AttrTaint::default(),
2166                );
2167                let parsed = Parser::new(value)
2168                    .parse_entirely(|input| {
2169                        input.skip_whitespace();
2170                        SpecifiedValue::parse(&parser_context, input).map(Arc::new)
2171                    })
2172                    .ok();
2173                if parsed.is_none() {
2174                    return InvalidInitialValue;
2175                }
2176                parsed
2177            },
2178            None => None,
2179        };
2180
2181        if let Err(error) = PropertyRegistration::validate_initial_value(
2182            PropertyIdRef::from(&name),
2183            &syntax,
2184            initial_value.as_deref(),
2185        ) {
2186            return match error {
2187                PropertyRegistrationError::InitialValueNotComputationallyIndependent => {
2188                    InitialValueNotComputationallyIndependent
2189                },
2190                PropertyRegistrationError::InvalidInitialValue => InvalidInitialValue,
2191                PropertyRegistrationError::NoInitialValue => NoInitialValue,
2192            };
2193        }
2194
2195        let property_registration = PropertyRegistration {
2196            name: PropertyRuleName(name),
2197            descriptors: PropertyDescriptors {
2198                syntax: Some(syntax),
2199                inherits: Some(if inherits {
2200                    Inherits::True
2201                } else {
2202                    Inherits::False
2203                }),
2204                initial_value,
2205            },
2206            url_data: url_data.clone(),
2207            source_location: SourceLocation { line: 0, column: 0 },
2208        };
2209        self.custom_property_script_registry_mut()
2210            .register(property_registration);
2211        self.rebuild_initial_values_for_custom_properties();
2212
2213        SuccessfullyRegistered
2214    }
2215}
2216
2217/// A vector that is sorted in layer order.
2218#[derive(Clone, Debug, Deref, MallocSizeOf)]
2219pub struct LayerOrderedVec<T>(Vec<(T, LayerId)>);
2220impl<T> Default for LayerOrderedVec<T> {
2221    fn default() -> Self {
2222        Self(Default::default())
2223    }
2224}
2225
2226/// A map that is sorted in layer order.
2227#[derive(Clone, Debug, Deref, MallocSizeOf)]
2228pub struct LayerOrderedMap<T>(PrecomputedHashMap<Atom, SmallVec<[(T, LayerId); 1]>>);
2229impl<T> Default for LayerOrderedMap<T> {
2230    fn default() -> Self {
2231        Self(Default::default())
2232    }
2233}
2234
2235impl<T: 'static> LayerOrderedVec<T> {
2236    fn clear(&mut self) {
2237        self.0.clear();
2238    }
2239    fn push(&mut self, v: T, id: LayerId) {
2240        self.0.push((v, id));
2241    }
2242    fn sort(&mut self, layers: &[CascadeLayer]) {
2243        self.0.sort_by_key(|(_, id)| layers[id.0 as usize].order)
2244    }
2245}
2246
2247impl<T: 'static> LayerOrderedMap<T> {
2248    fn shrink_if_needed(&mut self) {
2249        self.0.shrink_if_needed();
2250    }
2251    fn clear(&mut self) {
2252        self.0.clear();
2253    }
2254    fn try_insert(&mut self, name: &Atom, v: T, id: LayerId) -> Result<(), AllocErr> {
2255        self.try_insert_with(name, v, id, |_, _| Ordering::Equal)
2256    }
2257    fn try_insert_with(
2258        &mut self,
2259        name: &Atom,
2260        v: T,
2261        id: LayerId,
2262        cmp: impl Fn(&T, &T) -> Ordering,
2263    ) -> Result<(), AllocErr> {
2264        self.0.try_reserve(1)?;
2265        let vec = self.0.entry_ref(name).or_default();
2266        if let Some(&mut (ref mut val, ref last_id)) = vec.last_mut()
2267            && *last_id == id
2268        {
2269            if cmp(val, &v) != Ordering::Greater {
2270                *val = v;
2271            }
2272            return Ok(());
2273        }
2274        vec.push((v, id));
2275        Ok(())
2276    }
2277    fn sort(&mut self, layers: &[CascadeLayer]) {
2278        self.sort_with(layers, |_, _| Ordering::Equal)
2279    }
2280    fn sort_with(&mut self, layers: &[CascadeLayer], cmp: impl Fn(&T, &T) -> Ordering) {
2281        for (_, v) in self.0.iter_mut() {
2282            v.sort_by(|(v1, id1), (v2, id2)| {
2283                let order1 = layers[id1.0 as usize].order;
2284                let order2 = layers[id2.0 as usize].order;
2285                order1.cmp(&order2).then_with(|| cmp(v1, v2))
2286            })
2287        }
2288    }
2289    /// Get an entry on the LayerOrderedMap by name.
2290    pub fn get(&self, name: &Atom) -> Option<&T> {
2291        let vec = self.0.get(name)?;
2292        Some(&vec.last()?.0)
2293    }
2294}
2295
2296/// Wrapper to allow better tracking of memory usage by page rule lists.
2297///
2298/// This includes the layer ID for use with the named page table.
2299#[derive(Clone, Debug, MallocSizeOf)]
2300pub struct PageRuleData {
2301    /// Layer ID for sorting page rules after matching.
2302    pub layer: LayerId,
2303    /// Page rule
2304    #[ignore_malloc_size_of = "Arc, stylesheet measures as primary ref"]
2305    pub rule: Arc<Locked<PageRule>>,
2306}
2307
2308/// Stores page rules indexed by page names.
2309#[derive(Clone, Debug, Default, MallocSizeOf)]
2310pub struct PageRuleMap {
2311    /// Page rules, indexed by page name. An empty atom indicates no page name.
2312    pub rules: PrecomputedHashMap<Atom, SmallVec<[PageRuleData; 1]>>,
2313}
2314
2315impl PageRuleMap {
2316    #[inline]
2317    fn clear(&mut self) {
2318        self.rules.clear();
2319    }
2320
2321    /// Uses page-name and pseudo-classes to match all applicable
2322    /// page-rules and append them to the matched_rules vec.
2323    /// This will ensure correct rule order for cascading.
2324    pub fn match_and_append_rules<'a>(
2325        &'a self,
2326        matched_rules: &mut Vec<ApplicableDeclarationBlock<'a>>,
2327        origin: Origin,
2328        guards: &'a StylesheetGuards,
2329        cascade_data: &'a DocumentCascadeData,
2330        name: &Option<Atom>,
2331        pseudos: PagePseudoClassFlags,
2332    ) {
2333        let level = match origin {
2334            Origin::UserAgent => CascadeLevel::new(CascadeOrigin::UA),
2335            Origin::User => CascadeLevel::new(CascadeOrigin::User),
2336            Origin::Author => CascadeLevel::same_tree_author_normal(),
2337        };
2338        let cascade_data = cascade_data.borrow_for_origin(origin);
2339        let start = matched_rules.len();
2340
2341        self.match_and_add_rules(
2342            matched_rules,
2343            level,
2344            guards,
2345            cascade_data,
2346            &atom!(""),
2347            pseudos,
2348        );
2349        if let Some(name) = name {
2350            self.match_and_add_rules(matched_rules, level, guards, cascade_data, name, pseudos);
2351        }
2352
2353        // Because page-rules do not have source location information stored,
2354        // use stable sort to ensure source locations are preserved.
2355        matched_rules[start..].sort_by_key(|block| block.sort_key());
2356    }
2357
2358    fn match_and_add_rules<'a>(
2359        &'a self,
2360        extra_declarations: &mut Vec<ApplicableDeclarationBlock<'a>>,
2361        level: CascadeLevel,
2362        guards: &'a StylesheetGuards,
2363        cascade_data: &'a CascadeData,
2364        name: &Atom,
2365        pseudos: PagePseudoClassFlags,
2366    ) {
2367        let rules = match self.rules.get(name) {
2368            Some(rules) => rules,
2369            None => return,
2370        };
2371        for data in rules.iter() {
2372            let rule = data.rule.read_with(level.guard(guards));
2373            let specificity = match rule.match_specificity(pseudos) {
2374                Some(specificity) => specificity,
2375                None => continue,
2376            };
2377            extra_declarations.push(ApplicableDeclarationBlock::new(
2378                StyleSourceBorrow::from_declarations(rule.block.borrow_arc()),
2379                0,
2380                level,
2381                specificity,
2382                cascade_data.layer_order_for(data.layer),
2383                ScopeProximity::infinity(), // Page rule can't have nested rules anyway.
2384                RuleCascadeFlags::empty(),
2385            ));
2386        }
2387    }
2388}
2389
2390impl MallocShallowSizeOf for PageRuleMap {
2391    fn shallow_size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2392        self.rules.shallow_size_of(ops)
2393    }
2394}
2395
2396type PositionTryMap = LayerOrderedMap<Arc<Locked<PositionTryRule>>>;
2397
2398/// This struct holds data which users of Stylist may want to extract from stylesheets which can be
2399/// done at the same time as updating.
2400#[derive(Clone, Debug, Default)]
2401pub struct ExtraStyleData {
2402    /// A list of effective font-face rules and their origin.
2403    pub font_faces: LayerOrderedVec<Arc<Locked<FontFaceRule>>>,
2404
2405    /// A list of effective font-feature-values rules.
2406    pub font_feature_values: LayerOrderedVec<Arc<FontFeatureValuesRule>>,
2407
2408    /// A list of effective font-palette-values rules.
2409    pub font_palette_values: LayerOrderedVec<Arc<FontPaletteValuesRule>>,
2410
2411    /// A map of effective counter-style rules.
2412    pub counter_styles: LayerOrderedMap<Arc<Locked<CounterStyleRule>>>,
2413
2414    /// A map of effective @position-try rules.
2415    pub position_try_rules: PositionTryMap,
2416
2417    /// A map of effective page rules.
2418    pub pages: PageRuleMap,
2419
2420    /// A list of effective @view-transition rules.
2421    pub view_transitions: LayerOrderedVec<Arc<ViewTransitionRule>>,
2422}
2423
2424impl ExtraStyleData {
2425    /// Add the given @font-face rule.
2426    fn add_font_face(&mut self, rule: &Arc<Locked<FontFaceRule>>, layer: LayerId) {
2427        self.font_faces.push(rule.clone(), layer);
2428    }
2429
2430    /// Add the given @font-feature-values rule.
2431    fn add_font_feature_values(&mut self, rule: &Arc<FontFeatureValuesRule>, layer: LayerId) {
2432        self.font_feature_values.push(rule.clone(), layer);
2433    }
2434
2435    /// Add the given @font-palette-values rule.
2436    fn add_font_palette_values(&mut self, rule: &Arc<FontPaletteValuesRule>, layer: LayerId) {
2437        self.font_palette_values.push(rule.clone(), layer);
2438    }
2439
2440    /// Add the given @counter-style rule.
2441    fn add_counter_style(
2442        &mut self,
2443        guard: &SharedRwLockReadGuard,
2444        rule: &Arc<Locked<CounterStyleRule>>,
2445        layer: LayerId,
2446    ) -> Result<(), AllocErr> {
2447        let name = &rule.read_with(guard).name().0;
2448        self.counter_styles.try_insert(name, rule.clone(), layer)
2449    }
2450
2451    /// Add the given @position-try rule.
2452    fn add_position_try(
2453        &mut self,
2454        name: Atom,
2455        rule: Arc<Locked<PositionTryRule>>,
2456        layer: LayerId,
2457    ) -> Result<(), AllocErr> {
2458        self.position_try_rules.try_insert(&name, rule, layer)
2459    }
2460
2461    /// Add the given @page rule.
2462    fn add_page(
2463        &mut self,
2464        guard: &SharedRwLockReadGuard,
2465        rule: &Arc<Locked<PageRule>>,
2466        layer: LayerId,
2467    ) -> Result<(), AllocErr> {
2468        let page_rule = rule.read_with(guard);
2469        let mut add_rule = |name: &Atom| {
2470            let vec = self.pages.rules.entry_ref(name).or_default();
2471            vec.push(PageRuleData {
2472                layer,
2473                rule: rule.clone(),
2474            });
2475        };
2476        if page_rule.selectors.0.is_empty() {
2477            add_rule(&atom!(""));
2478        } else {
2479            for selector in page_rule.selectors.as_slice() {
2480                add_rule(&selector.name.0);
2481            }
2482        }
2483        Ok(())
2484    }
2485
2486    fn add_view_transition(&mut self, rule: &Arc<ViewTransitionRule>, layer: LayerId) {
2487        self.view_transitions.push(rule.clone(), layer)
2488    }
2489
2490    fn sort_by_layer(&mut self, layers: &[CascadeLayer]) {
2491        self.font_faces.sort(layers);
2492        self.font_feature_values.sort(layers);
2493        self.font_palette_values.sort(layers);
2494        self.counter_styles.sort(layers);
2495        self.position_try_rules.sort(layers);
2496        self.view_transitions.sort(layers);
2497    }
2498
2499    fn clear(&mut self) {
2500        self.font_faces.clear();
2501        self.font_feature_values.clear();
2502        self.font_palette_values.clear();
2503        self.counter_styles.clear();
2504        self.position_try_rules.clear();
2505        self.pages.clear();
2506        self.view_transitions.clear();
2507    }
2508}
2509
2510// Don't let a prefixed keyframes animation override
2511// a non-prefixed one.
2512fn compare_keyframes_in_same_layer(v1: &KeyframesAnimation, v2: &KeyframesAnimation) -> Ordering {
2513    if v1.vendor_prefix.is_some() == v2.vendor_prefix.is_some() {
2514        Ordering::Equal
2515    } else if v2.vendor_prefix.is_some() {
2516        Ordering::Greater
2517    } else {
2518        Ordering::Less
2519    }
2520}
2521
2522/// An iterator over the different ExtraStyleData.
2523pub struct ExtraStyleDataIterator<'a>(DocumentCascadeDataIter<'a>);
2524
2525impl<'a> Iterator for ExtraStyleDataIterator<'a> {
2526    type Item = (&'a ExtraStyleData, Origin);
2527
2528    fn next(&mut self) -> Option<Self::Item> {
2529        self.0.next().map(|d| (&d.0.extra_data, d.1))
2530    }
2531}
2532
2533impl MallocSizeOf for ExtraStyleData {
2534    /// Measure heap usage.
2535    fn size_of(&self, ops: &mut MallocSizeOfOps) -> usize {
2536        let mut n = 0;
2537        n += self.font_faces.shallow_size_of(ops);
2538        n += self.font_feature_values.shallow_size_of(ops);
2539        n += self.font_palette_values.shallow_size_of(ops);
2540        n += self.counter_styles.shallow_size_of(ops);
2541        n += self.position_try_rules.shallow_size_of(ops);
2542        n += self.pages.shallow_size_of(ops);
2543        n
2544    }
2545}
2546
2547/// SelectorMapEntry implementation for use in our revalidation selector map.
2548#[derive(Clone, Debug, MallocSizeOf)]
2549struct RevalidationSelectorAndHashes {
2550    #[ignore_malloc_size_of = "CssRules have primary refs, we measure there"]
2551    selector: Selector<SelectorImpl>,
2552    selector_offset: usize,
2553    hashes: AncestorHashes,
2554}
2555
2556impl RevalidationSelectorAndHashes {
2557    fn new(selector: Selector<SelectorImpl>, hashes: AncestorHashes) -> Self {
2558        let selector_offset = {
2559            // We basically want to check whether the first combinator is a
2560            // pseudo-element combinator.  If it is, we want to use the offset
2561            // one past it.  Otherwise, our offset is 0.
2562            let mut index = 0;
2563            let mut iter = selector.iter();
2564
2565            // First skip over the first ComplexSelector.
2566            //
2567            // We can't check what sort of what combinator we have until we do
2568            // that.
2569            for _ in &mut iter {
2570                index += 1; // Simple selector
2571            }
2572
2573            match iter.next_sequence() {
2574                Some(Combinator::PseudoElement) => index + 1, // +1 for the combinator
2575                _ => 0,
2576            }
2577        };
2578
2579        RevalidationSelectorAndHashes {
2580            selector,
2581            selector_offset,
2582            hashes,
2583        }
2584    }
2585}
2586
2587impl SelectorMapEntry for RevalidationSelectorAndHashes {
2588    fn selector(&self) -> SelectorIter<'_, SelectorImpl> {
2589        self.selector.iter_from(self.selector_offset)
2590    }
2591}
2592
2593/// A selector visitor implementation that collects all the state the Stylist
2594/// cares about a selector.
2595struct StylistSelectorVisitor<'a> {
2596    /// Whether we've past the rightmost compound selector, not counting
2597    /// pseudo-elements.
2598    passed_rightmost_selector: bool,
2599
2600    /// Whether the selector needs revalidation for the style sharing cache.
2601    needs_revalidation: &'a mut bool,
2602
2603    /// Whether any selector can make the match result of an element that isn't
2604    /// itself a link depend on the visitedness of a link.
2605    non_link_visited_dependency: &'a mut bool,
2606
2607    /// Flags for which selector list-containing components the visitor is
2608    /// inside of, if any
2609    in_selector_list_of: SelectorListKind,
2610
2611    /// The filter with all the id's getting referenced from selectors.
2612    mapped_ids: &'a mut PrecomputedHashSet<Atom>,
2613
2614    /// The filter with the IDs getting referenced from the selector list of
2615    /// :nth-child(... of <selector list>) selectors.
2616    nth_of_mapped_ids: &'a mut PrecomputedHashSet<Atom>,
2617
2618    /// The filter with the local names of attributes there are selectors for.
2619    attribute_dependencies: &'a mut PrecomputedHashSet<LocalName>,
2620
2621    /// The filter with the classes getting referenced from the selector list of
2622    /// :nth-child(... of <selector list>) selectors.
2623    nth_of_class_dependencies: &'a mut PrecomputedHashSet<Atom>,
2624
2625    /// The filter with the local names of attributes there are selectors for
2626    /// within the selector list of :nth-child(... of <selector list>)
2627    /// selectors.
2628    nth_of_attribute_dependencies: &'a mut PrecomputedHashSet<LocalName>,
2629
2630    /// The filter with the local names of custom states in selectors for
2631    /// within the selector list of :nth-child(... of <selector list>)
2632    /// selectors.
2633    nth_of_custom_state_dependencies: &'a mut PrecomputedHashSet<AtomIdent>,
2634
2635    /// All the states selectors in the page reference.
2636    state_dependencies: &'a mut ElementState,
2637
2638    /// All the state selectors in the page reference within the selector list
2639    /// of :nth-child(... of <selector list>) selectors.
2640    nth_of_state_dependencies: &'a mut ElementState,
2641
2642    /// All the document states selectors in the page reference.
2643    document_state_dependencies: &'a mut DocumentState,
2644}
2645
2646fn component_needs_revalidation(c: &Component<SelectorImpl>) -> bool {
2647    match *c {
2648        Component::AttributeInNoNamespaceExists { .. }
2649        | Component::AttributeInNoNamespace { .. }
2650        | Component::AttributeOther(_)
2651        | Component::Empty
2652        | Component::Nth(_)
2653        | Component::NthOf(_)
2654        | Component::Has(_) => true,
2655        Component::NonTSPseudoClass(ref p) => p.needs_cache_revalidation(),
2656        _ => false,
2657    }
2658}
2659
2660impl<'a> StylistSelectorVisitor<'a> {
2661    fn visit_nested_selector(
2662        &mut self,
2663        in_selector_list_of: SelectorListKind,
2664        selector: &Selector<SelectorImpl>,
2665    ) {
2666        let old_passed_rightmost_selector = self.passed_rightmost_selector;
2667        let old_in_selector_list_of = self.in_selector_list_of;
2668
2669        // NOTE: Not resetting passed_rightmost_selector, intentionally.
2670        self.in_selector_list_of = in_selector_list_of;
2671        let _ret = selector.visit(self);
2672        debug_assert!(_ret, "We never return false");
2673
2674        self.passed_rightmost_selector = old_passed_rightmost_selector;
2675        self.in_selector_list_of = old_in_selector_list_of;
2676    }
2677}
2678
2679impl<'a> SelectorVisitor for StylistSelectorVisitor<'a> {
2680    type Impl = SelectorImpl;
2681
2682    fn visit_complex_selector(&mut self, combinator: Option<Combinator>) -> bool {
2683        *self.needs_revalidation =
2684            *self.needs_revalidation || combinator.is_some_and(|c| c.is_sibling());
2685
2686        // NOTE(emilio): this call happens before we visit any of the simple
2687        // selectors in the next ComplexSelector, so we can use this to skip
2688        // looking at them.
2689        self.passed_rightmost_selector = self.passed_rightmost_selector
2690            || !matches!(combinator, None | Some(Combinator::PseudoElement));
2691
2692        true
2693    }
2694
2695    fn visit_selector_list(
2696        &mut self,
2697        list_kind: SelectorListKind,
2698        list: &[Selector<Self::Impl>],
2699    ) -> bool {
2700        let in_selector_list_of = self.in_selector_list_of | list_kind;
2701        for selector in list {
2702            self.visit_nested_selector(in_selector_list_of, selector);
2703        }
2704        true
2705    }
2706
2707    fn visit_relative_selector_list(
2708        &mut self,
2709        list: &[selectors::parser::RelativeSelector<Self::Impl>],
2710    ) -> bool {
2711        let in_selector_list_of = self.in_selector_list_of | SelectorListKind::HAS;
2712        for selector in list {
2713            self.visit_nested_selector(in_selector_list_of, &selector.selector);
2714        }
2715        true
2716    }
2717
2718    fn visit_attribute_selector(
2719        &mut self,
2720        _ns: &NamespaceConstraint<&Namespace>,
2721        name: &LocalName,
2722        lower_name: &LocalName,
2723    ) -> bool {
2724        if self.in_selector_list_of.relevant_to_nth_of_dependencies() {
2725            self.nth_of_attribute_dependencies.insert(name.clone());
2726            if name != lower_name {
2727                self.nth_of_attribute_dependencies
2728                    .insert(lower_name.clone());
2729            }
2730        }
2731
2732        self.attribute_dependencies.insert(name.clone());
2733        if name != lower_name {
2734            self.attribute_dependencies.insert(lower_name.clone());
2735        }
2736
2737        true
2738    }
2739
2740    fn visit_simple_selector(&mut self, s: &Component<SelectorImpl>) -> bool {
2741        *self.needs_revalidation = *self.needs_revalidation || component_needs_revalidation(s);
2742
2743        match *s {
2744            Component::NonTSPseudoClass(NonTSPseudoClass::CustomState(ref name)) => {
2745                // CustomStateSet is special cased as it is a functional pseudo
2746                // class with unbounded inner values. This is different to
2747                // other psuedo class like :emtpy or :dir() which can be packed
2748                // into the ElementState bitflags. For CustomState, however,
2749                // the state name should be checked for presence in the selector.
2750                if self.in_selector_list_of.relevant_to_nth_of_dependencies() {
2751                    self.nth_of_custom_state_dependencies.insert(name.0.clone());
2752                }
2753            },
2754            Component::NonTSPseudoClass(ref p) => {
2755                self.state_dependencies.insert(p.state_flag());
2756                self.document_state_dependencies
2757                    .insert(p.document_state_flag());
2758
2759                if self.in_selector_list_of.relevant_to_nth_of_dependencies() {
2760                    self.nth_of_state_dependencies.insert(p.state_flag());
2761                }
2762
2763                if self.passed_rightmost_selector
2764                    && matches!(*p, NonTSPseudoClass::Link | NonTSPseudoClass::Visited)
2765                {
2766                    *self.non_link_visited_dependency = true;
2767                }
2768            },
2769            Component::ID(ref id) => {
2770                self.mapped_ids.insert(id.0.clone());
2771                if self.in_selector_list_of.relevant_to_nth_of_dependencies() {
2772                    self.nth_of_mapped_ids.insert(id.0.clone());
2773                }
2774            },
2775            Component::Class(ref class)
2776                if self.in_selector_list_of.relevant_to_nth_of_dependencies() =>
2777            {
2778                self.nth_of_class_dependencies.insert(class.0.clone());
2779            },
2780            _ => {},
2781        }
2782
2783        true
2784    }
2785}
2786
2787/// A set of rules for element and pseudo-elements.
2788#[derive(Clone, Debug, Default, MallocSizeOf)]
2789struct GenericElementAndPseudoRules<Map> {
2790    /// Rules from stylesheets at this `CascadeData`'s origin.
2791    element_map: Map,
2792
2793    /// Rules from stylesheets at this `CascadeData`'s origin that correspond
2794    /// to a given pseudo-element.
2795    ///
2796    /// FIXME(emilio): There are a bunch of wasted entries here in practice.
2797    /// Figure out a good way to do a `PerNonAnonBox` and `PerAnonBox` (for
2798    /// `precomputed_values_for_pseudo`) without duplicating a lot of code.
2799    pseudos_map: PerPseudoElementMap<Self>,
2800}
2801
2802impl<Map: Default + MallocSizeOf> GenericElementAndPseudoRules<Map> {
2803    #[inline(always)]
2804    fn for_insertion(&mut self, pseudo_elements: &[&PseudoElement]) -> &mut Map {
2805        let mut current = self;
2806        for &pseudo_element in pseudo_elements {
2807            debug_assert!(
2808                !pseudo_element.is_precomputed()
2809                    && !pseudo_element.is_unknown_webkit_pseudo_element(),
2810                "Precomputed pseudos should end up in precomputed_pseudo_element_decls, \
2811                 and unknown webkit pseudos should be discarded before getting here"
2812            );
2813
2814            current = current
2815                .pseudos_map
2816                .get_or_insert_with(pseudo_element, Default::default);
2817        }
2818
2819        &mut current.element_map
2820    }
2821
2822    #[inline]
2823    fn rules(&self, pseudo_elements: &[PseudoElement]) -> Option<&Map> {
2824        let mut current = self;
2825        for pseudo in pseudo_elements {
2826            current = current.pseudos_map.get(pseudo)?;
2827        }
2828        Some(&current.element_map)
2829    }
2830
2831    /// Measures heap usage.
2832    #[cfg(feature = "gecko")]
2833    fn add_size_of(&self, ops: &mut MallocSizeOfOps, sizes: &mut ServoStyleSetSizes) {
2834        sizes.mElementAndPseudosMaps += self.element_map.size_of(ops);
2835
2836        for elem in self.pseudos_map.iter() {
2837            sizes.mElementAndPseudosMaps += MallocSizeOf::size_of(elem, ops);
2838        }
2839    }
2840}
2841
2842type ElementAndPseudoRules = GenericElementAndPseudoRules<SelectorMap<Rule>>;
2843type PartMap = PrecomputedHashMap<Atom, SmallVec<[Rule; 1]>>;
2844type PartElementAndPseudoRules = GenericElementAndPseudoRules<PartMap>;
2845
2846impl ElementAndPseudoRules {
2847    // TODO(emilio): Should we retain storage of these?
2848    fn clear(&mut self) {
2849        self.element_map.clear();
2850        self.pseudos_map.clear();
2851    }
2852
2853    fn shrink_if_needed(&mut self) {
2854        self.element_map.shrink_if_needed();
2855        for pseudo in self.pseudos_map.iter_mut() {
2856            pseudo.shrink_if_needed();
2857        }
2858    }
2859}
2860
2861impl PartElementAndPseudoRules {
2862    // TODO(emilio): Should we retain storage of these?
2863    fn clear(&mut self) {
2864        self.element_map.clear();
2865        self.pseudos_map.clear();
2866    }
2867}
2868
2869/// The id of a given layer, a sequentially-increasing identifier.
2870#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, PartialOrd, Ord)]
2871pub struct LayerId(u16);
2872
2873impl LayerId {
2874    /// The id of the root layer.
2875    pub const fn root() -> Self {
2876        Self(0)
2877    }
2878}
2879
2880#[derive(Clone, Debug, MallocSizeOf)]
2881struct CascadeLayer {
2882    id: LayerId,
2883    order: LayerOrder,
2884    children: Vec<LayerId>,
2885}
2886
2887impl CascadeLayer {
2888    const fn root() -> Self {
2889        Self {
2890            id: LayerId::root(),
2891            order: LayerOrder::root(),
2892            children: vec![],
2893        }
2894    }
2895}
2896
2897/// The id of a given container condition, a sequentially-increasing identifier
2898/// for a given style set.
2899#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, PartialOrd, Ord)]
2900pub struct ContainerConditionId(u16);
2901
2902impl ContainerConditionId {
2903    /// A special id that represents no container rule.
2904    pub const fn none() -> Self {
2905        Self(0)
2906    }
2907}
2908
2909#[derive(Clone, Debug, MallocSizeOf)]
2910struct ContainerConditionReference {
2911    parent: ContainerConditionId,
2912    /// Contains the container conditions of a particular rule.
2913    ///
2914    /// This should only ever be empty for the root rule, which acts as a
2915    /// sentinel value.
2916    #[ignore_malloc_size_of = "Arc"]
2917    conditions: ArcSlice<ContainerCondition>,
2918}
2919
2920impl ContainerConditionReference {
2921    /// Creates an empty, root container condition reference.
2922    fn none() -> Self {
2923        Self {
2924            parent: ContainerConditionId::none(),
2925            conditions: ArcSlice::default(),
2926        }
2927    }
2928}
2929
2930/// The id of a given scope condition, a sequentially-increasing identifier
2931/// for a given style set.
2932#[derive(Clone, Copy, Debug, Eq, MallocSizeOf, PartialEq, PartialOrd, Ord)]
2933pub struct ScopeConditionId(u16);
2934
2935impl ScopeConditionId {
2936    /// Construct a new scope condition id.
2937    pub fn new(id: u16) -> Self {
2938        Self(id)
2939    }
2940
2941    /// A special id that represents no scope rule.
2942    pub const fn none() -> Self {
2943        Self(0)
2944    }
2945}
2946
2947/// Data required to process this scope condition.
2948#[derive(Clone, Debug, MallocSizeOf)]
2949pub struct ScopeConditionReference {
2950    /// The ID of outer scope condition, `none()` otherwise.
2951    parent: ScopeConditionId,
2952    /// Start and end bounds of the scope. None implies sentinel data (i.e. Not a scope condition).
2953    condition: Option<ScopeBoundsWithHashes>,
2954    /// Implicit scope root of this scope condition, computed unconditionally,
2955    /// even if the start bound may be Some.
2956    #[ignore_malloc_size_of = "Raw ptr behind the scenes"]
2957    implicit_scope_root: StylistImplicitScopeRoot,
2958    /// Is the condition trivial? See `ScopeBoundsWithHashes::is_trivial`.
2959    is_trivial: bool,
2960}
2961
2962impl ScopeConditionReference {
2963    /// Create a new scope condition.
2964    pub fn new(
2965        parent: ScopeConditionId,
2966        condition: Option<ScopeBoundsWithHashes>,
2967        implicit_scope_root: ImplicitScopeRoot,
2968        is_trivial: bool,
2969    ) -> Self {
2970        Self {
2971            parent,
2972            condition,
2973            implicit_scope_root: StylistImplicitScopeRoot::Normal(implicit_scope_root),
2974            is_trivial,
2975        }
2976    }
2977
2978    /// Create a sentinel scope condition.
2979    pub const fn none() -> Self {
2980        Self {
2981            parent: ScopeConditionId::none(),
2982            condition: None,
2983            implicit_scope_root: StylistImplicitScopeRoot::default_const(),
2984            is_trivial: true,
2985        }
2986    }
2987}
2988
2989/// All potential sscope root candidates.
2990pub struct ScopeRootCandidates {
2991    /// List of scope root candidates.
2992    pub candidates: Vec<ScopeRootCandidate>,
2993    /// Is the scope condition matching these candidates trivial? See `ScopeBoundsWithHashes::is_trivial`.
2994    pub is_trivial: bool,
2995}
2996
2997impl Default for ScopeRootCandidates {
2998    fn default() -> Self {
2999        Self {
3000            candidates: vec![],
3001            is_trivial: true,
3002        }
3003    }
3004}
3005
3006impl ScopeRootCandidates {
3007    fn empty(is_trivial: bool) -> Self {
3008        Self {
3009            candidates: vec![],
3010            is_trivial,
3011        }
3012    }
3013}
3014
3015/// Start and end bound of a scope, along with their selector hashes.
3016#[derive(Clone, Debug, MallocSizeOf)]
3017pub struct ScopeBoundWithHashes {
3018    // TODO(dshin): With replaced parent selectors, these may be unique...
3019    #[ignore_malloc_size_of = "Arc"]
3020    selectors: SelectorList<SelectorImpl>,
3021    hashes: SmallVec<[AncestorHashes; 1]>,
3022}
3023
3024impl ScopeBoundWithHashes {
3025    fn new(quirks_mode: QuirksMode, selectors: SelectorList<SelectorImpl>) -> Self {
3026        let mut hashes = SmallVec::with_capacity(selectors.len());
3027        for selector in selectors.slice() {
3028            hashes.push(AncestorHashes::new(selector, quirks_mode));
3029        }
3030        Self { selectors, hashes }
3031    }
3032
3033    fn new_no_hash(selectors: SelectorList<SelectorImpl>) -> Self {
3034        let hashes = selectors
3035            .slice()
3036            .iter()
3037            .map(|_| AncestorHashes {
3038                packed_hashes: [0, 0, 0],
3039            })
3040            .collect();
3041        Self { selectors, hashes }
3042    }
3043}
3044
3045/// Bounds for this scope, along with corresponding selector hashes.
3046#[derive(Clone, Debug, MallocSizeOf)]
3047pub struct ScopeBoundsWithHashes {
3048    /// Start of the scope bound. If None, implies implicit scope root.
3049    start: Option<ScopeBoundWithHashes>,
3050    /// Optional end of the scope bound.
3051    end: Option<ScopeBoundWithHashes>,
3052}
3053
3054impl ScopeBoundsWithHashes {
3055    /// Create a new scope bound, hashing selectors for fast rejection.
3056    fn new(
3057        quirks_mode: QuirksMode,
3058        start: Option<SelectorList<SelectorImpl>>,
3059        end: Option<SelectorList<SelectorImpl>>,
3060    ) -> Self {
3061        Self {
3062            start: start.map(|selectors| ScopeBoundWithHashes::new(quirks_mode, selectors)),
3063            end: end.map(|selectors| ScopeBoundWithHashes::new(quirks_mode, selectors)),
3064        }
3065    }
3066
3067    /// Create a new scope bound, but not hashing any selector.
3068    pub fn new_no_hash(
3069        start: Option<SelectorList<SelectorImpl>>,
3070        end: Option<SelectorList<SelectorImpl>>,
3071    ) -> Self {
3072        Self {
3073            start: start.map(ScopeBoundWithHashes::new_no_hash),
3074            end: end.map(ScopeBoundWithHashes::new_no_hash),
3075        }
3076    }
3077
3078    fn selectors_for(
3079        bound_with_hashes: Option<&ScopeBoundWithHashes>,
3080    ) -> impl Iterator<Item = &Selector<SelectorImpl>> {
3081        bound_with_hashes
3082            .map(|b| b.selectors.slice().iter())
3083            .into_iter()
3084            .flatten()
3085    }
3086
3087    fn start_selectors(&self) -> impl Iterator<Item = &Selector<SelectorImpl>> {
3088        Self::selectors_for(self.start.as_ref())
3089    }
3090
3091    fn end_selectors(&self) -> impl Iterator<Item = &Selector<SelectorImpl>> {
3092        Self::selectors_for(self.end.as_ref())
3093    }
3094
3095    fn is_trivial(&self) -> bool {
3096        fn scope_bound_is_trivial(bound: &Option<ScopeBoundWithHashes>, default: bool) -> bool {
3097            bound.as_ref().map_or(default, |bound| {
3098                scope_selector_list_is_trivial(&bound.selectors)
3099            })
3100        }
3101
3102        // Given an implicit scope, we are unable to tell if the cousins share the same implicit root.
3103        scope_bound_is_trivial(&self.start, false) && scope_bound_is_trivial(&self.end, true)
3104    }
3105}
3106
3107/// Find all scope conditions for a given condition ID, indexing into the given list of scope conditions.
3108pub fn scope_root_candidates<E>(
3109    scope_conditions: &[ScopeConditionReference],
3110    id: ScopeConditionId,
3111    element: &E,
3112    override_matches_shadow_host_for_part: bool,
3113    scope_subject_map: &ScopeSubjectMap,
3114    context: &mut MatchingContext<SelectorImpl>,
3115) -> ScopeRootCandidates
3116where
3117    E: TElement,
3118{
3119    let condition_ref = &scope_conditions[id.0 as usize];
3120    let bounds = match condition_ref.condition {
3121        None => return ScopeRootCandidates::default(),
3122        Some(ref c) => c,
3123    };
3124    if id.0 <= condition_ref.parent.0 {
3125        debug_assert!(false, "@scope bookkeeping is corrupt.");
3126        return ScopeRootCandidates::default();
3127    }
3128    // Make sure the parent scopes ara evaluated first. This runs a bit counter to normal
3129    // selector matching where rightmost selectors match first. However, this avoids having
3130    // to traverse through descendants (i.e. Avoids tree traversal vs linear traversal).
3131    let outer_result = scope_root_candidates(
3132        scope_conditions,
3133        condition_ref.parent,
3134        element,
3135        override_matches_shadow_host_for_part,
3136        scope_subject_map,
3137        context,
3138    );
3139
3140    let is_trivial = condition_ref.is_trivial && outer_result.is_trivial;
3141    let is_outermost_scope = condition_ref.parent == ScopeConditionId::none();
3142    if !is_outermost_scope && outer_result.candidates.is_empty() {
3143        return ScopeRootCandidates::empty(is_trivial);
3144    }
3145
3146    let (root_target, matches_shadow_host) = if let Some(start) = bounds.start.as_ref() {
3147        if let Some(filter) = context.bloom_filter {
3148            // Use the bloom filter here. If our ancestors do not have the right hashes,
3149            // there's no point in traversing up. Besides, the filter is built for this depth,
3150            // so the filter contains more data than it should, the further we go up the ancestor
3151            // chain. It wouldn't generate wrong results, but makes the traversal even more pointless.
3152            if !start
3153                .hashes
3154                .iter()
3155                .any(|entry| selector_may_match(entry, filter))
3156            {
3157                return ScopeRootCandidates::empty(is_trivial);
3158            }
3159        }
3160        (
3161            ScopeTarget::Selector(&start.selectors),
3162            scope_start_matches_shadow_host(&start.selectors),
3163        )
3164    } else {
3165        let implicit_root = condition_ref.implicit_scope_root;
3166        match implicit_root {
3167            StylistImplicitScopeRoot::Normal(r) => (
3168                ScopeTarget::Implicit(r.element(context.current_host)),
3169                r.matches_shadow_host(),
3170            ),
3171            StylistImplicitScopeRoot::Cached(index) => {
3172                let host = context
3173                    .current_host
3174                    .expect("Cached implicit scope for light DOM implicit scope");
3175                match E::implicit_scope_for_sheet_in_shadow_root(host, index) {
3176                    None => return ScopeRootCandidates::empty(is_trivial),
3177                    Some(root) => (
3178                        ScopeTarget::Implicit(root.element(context.current_host)),
3179                        root.matches_shadow_host(),
3180                    ),
3181                }
3182            },
3183        }
3184    };
3185    // For `::part`, we need to be able to reach the outer tree. Parts without the corresponding
3186    // `exportparts` attribute will be rejected at the selector matching time.
3187    let matches_shadow_host = override_matches_shadow_host_for_part || matches_shadow_host;
3188
3189    let potential_scope_roots = if is_outermost_scope {
3190        collect_scope_roots(
3191            *element,
3192            None,
3193            context,
3194            &root_target,
3195            matches_shadow_host,
3196            scope_subject_map,
3197        )
3198    } else {
3199        let mut result = vec![];
3200        for activation in outer_result.candidates {
3201            let mut this_result = collect_scope_roots(
3202                *element,
3203                Some(activation.root),
3204                context,
3205                &root_target,
3206                matches_shadow_host,
3207                scope_subject_map,
3208            );
3209            result.append(&mut this_result);
3210        }
3211        result
3212    };
3213
3214    if potential_scope_roots.is_empty() {
3215        return ScopeRootCandidates::empty(is_trivial);
3216    }
3217
3218    let candidates = if let Some(end) = bounds.end.as_ref() {
3219        let mut result = vec![];
3220        // If any scope-end selector matches, we're not in scope.
3221        for scope_root in potential_scope_roots {
3222            if end
3223                .selectors
3224                .slice()
3225                .iter()
3226                .zip(end.hashes.iter())
3227                .all(|(selector, hashes)| {
3228                    // Like checking for scope-start, use the bloom filter here.
3229                    if let Some(filter) = context.bloom_filter
3230                        && !selector_may_match(hashes, filter)
3231                    {
3232                        // Selector this hash belongs to won't cause us to be out of this scope.
3233                        return true;
3234                    }
3235
3236                    !element_is_outside_of_scope(
3237                        selector,
3238                        *element,
3239                        scope_root.root,
3240                        context,
3241                        matches_shadow_host,
3242                    )
3243                })
3244            {
3245                result.push(scope_root);
3246            }
3247        }
3248        result
3249    } else {
3250        potential_scope_roots
3251    };
3252
3253    ScopeRootCandidates {
3254        candidates,
3255        is_trivial,
3256    }
3257}
3258
3259/// Implicit scope root, which may or may not be cached (i.e. For shadow DOM author
3260/// styles that are cached and shared).
3261#[derive(Copy, Clone, Debug, MallocSizeOf)]
3262enum StylistImplicitScopeRoot {
3263    Normal(ImplicitScopeRoot),
3264    Cached(usize),
3265}
3266// Should be safe, only mutated through mutable methods in `Stylist`.
3267unsafe impl Sync for StylistImplicitScopeRoot {}
3268
3269impl StylistImplicitScopeRoot {
3270    const fn default_const() -> Self {
3271        // Use the "safest" fallback.
3272        Self::Normal(ImplicitScopeRoot::DocumentElement)
3273    }
3274}
3275
3276impl Default for StylistImplicitScopeRoot {
3277    fn default() -> Self {
3278        Self::default_const()
3279    }
3280}
3281
3282/// Cascade layer data.
3283#[derive(Debug, Clone, MallocSizeOf)]
3284struct CascadeLayers {
3285    /// A map from cascade layer name to layer order.
3286    layer_id_by_name: FxHashMap<LayerName, LayerId>,
3287
3288    /// The list of cascade layers, indexed by their layer id.
3289    layer_by_id: SmallVec<[CascadeLayer; 1]>,
3290}
3291
3292impl Default for CascadeLayers {
3293    fn default() -> Self {
3294        Self {
3295            layer_id_by_name: FxHashMap::default(),
3296            layer_by_id: smallvec::smallvec![CascadeLayer::root()],
3297        }
3298    }
3299}
3300
3301impl CascadeLayers {
3302    fn clear(&mut self) {
3303        self.layer_id_by_name.clear();
3304        self.layer_by_id.clear();
3305        self.layer_by_id.push(CascadeLayer::root());
3306    }
3307
3308    fn shrink_if_needed(&mut self) {
3309        self.layer_id_by_name.shrink_if_needed();
3310    }
3311
3312    fn has_layers(&self) -> bool {
3313        debug_assert_ne!(
3314            self.layer_by_id.len(),
3315            0,
3316            "Should have at least the root layer"
3317        );
3318        self.layer_by_id.len() > 1
3319    }
3320
3321    // NOTE(emilio): This is a bit trickier than it should to avoid having to clone() around layer
3322    // indices.
3323    fn compute_layer_order_for_subtree(
3324        parent: &mut CascadeLayer,
3325        remaining_layers: &mut [CascadeLayer],
3326        order: &mut LayerOrder,
3327    ) {
3328        for child in &parent.children {
3329            debug_assert!(
3330                parent.id < *child,
3331                "Children are always registered after parents"
3332            );
3333            let child_index = (child.0 - parent.id.0 - 1) as usize;
3334            let (first, remaining) = remaining_layers.split_at_mut(child_index + 1);
3335            let child = &mut first[child_index];
3336            Self::compute_layer_order_for_subtree(child, remaining, order);
3337        }
3338
3339        if parent.id != LayerId::root() {
3340            parent.order = *order;
3341            order.inc();
3342        }
3343    }
3344
3345    fn compute_layer_order(&mut self) {
3346        let (first, remaining) = self.layer_by_id.split_at_mut(1);
3347        let root = &mut first[0];
3348        let mut order = LayerOrder::first();
3349        Self::compute_layer_order_for_subtree(root, remaining, &mut order);
3350    }
3351}
3352
3353/// Data resulting from performing the CSS cascade that is specific to a given
3354/// origin.
3355///
3356/// FIXME(emilio): Consider renaming and splitting in `CascadeData` and
3357/// `InvalidationData`? That'd make `clear_cascade_data()` clearer.
3358#[derive(Debug, Clone, MallocSizeOf)]
3359pub struct CascadeData {
3360    /// The data coming from normal style rules that apply to elements at this
3361    /// cascade level.
3362    normal_rules: ElementAndPseudoRules,
3363
3364    /// The `:host` pseudo rules that are the rightmost selector (without
3365    /// accounting for pseudo-elements), or `:scope` rules that may match
3366    /// the featureless host.
3367    featureless_host_rules: Option<Box<ElementAndPseudoRules>>,
3368
3369    /// The data coming from ::slotted() pseudo-element rules.
3370    ///
3371    /// We need to store them separately because an element needs to match
3372    /// ::slotted() pseudo-element rules in different shadow roots.
3373    ///
3374    /// In particular, we need to go through all the style data in all the
3375    /// containing style scopes starting from the closest assigned slot.
3376    slotted_rules: Option<Box<ElementAndPseudoRules>>,
3377
3378    /// The data coming from ::part() pseudo-element rules.
3379    ///
3380    /// We need to store them separately because an element needs to match
3381    /// ::part() pseudo-element rules in different shadow roots.
3382    part_rules: Option<Box<PartElementAndPseudoRules>>,
3383
3384    /// The invalidation map for these rules.
3385    invalidation_map: InvalidationMap,
3386
3387    /// The relative selector equivalent of the invalidation map.
3388    relative_selector_invalidation_map: InvalidationMap,
3389
3390    additional_relative_selector_invalidation_map: AdditionalRelativeSelectorInvalidationMap,
3391
3392    /// The attribute local names that appear in attribute selectors.  Used
3393    /// to avoid taking element snapshots when an irrelevant attribute changes.
3394    /// (We don't bother storing the namespace, since namespaced attributes are
3395    /// rare.)
3396    attribute_dependencies: PrecomputedHashSet<LocalName>,
3397
3398    /// The classes that appear in the selector list of
3399    /// :nth-child(... of <selector list>). Used to avoid restyling siblings of
3400    /// an element when an irrelevant class changes.
3401    nth_of_class_dependencies: PrecomputedHashSet<Atom>,
3402
3403    /// The attributes that appear in the selector list of
3404    /// :nth-child(... of <selector list>). Used to avoid restyling siblings of
3405    /// an element when an irrelevant attribute changes.
3406    nth_of_attribute_dependencies: PrecomputedHashSet<LocalName>,
3407
3408    /// The custom states that appear in the selector list of
3409    /// :nth-child(... of <selector list>). Used to avoid restyling siblings of
3410    /// an element when an irrelevant custom state changes.
3411    nth_of_custom_state_dependencies: PrecomputedHashSet<AtomIdent>,
3412
3413    /// The element state bits that are relied on by selectors.  Like
3414    /// `attribute_dependencies`, this is used to avoid taking element snapshots
3415    /// when an irrelevant element state bit changes.
3416    state_dependencies: ElementState,
3417
3418    /// Whether some selector tests `:link` / `:visited` from a position that
3419    /// can change the match result of an element that isn't itself a link.
3420    non_link_visited_dependency: bool,
3421
3422    /// The element state bits that are relied on by selectors that appear in
3423    /// the selector list of :nth-child(... of <selector list>).
3424    nth_of_state_dependencies: ElementState,
3425
3426    /// The document state bits that are relied on by selectors.  This is used
3427    /// to tell whether we need to restyle the entire document when a document
3428    /// state bit changes.
3429    document_state_dependencies: DocumentState,
3430
3431    /// The ids that appear in the rightmost complex selector of selectors (and
3432    /// hence in our selector maps).  Used to determine when sharing styles is
3433    /// safe: we disallow style sharing for elements whose id matches this
3434    /// filter, and hence might be in one of our selector maps.
3435    mapped_ids: PrecomputedHashSet<Atom>,
3436
3437    /// The IDs that appear in the selector list of
3438    /// :nth-child(... of <selector list>). Used to avoid restyling siblings
3439    /// of an element when an irrelevant ID changes.
3440    nth_of_mapped_ids: PrecomputedHashSet<Atom>,
3441
3442    /// Selectors that require explicit cache revalidation (i.e. which depend
3443    /// on state that is not otherwise visible to the cache, like attributes or
3444    /// tree-structural state like child index and pseudos).
3445    #[ignore_malloc_size_of = "Arc"]
3446    selectors_for_cache_revalidation: SelectorMap<RevalidationSelectorAndHashes>,
3447
3448    /// A map with all the animations at this `CascadeData`'s origin, indexed
3449    /// by name.
3450    animations: LayerOrderedMap<KeyframesAnimation>,
3451
3452    /// A map with all the layer-ordered registrations from style at this `CascadeData`'s origin,
3453    /// indexed by name.
3454    #[ignore_malloc_size_of = "Arc"]
3455    custom_property_registrations: LayerOrderedMap<Arc<PropertyRegistration>>,
3456
3457    /// Custom media query registrations.
3458    custom_media: CustomMediaMap,
3459
3460    layers: CascadeLayers,
3461
3462    /// The list of container conditions, indexed by their id.
3463    container_conditions: SmallVec<[ContainerConditionReference; 1]>,
3464
3465    /// A map of attributes that are referenced by `attr()` functions in container queries.
3466    /// The attribute exists as a key if it is referenced inside a style container query.
3467    /// The enum value tells us whether or not the container query condition is named.
3468    container_attr_function_dependencies:
3469        PrecomputedHashMap<LocalName, ContainerAttributeDependencyKind>,
3470
3471    /// Indicates whether a container query contains `attr()` functions with attribute names
3472    /// that are not known at parse time (due to nested substitution functions). The enum
3473    /// value tells us whether or not the container query condition is named.
3474    container_unparsed_attr_function_dependency: ContainerAttributeDependencyKind,
3475
3476    /// The list of scope conditions, indexed by their id.
3477    scope_conditions: SmallVec<[ScopeConditionReference; 1]>,
3478
3479    /// Map of unique selectors on scope start selectors' subjects.
3480    scope_subject_map: ScopeSubjectMap,
3481
3482    /// Effective media query results cached from the last rebuild.
3483    effective_media_query_results: EffectiveMediaQueryResults,
3484
3485    /// Extra data, like different kinds of rules, etc.
3486    extra_data: ExtraStyleData,
3487
3488    /// A monotonically increasing counter to represent the order on which a
3489    /// style rule appears in a stylesheet, needed to sort them by source order.
3490    rules_source_order: u32,
3491
3492    /// The total number of selectors.
3493    num_selectors: usize,
3494
3495    /// The total number of declarations.
3496    num_declarations: usize,
3497}
3498
3499static IMPLICIT_SCOPE: LazyLock<SelectorList<SelectorImpl>> = LazyLock::new(|| {
3500    // Implicit scope, as per https://github.com/w3c/csswg-drafts/issues/10196
3501    // Also, `&` is `:where(:scope)`, as per https://github.com/w3c/csswg-drafts/issues/9740
3502    // ``:where(:scope)` effectively behaves the same as the implicit scope.
3503    let list = SelectorList::implicit_scope();
3504    list.mark_as_intentionally_leaked();
3505    list
3506});
3507
3508fn scope_start_matches_shadow_host(start: &SelectorList<SelectorImpl>) -> bool {
3509    // TODO(emilio): Should we carry a MatchesFeaturelessHost rather than a bool around?
3510    // Pre-existing behavior with multiple selectors matches this tho.
3511    start
3512        .slice()
3513        .iter()
3514        .any(|s| s.matches_featureless_host(true).may_match())
3515}
3516
3517/// Replace any occurrence of parent selector in the given selector with a implicit scope selector.
3518pub fn replace_parent_selector_with_implicit_scope(
3519    selectors: &SelectorList<SelectorImpl>,
3520) -> SelectorList<SelectorImpl> {
3521    selectors.replace_parent_selector(&IMPLICIT_SCOPE)
3522}
3523
3524impl CascadeData {
3525    /// Creates an empty `CascadeData`.
3526    pub fn new() -> Self {
3527        Self {
3528            normal_rules: ElementAndPseudoRules::default(),
3529            featureless_host_rules: None,
3530            slotted_rules: None,
3531            part_rules: None,
3532            invalidation_map: InvalidationMap::new(),
3533            relative_selector_invalidation_map: InvalidationMap::new(),
3534            additional_relative_selector_invalidation_map:
3535                AdditionalRelativeSelectorInvalidationMap::new(),
3536            nth_of_mapped_ids: PrecomputedHashSet::default(),
3537            nth_of_class_dependencies: PrecomputedHashSet::default(),
3538            nth_of_attribute_dependencies: PrecomputedHashSet::default(),
3539            nth_of_custom_state_dependencies: PrecomputedHashSet::default(),
3540            nth_of_state_dependencies: ElementState::empty(),
3541            attribute_dependencies: PrecomputedHashSet::default(),
3542            state_dependencies: ElementState::empty(),
3543            non_link_visited_dependency: false,
3544            document_state_dependencies: DocumentState::empty(),
3545            mapped_ids: PrecomputedHashSet::default(),
3546            selectors_for_cache_revalidation: SelectorMap::new(),
3547            animations: Default::default(),
3548            custom_property_registrations: Default::default(),
3549            custom_media: Default::default(),
3550            layers: CascadeLayers::default(),
3551            container_conditions: smallvec::smallvec![ContainerConditionReference::none()],
3552            container_attr_function_dependencies: PrecomputedHashMap::default(),
3553            container_unparsed_attr_function_dependency: ContainerAttributeDependencyKind::None,
3554            scope_conditions: smallvec::smallvec![ScopeConditionReference::none()],
3555            scope_subject_map: Default::default(),
3556            extra_data: ExtraStyleData::default(),
3557            effective_media_query_results: EffectiveMediaQueryResults::new(),
3558            rules_source_order: 0,
3559            num_selectors: 0,
3560            num_declarations: 0,
3561        }
3562    }
3563
3564    /// Rebuild the cascade data from a given SheetCollection, incrementally if possible.
3565    pub fn rebuild<'a, S>(
3566        &mut self,
3567        device: &Device,
3568        quirks_mode: QuirksMode,
3569        collection: SheetCollectionFlusher<S>,
3570        guard: &SharedRwLockReadGuard,
3571        difference: &mut CascadeDataDifference,
3572    ) -> Result<(), AllocErr>
3573    where
3574        S: StylesheetInDocument + PartialEq + 'static,
3575    {
3576        if !collection.dirty() {
3577            return Ok(());
3578        }
3579
3580        let validity = collection.data_validity();
3581
3582        let mut old_position_try_data = LayerOrderedMap::default();
3583        let mut old_layers = CascadeLayers::default();
3584        if validity != DataValidity::Valid {
3585            old_position_try_data = std::mem::take(&mut self.extra_data.position_try_rules);
3586            old_layers = std::mem::take(&mut self.layers);
3587            self.clear_cascade_data();
3588            if validity == DataValidity::FullyInvalid {
3589                self.clear_invalidation_data();
3590            }
3591        }
3592
3593        let mut result = Ok(());
3594
3595        let mut prev_sheet = None;
3596        collection.each(|index, stylesheet, rebuild_kind| {
3597            result = self.add_stylesheet(
3598                device,
3599                quirks_mode,
3600                stylesheet,
3601                index,
3602                guard,
3603                rebuild_kind,
3604                /* precomputed_pseudo_element_decls = */ None,
3605                if validity == DataValidity::Valid {
3606                    Some(difference)
3607                } else {
3608                    None
3609                },
3610                &mut prev_sheet,
3611            );
3612            result.is_ok()
3613        });
3614
3615        self.did_finish_rebuild();
3616
3617        // For DataValidity::Valid, we pass the difference down to `add_stylesheet` so that we
3618        // populate it with new data. Otherwise we need to diff with the old data.
3619        if validity != DataValidity::Valid {
3620            difference.update_layers(&old_layers, &self.layers);
3621            difference
3622                .update_position_try(&old_position_try_data, &self.extra_data.position_try_rules);
3623        }
3624
3625        result
3626    }
3627
3628    /// Returns the custom media query map.
3629    pub fn custom_media_map(&self) -> &CustomMediaMap {
3630        &self.custom_media
3631    }
3632
3633    /// Returns the invalidation map.
3634    pub fn invalidation_map(&self) -> &InvalidationMap {
3635        &self.invalidation_map
3636    }
3637
3638    /// Returns the relative selector invalidation map.
3639    pub fn relative_selector_invalidation_map(&self) -> &InvalidationMap {
3640        &self.relative_selector_invalidation_map
3641    }
3642
3643    /// Returns the relative selector invalidation map data.
3644    pub fn relative_invalidation_map_attributes(
3645        &self,
3646    ) -> &AdditionalRelativeSelectorInvalidationMap {
3647        &self.additional_relative_selector_invalidation_map
3648    }
3649
3650    /// Returns whether the given ElementState bit is relied upon by a selector
3651    /// of some rule.
3652    #[inline]
3653    pub fn has_state_dependency(&self, state: ElementState) -> bool {
3654        self.state_dependencies.intersects(state)
3655    }
3656
3657    /// Returns whether the given Custom State is relied upon by a selector
3658    /// of some rule in the selector list of :nth-child(... of <selector list>).
3659    #[inline]
3660    pub fn has_nth_of_custom_state_dependency(&self, state: &AtomIdent) -> bool {
3661        self.nth_of_custom_state_dependencies.contains(state)
3662    }
3663
3664    /// Returns whether the given ElementState bit is relied upon by a selector
3665    /// of some rule in the selector list of :nth-child(... of <selector list>).
3666    #[inline]
3667    pub fn has_nth_of_state_dependency(&self, state: ElementState) -> bool {
3668        self.nth_of_state_dependencies.intersects(state)
3669    }
3670
3671    /// Returns whether the given attribute might appear in an attribute selector
3672    /// of some rule or a container query with `attr()` functions.
3673    #[inline]
3674    pub fn might_have_attribute_dependency(&self, local_name: &LocalName) -> bool {
3675        // If a container query has an `attr()` function whose target attribute can't
3676        // be known at parse time (due to nested substitution functions), then _any_
3677        // attribute modification could require style invalidation.
3678        //
3679        // TODO(Bug 2087544) - Optimize invalidation for these `attr()` cases.
3680        self.container_unparsed_attr_function_dependency != ContainerAttributeDependencyKind::None
3681            || self.attribute_dependencies.contains(local_name)
3682    }
3683
3684    /// Whether matching an element that isn't itself a link can depend on
3685    /// whether a link is visited. Note this doesn't account for pseudo-element
3686    /// rules, whose originating element is the one `:visited` would match.
3687    pub fn has_non_link_visited_dependency(&self) -> bool {
3688        self.non_link_visited_dependency
3689    }
3690
3691    /// Returns whether the given attribute might appear in an attribute
3692    /// function inside a container rule. Unnamed container means that the
3693    /// value is used in an unamed style container rule. NamedContainer means
3694    /// that the value is used in a named container rule. None means the value
3695    /// is not used in a style container prelude at all.
3696    #[inline]
3697    pub fn might_have_attribute_dependency_in_container(
3698        &self,
3699        local_name: &LocalName,
3700    ) -> ContainerAttributeDependencyKind {
3701        self.container_attr_function_dependencies
3702            .get(local_name)
3703            .copied()
3704            .unwrap_or(ContainerAttributeDependencyKind::None)
3705            .max(self.container_unparsed_attr_function_dependency)
3706    }
3707
3708    /// Returns whether the given ID might appear in an ID selector in the
3709    /// selector list of :nth-child(... of <selector list>).
3710    #[inline]
3711    pub fn might_have_nth_of_id_dependency(&self, id: &Atom) -> bool {
3712        self.nth_of_mapped_ids.contains(id)
3713    }
3714
3715    /// Returns whether the given class might appear in a class selector in the
3716    /// selector list of :nth-child(... of <selector list>).
3717    #[inline]
3718    pub fn might_have_nth_of_class_dependency(&self, class: &Atom) -> bool {
3719        self.nth_of_class_dependencies.contains(class)
3720    }
3721
3722    /// Returns whether the given attribute might appear in an attribute
3723    /// selector in the selector list of :nth-child(... of <selector list>).
3724    #[inline]
3725    pub fn might_have_nth_of_attribute_dependency(&self, local_name: &LocalName) -> bool {
3726        self.nth_of_attribute_dependencies.contains(local_name)
3727    }
3728
3729    /// Returns the normal rule map for a given pseudo-element.
3730    #[inline]
3731    pub fn normal_rules(&self, pseudo_elements: &[PseudoElement]) -> Option<&SelectorMap<Rule>> {
3732        self.normal_rules.rules(pseudo_elements)
3733    }
3734
3735    /// Returns the featureless pseudo rule map for a given pseudo-element.
3736    #[inline]
3737    pub fn featureless_host_rules(
3738        &self,
3739        pseudo_elements: &[PseudoElement],
3740    ) -> Option<&SelectorMap<Rule>> {
3741        self.featureless_host_rules
3742            .as_ref()
3743            .and_then(|d| d.rules(pseudo_elements))
3744    }
3745
3746    /// Whether there's any featureless rule that could match in this scope.
3747    pub fn any_featureless_host_rules(&self) -> bool {
3748        self.featureless_host_rules.is_some()
3749    }
3750
3751    /// Returns the slotted rule map for a given pseudo-element.
3752    #[inline]
3753    pub fn slotted_rules(&self, pseudo_elements: &[PseudoElement]) -> Option<&SelectorMap<Rule>> {
3754        self.slotted_rules
3755            .as_ref()
3756            .and_then(|d| d.rules(pseudo_elements))
3757    }
3758
3759    /// Whether there's any ::slotted rule that could match in this scope.
3760    pub fn any_slotted_rule(&self) -> bool {
3761        self.slotted_rules.is_some()
3762    }
3763
3764    /// Returns the parts rule map for a given pseudo-element.
3765    #[inline]
3766    pub fn part_rules(&self, pseudo_elements: &[PseudoElement]) -> Option<&PartMap> {
3767        self.part_rules
3768            .as_ref()
3769            .and_then(|d| d.rules(pseudo_elements))
3770    }
3771
3772    /// Whether there's any ::part rule that could match in this scope.
3773    pub fn any_part_rule(&self) -> bool {
3774        self.part_rules.is_some()
3775    }
3776
3777    #[inline]
3778    fn layer_order_for(&self, id: LayerId) -> LayerOrder {
3779        self.layers.layer_by_id[id.0 as usize].order
3780    }
3781
3782    pub(crate) fn container_condition_matches<E>(
3783        &self,
3784        mut id: ContainerConditionId,
3785        stylist: &Stylist,
3786        element: E,
3787        context: &mut MatchingContext<E::Impl>,
3788    ) -> bool
3789    where
3790        E: TElement,
3791    {
3792        loop {
3793            let condition_ref = &self.container_conditions[id.0 as usize];
3794            if condition_ref.conditions.is_empty() {
3795                return true;
3796            }
3797            let matches = condition_ref.conditions.iter().any(|condition| {
3798                condition
3799                    .matches(
3800                        stylist,
3801                        element,
3802                        context.extra_data.originating_element_style,
3803                        &mut context.extra_data.cascade_input_flags,
3804                    )
3805                    .to_bool(/* unknown = */ false)
3806            });
3807            if !matches {
3808                return false;
3809            }
3810            id = condition_ref.parent;
3811        }
3812    }
3813
3814    pub(crate) fn find_scope_proximity_if_matching<E: TElement>(
3815        &self,
3816        rule: &Rule,
3817        element: E,
3818        context: &mut MatchingContext<E::Impl>,
3819    ) -> ScopeProximity {
3820        context
3821            .extra_data
3822            .cascade_input_flags
3823            .insert(ComputedValueFlags::CONSIDERED_NONTRIVIAL_SCOPED_STYLE);
3824
3825        // Whether the scope root matches a shadow host mostly olny depends on scope-intrinsic
3826        // parameters (i.e. bounds/implicit scope) - except for the use of `::parts`, where
3827        // matching crosses the shadow boundary.
3828        let result = scope_root_candidates(
3829            &self.scope_conditions,
3830            rule.scope_condition_id,
3831            &element,
3832            rule.selector.is_part(),
3833            &self.scope_subject_map,
3834            context,
3835        );
3836        for candidate in result.candidates {
3837            if context.nest_for_scope(Some(candidate.root), |context| {
3838                rule.matches_selector(element, context)
3839            }) {
3840                return candidate.proximity;
3841            }
3842        }
3843        ScopeProximity::infinity()
3844    }
3845
3846    fn did_finish_rebuild(&mut self) {
3847        self.shrink_maps_if_needed();
3848        self.compute_layer_order();
3849    }
3850
3851    fn shrink_maps_if_needed(&mut self) {
3852        self.normal_rules.shrink_if_needed();
3853        if let Some(ref mut host_rules) = self.featureless_host_rules {
3854            host_rules.shrink_if_needed();
3855        }
3856        if let Some(ref mut slotted_rules) = self.slotted_rules {
3857            slotted_rules.shrink_if_needed();
3858        }
3859        self.animations.shrink_if_needed();
3860        self.custom_property_registrations.shrink_if_needed();
3861        self.invalidation_map.shrink_if_needed();
3862        self.relative_selector_invalidation_map.shrink_if_needed();
3863        self.additional_relative_selector_invalidation_map
3864            .shrink_if_needed();
3865        self.attribute_dependencies.shrink_if_needed();
3866        self.nth_of_attribute_dependencies.shrink_if_needed();
3867        self.nth_of_custom_state_dependencies.shrink_if_needed();
3868        self.nth_of_class_dependencies.shrink_if_needed();
3869        self.nth_of_mapped_ids.shrink_if_needed();
3870        self.mapped_ids.shrink_if_needed();
3871        self.layers.shrink_if_needed();
3872        self.selectors_for_cache_revalidation.shrink_if_needed();
3873        self.scope_subject_map.shrink_if_needed();
3874    }
3875
3876    fn compute_layer_order(&mut self) {
3877        if !self.layers.has_layers() {
3878            return;
3879        }
3880        self.layers.compute_layer_order();
3881        self.extra_data.sort_by_layer(&self.layers.layer_by_id);
3882        self.animations
3883            .sort_with(&self.layers.layer_by_id, compare_keyframes_in_same_layer);
3884        self.custom_property_registrations
3885            .sort(&self.layers.layer_by_id);
3886    }
3887
3888    /// Collects all the applicable media query results into `results`.
3889    ///
3890    /// This duplicates part of the logic in `add_stylesheet`, which is
3891    /// a bit unfortunate.
3892    ///
3893    /// FIXME(emilio): With a bit of smartness in
3894    /// `media_feature_affected_matches`, we could convert
3895    /// `EffectiveMediaQueryResults` into a vector without too much effort.
3896    fn collect_applicable_media_query_results_into<S>(
3897        device: &Device,
3898        stylesheet: &S,
3899        guard: &SharedRwLockReadGuard,
3900        results: &mut Vec<MediaListKey>,
3901        contents_list: &mut StyleSheetContentList,
3902        custom_media_map: &mut CustomMediaMap,
3903    ) where
3904        S: StylesheetInDocument + 'static,
3905    {
3906        if !stylesheet.enabled() {
3907            return;
3908        }
3909        if !stylesheet.is_effective_for_device(device, custom_media_map, guard) {
3910            return;
3911        }
3912
3913        debug!(" + {:?}", stylesheet);
3914        let contents = stylesheet.contents(guard);
3915        results.push(contents.to_media_list_key());
3916
3917        // Safety: StyleSheetContents are reference-counted with Arc.
3918        contents_list.push(StylesheetContentsPtr(unsafe {
3919            Arc::from_raw_addrefed(contents)
3920        }));
3921
3922        let mut iter = stylesheet
3923            .contents(guard)
3924            .effective_rules(device, custom_media_map, guard);
3925        while let Some(rule) = iter.next() {
3926            match *rule {
3927                CssRule::CustomMedia(ref custom_media) => {
3928                    iter.custom_media()
3929                        .insert(custom_media.name.0.clone(), custom_media.condition.clone());
3930                },
3931                CssRule::Import(ref lock) => {
3932                    let import_rule = lock.read_with(guard);
3933                    debug!(" + {:?}", import_rule.stylesheet.media(guard));
3934                    results.push(import_rule.to_media_list_key());
3935                },
3936                CssRule::Media(ref media_rule) => {
3937                    debug!(" + {:?}", media_rule.media_queries.read_with(guard));
3938                    results.push(media_rule.to_media_list_key());
3939                },
3940                _ => {},
3941            }
3942        }
3943    }
3944
3945    fn add_styles(
3946        &mut self,
3947        selectors: &SelectorList<SelectorImpl>,
3948        declarations: &Arc<Locked<PropertyDeclarationBlock>>,
3949        ancestor_selectors: Option<&SelectorList<SelectorImpl>>,
3950        containing_rule_state: &ContainingRuleState,
3951        mut replaced_selectors: Option<&mut ReplacedSelectors>,
3952        guard: &SharedRwLockReadGuard,
3953        rebuild_kind: SheetRebuildKind,
3954        mut precomputed_pseudo_element_decls: Option<&mut PrecomputedPseudoElementDeclarations>,
3955        quirks_mode: QuirksMode,
3956        mut collected_scope_dependencies: Option<&mut Vec<Dependency>>,
3957    ) -> Result<(), AllocErr> {
3958        self.num_declarations += declarations.read_with(guard).len();
3959        for selector in selectors.slice() {
3960            self.num_selectors += 1;
3961
3962            let pseudo_elements = selector.pseudo_elements();
3963            let inner_pseudo_element = pseudo_elements.first();
3964            if let Some(pseudo) = inner_pseudo_element {
3965                if pseudo.is_precomputed() {
3966                    debug_assert!(selector.is_universal());
3967                    debug_assert!(ancestor_selectors.is_none());
3968                    debug_assert_eq!(containing_rule_state.layer_id, LayerId::root());
3969                    // Because we precompute pseudos, we cannot possibly calculate scope proximity.
3970                    debug_assert!(!containing_rule_state.scope_is_effective());
3971                    precomputed_pseudo_element_decls
3972                        .as_mut()
3973                        .expect("Expected precomputed declarations for the UA level")
3974                        .get_or_insert_with(pseudo, Vec::new)
3975                        .push(StyleSource::from_declarations(declarations.clone()));
3976                    continue;
3977                }
3978                if pseudo_elements
3979                    .iter()
3980                    .any(|p| p.is_unknown_webkit_pseudo_element())
3981                {
3982                    continue;
3983                }
3984            }
3985
3986            debug_assert!(
3987                !pseudo_elements
3988                    .iter()
3989                    .any(|p| p.is_precomputed() || p.is_unknown_webkit_pseudo_element())
3990            );
3991
3992            let selector = match ancestor_selectors {
3993                Some(s) => selector.replace_parent_selector(s),
3994                None => selector.clone(),
3995            };
3996
3997            let hashes = AncestorHashes::new(&selector, quirks_mode);
3998
3999            let rule = Rule::new(
4000                selector,
4001                hashes,
4002                StyleSource::from_declarations(declarations.clone()),
4003                self.rules_source_order,
4004                containing_rule_state.layer_id,
4005                containing_rule_state.container_condition_id,
4006                containing_rule_state.cascade_flags(),
4007                containing_rule_state.containing_scope_rule_state.id,
4008            );
4009
4010            if let Some(ref mut replaced_selectors) = replaced_selectors {
4011                replaced_selectors.push(rule.selector.clone())
4012            }
4013
4014            if rebuild_kind.should_rebuild_invalidation() {
4015                let mut scope_dependencies = note_selector_for_invalidation(
4016                    &rule.selector,
4017                    quirks_mode,
4018                    &mut self.invalidation_map,
4019                    &mut self.relative_selector_invalidation_map,
4020                    &mut self.additional_relative_selector_invalidation_map,
4021                    None,
4022                    None,
4023                )?;
4024                let mut needs_revalidation = false;
4025                let mut visitor = StylistSelectorVisitor {
4026                    passed_rightmost_selector: false,
4027                    needs_revalidation: &mut needs_revalidation,
4028                    non_link_visited_dependency: &mut self.non_link_visited_dependency,
4029                    in_selector_list_of: SelectorListKind::default(),
4030                    mapped_ids: &mut self.mapped_ids,
4031                    nth_of_mapped_ids: &mut self.nth_of_mapped_ids,
4032                    attribute_dependencies: &mut self.attribute_dependencies,
4033                    nth_of_class_dependencies: &mut self.nth_of_class_dependencies,
4034                    nth_of_attribute_dependencies: &mut self.nth_of_attribute_dependencies,
4035                    nth_of_custom_state_dependencies: &mut self.nth_of_custom_state_dependencies,
4036                    state_dependencies: &mut self.state_dependencies,
4037                    nth_of_state_dependencies: &mut self.nth_of_state_dependencies,
4038                    document_state_dependencies: &mut self.document_state_dependencies,
4039                };
4040                rule.selector.visit(&mut visitor);
4041
4042                if needs_revalidation {
4043                    self.selectors_for_cache_revalidation.insert(
4044                        RevalidationSelectorAndHashes::new(
4045                            rule.selector.clone(),
4046                            rule.hashes.clone(),
4047                        ),
4048                        quirks_mode,
4049                    )?;
4050                }
4051
4052                if let (Some(inner_scope_deps), Some(scope_deps)) = (
4053                    scope_dependencies.as_mut(),
4054                    collected_scope_dependencies.as_mut(),
4055                ) {
4056                    scope_deps.append(inner_scope_deps)
4057                }
4058            }
4059
4060            // Part is special, since given it doesn't have any
4061            // selectors inside, it's not worth using a whole
4062            // SelectorMap for it.
4063            if let Some(parts) = rule.selector.parts() {
4064                // ::part() has all semantics, so we just need to
4065                // put any of them in the selector map.
4066                //
4067                // We choose the last one quite arbitrarily,
4068                // expecting it's slightly more likely to be more
4069                // specific.
4070                let map = self
4071                    .part_rules
4072                    .get_or_insert_with(Box::default)
4073                    .for_insertion(&pseudo_elements);
4074                map.try_reserve(1)?;
4075                let vec = map.entry_ref(&parts.last().unwrap().0).or_default();
4076                vec.try_reserve(1)?;
4077                vec.push(rule);
4078            } else {
4079                let scope_matches_shadow_host = containing_rule_state
4080                    .containing_scope_rule_state
4081                    .matches_shadow_host
4082                    == ScopeMatchesShadowHost::Yes;
4083                let matches_featureless_host_only = match rule
4084                    .selector
4085                    .matches_featureless_host(scope_matches_shadow_host)
4086                {
4087                    MatchesFeaturelessHost::Only => true,
4088                    MatchesFeaturelessHost::Yes => {
4089                        // We need to insert this in featureless_host_rules but also normal_rules.
4090                        self.featureless_host_rules
4091                            .get_or_insert_with(Box::default)
4092                            .for_insertion(&pseudo_elements)
4093                            .insert(rule.clone(), quirks_mode)?;
4094                        false
4095                    },
4096                    MatchesFeaturelessHost::Never => false,
4097                };
4098
4099                // NOTE(emilio): It's fine to look at :host and then at
4100                // ::slotted(..), since :host::slotted(..) could never
4101                // possibly match, as <slot> is not a valid shadow host.
4102                // :scope may match featureless shadow host if the scope
4103                // root is the shadow root.
4104                // See https://github.com/w3c/csswg-drafts/issues/9025
4105                let rules = if matches_featureless_host_only {
4106                    self.featureless_host_rules.get_or_insert_with(Box::default)
4107                } else if rule.selector.is_slotted() {
4108                    self.slotted_rules.get_or_insert_with(Box::default)
4109                } else {
4110                    &mut self.normal_rules
4111                }
4112                .for_insertion(&pseudo_elements);
4113                rules.insert(rule, quirks_mode)?;
4114            }
4115        }
4116        self.rules_source_order += 1;
4117        Ok(())
4118    }
4119
4120    fn add_rule_list<S>(
4121        &mut self,
4122        rules: std::slice::Iter<CssRule>,
4123        device: &Device,
4124        quirks_mode: QuirksMode,
4125        stylesheet: &S,
4126        sheet_index: usize,
4127        guard: &SharedRwLockReadGuard,
4128        rebuild_kind: SheetRebuildKind,
4129        containing_rule_state: &mut ContainingRuleState,
4130        mut precomputed_pseudo_element_decls: Option<&mut PrecomputedPseudoElementDeclarations>,
4131        mut difference: Option<&mut CascadeDataDifference>,
4132    ) -> Result<(), AllocErr>
4133    where
4134        S: StylesheetInDocument + 'static,
4135    {
4136        for rule in rules {
4137            // Handle leaf rules first, as those are by far the most common
4138            // ones, and are always effective, so we can skip some checks.
4139            let mut handled = true;
4140            let mut list_for_nested_rules = None;
4141            match *rule {
4142                CssRule::Style(ref locked) => {
4143                    let style_rule = locked.read_with(guard);
4144                    let has_nested_rules = style_rule.rules.is_some();
4145                    let mut replaced_selectors = ReplacedSelectors::new();
4146                    let ancestor_selectors = containing_rule_state.ancestor_selector_lists.last();
4147                    let collect_replaced_selectors =
4148                        has_nested_rules && ancestor_selectors.is_some();
4149                    let mut inner_dependencies: Option<Vec<Dependency>> =
4150                        containing_rule_state.scope_is_effective().then(Vec::new);
4151                    self.add_styles(
4152                        &style_rule.selectors,
4153                        &style_rule.block,
4154                        ancestor_selectors,
4155                        containing_rule_state,
4156                        if collect_replaced_selectors {
4157                            Some(&mut replaced_selectors)
4158                        } else {
4159                            None
4160                        },
4161                        guard,
4162                        rebuild_kind,
4163                        precomputed_pseudo_element_decls.as_deref_mut(),
4164                        quirks_mode,
4165                        inner_dependencies.as_mut(),
4166                    )?;
4167                    if let Some(mut scope_dependencies) = inner_dependencies {
4168                        containing_rule_state
4169                            .containing_scope_rule_state
4170                            .inner_dependencies
4171                            .append(&mut scope_dependencies);
4172                    }
4173                    if has_nested_rules {
4174                        handled = false;
4175                        list_for_nested_rules = Some(if collect_replaced_selectors {
4176                            SelectorList::from_iter(replaced_selectors.drain(..))
4177                        } else {
4178                            style_rule.selectors.clone()
4179                        });
4180                    }
4181                },
4182                CssRule::NestedDeclarations(ref rule) => {
4183                    if let Some(ancestor_selectors) =
4184                        containing_rule_state.ancestor_selector_lists.last()
4185                    {
4186                        let decls = &rule.read_with(guard).block;
4187                        let selectors = match containing_rule_state.nested_declarations_context {
4188                            NestedDeclarationsContext::Style => ancestor_selectors,
4189                            NestedDeclarationsContext::Scope => &*IMPLICIT_SCOPE,
4190                        };
4191                        let mut inner_dependencies: Option<Vec<Dependency>> =
4192                            containing_rule_state.scope_is_effective().then(Vec::new);
4193                        self.add_styles(
4194                            selectors,
4195                            decls,
4196                            /* ancestor_selectors = */ None,
4197                            containing_rule_state,
4198                            /* replaced_selectors = */ None,
4199                            guard,
4200                            // We don't need to rebuild invalidation data, since our ancestor style
4201                            // rule would've done this.
4202                            SheetRebuildKind::CascadeOnly,
4203                            precomputed_pseudo_element_decls.as_deref_mut(),
4204                            quirks_mode,
4205                            inner_dependencies.as_mut(),
4206                        )?;
4207                        if let Some(mut scope_dependencies) = inner_dependencies {
4208                            containing_rule_state
4209                                .containing_scope_rule_state
4210                                .inner_dependencies
4211                                .append(&mut scope_dependencies);
4212                        }
4213                    }
4214                },
4215                CssRule::Keyframes(ref keyframes_rule) => {
4216                    debug!("Found valid keyframes rule: {:?}", *keyframes_rule);
4217                    let keyframes_rule = keyframes_rule.read_with(guard);
4218                    let name = keyframes_rule.name.as_atom();
4219                    let animation = KeyframesAnimation::from_keyframes(
4220                        &keyframes_rule.keyframes,
4221                        keyframes_rule.vendor_prefix.clone(),
4222                        guard,
4223                    );
4224                    self.animations.try_insert_with(
4225                        name,
4226                        animation,
4227                        containing_rule_state.layer_id,
4228                        compare_keyframes_in_same_layer,
4229                    )?;
4230                },
4231                CssRule::Property(ref registration) => {
4232                    self.custom_property_registrations.try_insert(
4233                        &registration.name.0,
4234                        Arc::clone(registration),
4235                        containing_rule_state.layer_id,
4236                    )?;
4237                },
4238                CssRule::FontFace(ref rule) => {
4239                    // NOTE(emilio): We don't care about container_condition_id
4240                    // because:
4241                    //
4242                    //     Global, name-defining at-rules such as @keyframes or
4243                    //     @font-face or @layer that are defined inside container
4244                    //     queries are not constrained by the container query
4245                    //     conditions.
4246                    //
4247                    // https://drafts.csswg.org/css-contain-3/#container-rule
4248                    // (Same elsewhere)
4249                    self.extra_data
4250                        .add_font_face(rule, containing_rule_state.layer_id);
4251                },
4252                CssRule::FontFeatureValues(ref rule) => {
4253                    self.extra_data
4254                        .add_font_feature_values(rule, containing_rule_state.layer_id);
4255                },
4256                CssRule::FontPaletteValues(ref rule) => {
4257                    self.extra_data
4258                        .add_font_palette_values(rule, containing_rule_state.layer_id);
4259                },
4260                CssRule::CounterStyle(ref rule) => {
4261                    self.extra_data.add_counter_style(
4262                        guard,
4263                        rule,
4264                        containing_rule_state.layer_id,
4265                    )?;
4266                },
4267                CssRule::PositionTry(ref rule) => {
4268                    let name = rule.read_with(guard).name.0.clone();
4269                    if let Some(ref mut difference) = difference {
4270                        difference.changed_position_try_names.insert(name.clone());
4271                    }
4272                    self.extra_data.add_position_try(
4273                        name,
4274                        rule.clone(),
4275                        containing_rule_state.layer_id,
4276                    )?;
4277                },
4278                CssRule::Page(ref rule) => {
4279                    self.extra_data
4280                        .add_page(guard, rule, containing_rule_state.layer_id)?;
4281                    handled = false;
4282                },
4283                CssRule::ViewTransition(ref rule) => {
4284                    self.extra_data
4285                        .add_view_transition(rule, containing_rule_state.layer_id);
4286                },
4287                _ => {
4288                    handled = false;
4289                },
4290            }
4291
4292            if handled {
4293                // Assert that there are no children, and that the rule is
4294                // effective.
4295                if cfg!(debug_assertions) {
4296                    let mut effective = false;
4297                    let children = EffectiveRulesIterator::<&CustomMediaMap>::children(
4298                        rule,
4299                        device,
4300                        quirks_mode,
4301                        &self.custom_media,
4302                        guard,
4303                        &mut effective,
4304                    );
4305                    debug_assert!(children.is_empty());
4306                    debug_assert!(effective);
4307                }
4308                continue;
4309            }
4310
4311            let mut effective = false;
4312            let children = EffectiveRulesIterator::<&CustomMediaMap>::children(
4313                rule,
4314                device,
4315                quirks_mode,
4316                &self.custom_media,
4317                guard,
4318                &mut effective,
4319            );
4320            if !effective {
4321                continue;
4322            }
4323
4324            fn maybe_register_layer(data: &mut CascadeData, layer: &LayerName) -> LayerId {
4325                // TODO: Measure what's more common / expensive, if
4326                // layer.clone() or the double hash lookup in the insert
4327                // case.
4328                if let Some(id) = data.layers.layer_id_by_name.get(layer) {
4329                    return *id;
4330                }
4331                let id = LayerId(data.layers.layer_by_id.len() as u16);
4332
4333                let parent_layer_id = if layer.layer_names().len() > 1 {
4334                    let mut parent = layer.clone();
4335                    parent.0.pop();
4336
4337                    *data
4338                        .layers
4339                        .layer_id_by_name
4340                        .get(&parent)
4341                        .expect("Parent layers should be registered before child layers")
4342                } else {
4343                    LayerId::root()
4344                };
4345
4346                data.layers.layer_by_id[parent_layer_id.0 as usize]
4347                    .children
4348                    .push(id);
4349                data.layers.layer_by_id.push(CascadeLayer {
4350                    id,
4351                    // NOTE(emilio): Order is evaluated after rebuild in compute_layer_order.
4352                    order: LayerOrder::first(),
4353                    children: vec![],
4354                });
4355                data.layers.layer_id_by_name.insert(layer.clone(), id);
4356
4357                id
4358            }
4359
4360            fn maybe_register_layers(
4361                data: &mut CascadeData,
4362                name: Option<&LayerName>,
4363                containing_rule_state: &mut ContainingRuleState,
4364            ) {
4365                let anon_name;
4366                let name = match name {
4367                    Some(name) => name,
4368                    None => {
4369                        anon_name = LayerName::new_anonymous();
4370                        &anon_name
4371                    },
4372                };
4373                for name in name.layer_names() {
4374                    containing_rule_state.layer_name.0.push(name.clone());
4375                    containing_rule_state.layer_id =
4376                        maybe_register_layer(data, &containing_rule_state.layer_name);
4377                }
4378                debug_assert_ne!(containing_rule_state.layer_id, LayerId::root());
4379            }
4380
4381            let saved_containing_rule_state = containing_rule_state.save();
4382            match *rule {
4383                CssRule::Import(ref lock) => {
4384                    let import_rule = lock.read_with(guard);
4385                    if rebuild_kind.should_rebuild_invalidation() {
4386                        self.effective_media_query_results
4387                            .saw_effective(import_rule);
4388                    }
4389                    match import_rule.layer {
4390                        ImportLayer::Named(ref name) => {
4391                            maybe_register_layers(self, Some(name), containing_rule_state)
4392                        },
4393                        ImportLayer::Anonymous => {
4394                            maybe_register_layers(self, None, containing_rule_state)
4395                        },
4396                        ImportLayer::None => {},
4397                    }
4398                },
4399                CssRule::Media(ref media_rule) => {
4400                    if rebuild_kind.should_rebuild_invalidation() {
4401                        self.effective_media_query_results
4402                            .saw_effective(&**media_rule);
4403                    }
4404                },
4405                CssRule::LayerBlock(ref rule) => {
4406                    maybe_register_layers(self, rule.name.as_ref(), containing_rule_state);
4407                },
4408                CssRule::CustomMedia(ref custom_media) => {
4409                    self.custom_media
4410                        .insert(custom_media.name.0.clone(), custom_media.condition.clone());
4411                },
4412                CssRule::LayerStatement(ref rule) => {
4413                    for name in &*rule.names {
4414                        maybe_register_layers(self, Some(name), containing_rule_state);
4415                        // Register each layer individually.
4416                        containing_rule_state.restore(&saved_containing_rule_state);
4417                    }
4418                },
4419                CssRule::Style(..) => {
4420                    containing_rule_state.nested_declarations_context =
4421                        NestedDeclarationsContext::Style;
4422                    if let Some(s) = list_for_nested_rules {
4423                        containing_rule_state.ancestor_selector_lists.push(s);
4424                    }
4425                },
4426                CssRule::Container(ref rule) => {
4427                    let id = ContainerConditionId(self.container_conditions.len() as u16);
4428                    let condition = ContainerConditionReference {
4429                        parent: containing_rule_state.container_condition_id,
4430                        conditions: rule.conditions.0.clone(),
4431                    };
4432                    self.container_conditions.push(condition);
4433                    containing_rule_state.container_condition_id = id;
4434
4435                    if rebuild_kind.should_rebuild_invalidation() {
4436                        for condition in rule.conditions.0.iter() {
4437                            let unparsed_dependency_kind = condition
4438                                .insert_attribute_references_in_dependency_map(
4439                                    &mut self.container_attr_function_dependencies,
4440                                    &mut self.attribute_dependencies,
4441                                );
4442                            self.container_unparsed_attr_function_dependency = self
4443                                .container_unparsed_attr_function_dependency
4444                                .max(unparsed_dependency_kind);
4445                        }
4446                    }
4447                },
4448                CssRule::StartingStyle(..) => {
4449                    containing_rule_state
4450                        .cascade_flags
4451                        .insert(RuleCascadeFlags::STARTING_STYLE);
4452                },
4453                CssRule::AppearanceBase(..) => {
4454                    containing_rule_state
4455                        .cascade_flags
4456                        .insert(RuleCascadeFlags::APPEARANCE_BASE);
4457                },
4458                CssRule::Scope(ref rule) if self.scope_conditions.len() <= u16::MAX.into() => {
4459                    containing_rule_state.nested_declarations_context =
4460                        NestedDeclarationsContext::Scope;
4461                    let id = ScopeConditionId(self.scope_conditions.len() as u16);
4462                    let mut matches_shadow_host = false;
4463                    let implicit_scope_root = if let Some(start) = rule.bounds.start.as_ref() {
4464                        matches_shadow_host = scope_start_matches_shadow_host(start);
4465                        // Would be unused, but use the default as fallback.
4466                        StylistImplicitScopeRoot::default()
4467                    } else {
4468                        containing_rule_state.saw_implicit_scope_root = true;
4469                        // (Re)Moving stylesheets trigger a complete flush, so saving the implicit
4470                        // root here should be safe.
4471                        if let Some(root) = stylesheet.implicit_scope_root() {
4472                            matches_shadow_host = root.matches_shadow_host();
4473                            match root {
4474                                ImplicitScopeRoot::InLightTree(_)
4475                                | ImplicitScopeRoot::Constructed
4476                                | ImplicitScopeRoot::DocumentElement => {
4477                                    StylistImplicitScopeRoot::Normal(root)
4478                                },
4479                                ImplicitScopeRoot::ShadowHost(_)
4480                                | ImplicitScopeRoot::InShadowTree(_) => {
4481                                    // Style data can be shared between shadow trees, so we must
4482                                    // query the implicit root for that specific tree.
4483                                    // Shared stylesheet means shared sheet indices, so we can
4484                                    // use that to locate the implicit root.
4485                                    // Technically, this can also be applied to the light tree,
4486                                    // but that requires also knowing about what cascade level we're at.
4487                                    StylistImplicitScopeRoot::Cached(sheet_index)
4488                                },
4489                            }
4490                        } else {
4491                            // Could not find implicit scope root, but use the default as fallback.
4492                            StylistImplicitScopeRoot::default()
4493                        }
4494                    };
4495
4496                    let replaced =
4497                        {
4498                            let start = rule.bounds.start.as_ref().map(|selector| {
4499                                match containing_rule_state.ancestor_selector_lists.last() {
4500                                    Some(s) => selector.replace_parent_selector(s),
4501                                    None => selector.clone(),
4502                                }
4503                            });
4504                            let implicit_scope_selector = &*IMPLICIT_SCOPE;
4505                            let end = rule.bounds.end.as_ref().map(|selector| {
4506                                selector.replace_parent_selector(implicit_scope_selector)
4507                            });
4508                            containing_rule_state
4509                                .ancestor_selector_lists
4510                                .push(implicit_scope_selector.clone());
4511                            ScopeBoundsWithHashes::new(quirks_mode, start, end)
4512                        };
4513
4514                    if let Some(selectors) = replaced.start.as_ref() {
4515                        self.scope_subject_map
4516                            .add_bound_start(&selectors.selectors, quirks_mode);
4517                    }
4518
4519                    let is_trivial = replaced.is_trivial();
4520                    self.scope_conditions.push(ScopeConditionReference {
4521                        parent: containing_rule_state.containing_scope_rule_state.id,
4522                        condition: Some(replaced),
4523                        implicit_scope_root,
4524                        is_trivial,
4525                    });
4526
4527                    containing_rule_state
4528                        .containing_scope_rule_state
4529                        .matches_shadow_host
4530                        .nest_for_scope(matches_shadow_host);
4531                    containing_rule_state.containing_scope_rule_state.id = id;
4532                    containing_rule_state
4533                        .containing_scope_rule_state
4534                        .inner_dependencies
4535                        .reserve(children.iter().len());
4536                },
4537                // We don't care about any other rule.
4538                _ => {},
4539            }
4540
4541            if !children.is_empty() {
4542                self.add_rule_list(
4543                    children.iter(),
4544                    device,
4545                    quirks_mode,
4546                    stylesheet,
4547                    sheet_index,
4548                    guard,
4549                    rebuild_kind,
4550                    containing_rule_state,
4551                    precomputed_pseudo_element_decls.as_deref_mut(),
4552                    difference.as_deref_mut(),
4553                )?;
4554            }
4555
4556            if let Some(scope_restore_data) =
4557                containing_rule_state.restore(&saved_containing_rule_state)
4558            {
4559                let (cur_scope_inner_dependencies, scope_idx) = scope_restore_data;
4560                let cur_scope = &self.scope_conditions[scope_idx.0 as usize];
4561                if let Some(cond) = cur_scope.condition.as_ref() {
4562                    let mut _unused = false;
4563                    let visitor = StylistSelectorVisitor {
4564                        passed_rightmost_selector: true,
4565                        needs_revalidation: &mut _unused,
4566                        non_link_visited_dependency: &mut self.non_link_visited_dependency,
4567                        in_selector_list_of: SelectorListKind::default(),
4568                        mapped_ids: &mut self.mapped_ids,
4569                        nth_of_mapped_ids: &mut self.nth_of_mapped_ids,
4570                        attribute_dependencies: &mut self.attribute_dependencies,
4571                        nth_of_class_dependencies: &mut self.nth_of_class_dependencies,
4572                        nth_of_attribute_dependencies: &mut self.nth_of_attribute_dependencies,
4573                        nth_of_custom_state_dependencies: &mut self
4574                            .nth_of_custom_state_dependencies,
4575                        state_dependencies: &mut self.state_dependencies,
4576                        nth_of_state_dependencies: &mut self.nth_of_state_dependencies,
4577                        document_state_dependencies: &mut self.document_state_dependencies,
4578                    };
4579
4580                    let dependency_vector = build_scope_dependencies(
4581                        quirks_mode,
4582                        cur_scope_inner_dependencies,
4583                        visitor,
4584                        cond,
4585                        &mut self.invalidation_map,
4586                        &mut self.relative_selector_invalidation_map,
4587                        &mut self.additional_relative_selector_invalidation_map,
4588                    )?;
4589
4590                    containing_rule_state
4591                        .containing_scope_rule_state
4592                        .inner_dependencies
4593                        .extend(dependency_vector);
4594                }
4595            }
4596        }
4597
4598        Ok(())
4599    }
4600
4601    // Returns Err(..) to signify OOM
4602    fn add_stylesheet<S>(
4603        &mut self,
4604        device: &Device,
4605        quirks_mode: QuirksMode,
4606        stylesheet: &S,
4607        sheet_index: usize,
4608        guard: &SharedRwLockReadGuard,
4609        rebuild_kind: SheetRebuildKind,
4610        precomputed_pseudo_element_decls: Option<&mut PrecomputedPseudoElementDeclarations>,
4611        difference: Option<&mut CascadeDataDifference>,
4612        prev_sheet: &mut Option<*const StylesheetContents>,
4613    ) -> Result<(), AllocErr>
4614    where
4615        S: StylesheetInDocument + 'static,
4616    {
4617        if !stylesheet.enabled() {
4618            return Ok(());
4619        }
4620
4621        if !stylesheet.is_effective_for_device(device, &self.custom_media, guard) {
4622            return Ok(());
4623        }
4624
4625        let contents = stylesheet.contents(guard);
4626        if rebuild_kind.should_rebuild_invalidation() {
4627            self.effective_media_query_results.saw_effective(contents);
4628        }
4629
4630        // Identical sheets share their parsed contents, so one that repeats its
4631        // predecessor adds the same rules to the selector maps a second time.
4632        if prev_sheet.is_some_and(|p| std::ptr::eq(p, contents)) {
4633            return Ok(());
4634        }
4635
4636        let mut state = ContainingRuleState::default();
4637        self.add_rule_list(
4638            contents.rules(guard).iter(),
4639            device,
4640            quirks_mode,
4641            stylesheet,
4642            sheet_index,
4643            guard,
4644            rebuild_kind,
4645            &mut state,
4646            precomputed_pseudo_element_decls,
4647            difference,
4648        )?;
4649
4650        // Only a sheet whose rules don't depend on which sheet they came from can
4651        // stand in for a later copy; an implicitly scoped rule's root does.
4652        *prev_sheet = (!state.saw_implicit_scope_root).then_some(std::ptr::from_ref(contents));
4653
4654        Ok(())
4655    }
4656
4657    /// Returns whether all the media-feature affected values matched before and
4658    /// match now in the given stylesheet.
4659    pub fn media_feature_affected_matches<S>(
4660        &self,
4661        stylesheet: &S,
4662        guard: &SharedRwLockReadGuard,
4663        device: &Device,
4664        quirks_mode: QuirksMode,
4665    ) -> bool
4666    where
4667        S: StylesheetInDocument + 'static,
4668    {
4669        use crate::invalidation::media_queries::PotentiallyEffectiveMediaRules;
4670
4671        let effective_now = stylesheet.is_effective_for_device(device, &self.custom_media, guard);
4672
4673        let contents = stylesheet.contents(guard);
4674        let effective_then = self.effective_media_query_results.was_effective(contents);
4675
4676        if effective_now != effective_then {
4677            debug!(
4678                " > Stylesheet {:?} changed -> {}, {}",
4679                stylesheet.media(guard),
4680                effective_then,
4681                effective_now
4682            );
4683            return false;
4684        }
4685
4686        if !effective_now {
4687            return true;
4688        }
4689
4690        // We don't need a custom media map for PotentiallyEffectiveMediaRules.
4691        let custom_media = CustomMediaMap::default();
4692        let mut iter =
4693            contents.iter_rules::<PotentiallyEffectiveMediaRules, _>(device, &custom_media, guard);
4694        while let Some(rule) = iter.next() {
4695            match *rule {
4696                CssRule::Style(..)
4697                | CssRule::NestedDeclarations(..)
4698                | CssRule::Namespace(..)
4699                | CssRule::FontFace(..)
4700                | CssRule::Container(..)
4701                | CssRule::CounterStyle(..)
4702                | CssRule::Supports(..)
4703                | CssRule::Keyframes(..)
4704                | CssRule::Margin(..)
4705                | CssRule::Page(..)
4706                | CssRule::Property(..)
4707                | CssRule::Document(..)
4708                | CssRule::LayerBlock(..)
4709                | CssRule::LayerStatement(..)
4710                | CssRule::FontPaletteValues(..)
4711                | CssRule::FontFeatureValues(..)
4712                | CssRule::Scope(..)
4713                | CssRule::StartingStyle(..)
4714                | CssRule::AppearanceBase(..)
4715                | CssRule::CustomMedia(..)
4716                | CssRule::PositionTry(..)
4717                | CssRule::ViewTransition(..) => {
4718                    // Not affected by device changes. @custom-media is handled by the potential
4719                    // @media rules referencing it being handled.
4720                    continue;
4721                },
4722                CssRule::Import(ref lock) => {
4723                    let import_rule = lock.read_with(guard);
4724                    let effective_now = match import_rule.stylesheet.media(guard) {
4725                        Some(m) => m.evaluate(
4726                            device,
4727                            quirks_mode,
4728                            &mut CustomMediaEvaluator::new(&self.custom_media, guard),
4729                        ),
4730                        None => true,
4731                    };
4732                    let effective_then = self
4733                        .effective_media_query_results
4734                        .was_effective(import_rule);
4735                    if effective_now != effective_then {
4736                        debug!(
4737                            " > @import rule {:?} changed {} -> {}",
4738                            import_rule.stylesheet.media(guard),
4739                            effective_then,
4740                            effective_now
4741                        );
4742                        return false;
4743                    }
4744
4745                    if !effective_now {
4746                        iter.skip_children();
4747                    }
4748                },
4749                CssRule::Media(ref media_rule) => {
4750                    let mq = media_rule.media_queries.read_with(guard);
4751                    let effective_now = mq.evaluate(
4752                        device,
4753                        quirks_mode,
4754                        &mut CustomMediaEvaluator::new(&self.custom_media, guard),
4755                    );
4756                    let effective_then = self
4757                        .effective_media_query_results
4758                        .was_effective(&**media_rule);
4759
4760                    if effective_now != effective_then {
4761                        debug!(
4762                            " > @media rule {:?} changed {} -> {}",
4763                            mq, effective_then, effective_now
4764                        );
4765                        return false;
4766                    }
4767
4768                    if !effective_now {
4769                        iter.skip_children();
4770                    }
4771                },
4772            }
4773        }
4774
4775        true
4776    }
4777
4778    /// Returns the custom properties map.
4779    pub fn custom_property_registrations(&self) -> &LayerOrderedMap<Arc<PropertyRegistration>> {
4780        &self.custom_property_registrations
4781    }
4782
4783    fn revalidate_scopes<E: TElement>(
4784        &self,
4785        element: &E,
4786        matching_context: &mut MatchingContext<E::Impl>,
4787        result: &mut ScopeRevalidationResult,
4788    ) {
4789        // TODO(dshin): A scope block may not contain style rule for this element, but we don't keep
4790        // track of that, so we check _all_ scope conditions. It's possible for two comparable elements
4791        // to share scope & relevant styles rules, but also differ in scopes that do not contain style
4792        // rules relevant to them. So while we can be certain that an identical result share scoped styles
4793        // (Given that other sharing conditions are met), it is uncertain if elements with non-matching
4794        // results do not.
4795        for condition_id in 1..self.scope_conditions.len() {
4796            let condition = &self.scope_conditions[condition_id];
4797            let matches = if condition.is_trivial {
4798                // Just ignore this condition - for style sharing candidates, guaranteed
4799                // the same match result.
4800                continue;
4801            } else {
4802                let result = scope_root_candidates(
4803                    &self.scope_conditions,
4804                    ScopeConditionId(condition_id as u16),
4805                    element,
4806                    // This should be ok since we aren't sharing styles across shadow boundaries.
4807                    false,
4808                    &self.scope_subject_map,
4809                    matching_context,
4810                );
4811                !result.candidates.is_empty()
4812            };
4813            result.scopes_matched.push(matches);
4814        }
4815    }
4816
4817    /// Clears the cascade data, but not the invalidation data.
4818    fn clear_cascade_data(&mut self) {
4819        self.normal_rules.clear();
4820        if let Some(ref mut slotted_rules) = self.slotted_rules {
4821            slotted_rules.clear();
4822        }
4823        if let Some(ref mut part_rules) = self.part_rules {
4824            part_rules.clear();
4825        }
4826        if let Some(ref mut host_rules) = self.featureless_host_rules {
4827            host_rules.clear();
4828        }
4829        self.animations.clear();
4830        self.custom_property_registrations.clear();
4831        self.layers.clear();
4832        self.custom_media.clear();
4833        self.container_conditions.clear();
4834        self.container_conditions
4835            .push(ContainerConditionReference::none());
4836        self.scope_conditions.clear();
4837        self.scope_conditions.push(ScopeConditionReference::none());
4838        self.extra_data.clear();
4839        self.rules_source_order = 0;
4840        self.num_selectors = 0;
4841        self.num_declarations = 0;
4842    }
4843
4844    fn clear_invalidation_data(&mut self) {
4845        self.invalidation_map.clear();
4846        self.relative_selector_invalidation_map.clear();
4847        self.additional_relative_selector_invalidation_map.clear();
4848        self.attribute_dependencies.clear();
4849        self.container_attr_function_dependencies.clear();
4850        self.container_unparsed_attr_function_dependency = ContainerAttributeDependencyKind::None;
4851        self.nth_of_attribute_dependencies.clear();
4852        self.nth_of_custom_state_dependencies.clear();
4853        self.nth_of_class_dependencies.clear();
4854        self.state_dependencies = ElementState::empty();
4855        self.nth_of_state_dependencies = ElementState::empty();
4856        self.non_link_visited_dependency = false;
4857        self.document_state_dependencies = DocumentState::empty();
4858        self.mapped_ids.clear();
4859        self.nth_of_mapped_ids.clear();
4860        self.selectors_for_cache_revalidation.clear();
4861        self.effective_media_query_results.clear();
4862        self.scope_subject_map.clear();
4863    }
4864}
4865
4866fn note_scope_selector_for_invalidation(
4867    quirks_mode: QuirksMode,
4868    scope_dependencies: &Arc<servo_arc::HeaderSlice<(), Dependency>>,
4869    dependency_vector: &mut Vec<Dependency>,
4870    invalidation_map: &mut InvalidationMap,
4871    relative_selector_invalidation_map: &mut InvalidationMap,
4872    additional_relative_selector_invalidation_map: &mut AdditionalRelativeSelectorInvalidationMap,
4873    visitor: &mut StylistSelectorVisitor<'_>,
4874    scope_kind: ScopeDependencyInvalidationKind,
4875    s: &Selector<SelectorImpl>,
4876) -> Result<(), AllocErr> {
4877    let mut new_inner_dependencies = note_selector_for_invalidation(
4878        &s.clone(),
4879        quirks_mode,
4880        invalidation_map,
4881        relative_selector_invalidation_map,
4882        additional_relative_selector_invalidation_map,
4883        Some(scope_dependencies),
4884        Some(scope_kind),
4885    )?;
4886    s.visit(visitor);
4887    if let Some(dep) = new_inner_dependencies.as_mut() {
4888        dependency_vector.append(dep);
4889    }
4890    Ok(())
4891}
4892
4893fn build_scope_dependencies(
4894    quirks_mode: QuirksMode,
4895    mut cur_scope_inner_dependencies: Vec<Dependency>,
4896    mut visitor: StylistSelectorVisitor<'_>,
4897    cond: &ScopeBoundsWithHashes,
4898    invalidation_map: &mut InvalidationMap,
4899    relative_selector_invalidation_map: &mut InvalidationMap,
4900    additional_relative_selector_invalidation_map: &mut AdditionalRelativeSelectorInvalidationMap,
4901) -> Result<Vec<Dependency>, AllocErr> {
4902    if cond.end.is_some() {
4903        let deps =
4904            ThinArc::from_header_and_iter((), cur_scope_inner_dependencies.clone().into_iter());
4905        let mut end_dependency_vector = Vec::new();
4906        for s in cond.end_selectors() {
4907            note_scope_selector_for_invalidation(
4908                quirks_mode,
4909                &deps,
4910                &mut end_dependency_vector,
4911                invalidation_map,
4912                relative_selector_invalidation_map,
4913                additional_relative_selector_invalidation_map,
4914                &mut visitor,
4915                ScopeDependencyInvalidationKind::ScopeEnd,
4916                s,
4917            )?;
4918        }
4919        cur_scope_inner_dependencies.append(&mut end_dependency_vector);
4920    }
4921    let inner_scope_dependencies =
4922        ThinArc::from_header_and_iter((), cur_scope_inner_dependencies.into_iter());
4923
4924    Ok(if cond.start.is_some() {
4925        let mut dependency_vector = Vec::new();
4926        for s in cond.start_selectors() {
4927            note_scope_selector_for_invalidation(
4928                quirks_mode,
4929                &inner_scope_dependencies,
4930                &mut dependency_vector,
4931                invalidation_map,
4932                relative_selector_invalidation_map,
4933                additional_relative_selector_invalidation_map,
4934                &mut visitor,
4935                ScopeDependencyInvalidationKind::ExplicitScope,
4936                s,
4937            )?;
4938        }
4939        dependency_vector
4940    } else {
4941        vec![Dependency::new(
4942            IMPLICIT_SCOPE.slice()[0].clone(),
4943            0,
4944            Some(inner_scope_dependencies),
4945            DependencyInvalidationKind::Scope(ScopeDependencyInvalidationKind::ImplicitScope),
4946        )]
4947    })
4948}
4949
4950impl CascadeDataCacheEntry for CascadeData {
4951    fn rebuild<S>(
4952        device: &Device,
4953        quirks_mode: QuirksMode,
4954        collection: SheetCollectionFlusher<S>,
4955        guard: &SharedRwLockReadGuard,
4956        old: &Self,
4957        difference: &mut CascadeDataDifference,
4958    ) -> Result<Arc<Self>, AllocErr>
4959    where
4960        S: StylesheetInDocument + PartialEq + 'static,
4961    {
4962        debug_assert!(collection.dirty(), "We surely need to do something?");
4963        // If we're doing a full rebuild anyways, don't bother cloning the data.
4964        let mut updatable_entry = match collection.data_validity() {
4965            DataValidity::Valid | DataValidity::CascadeInvalid => old.clone(),
4966            DataValidity::FullyInvalid => Self::new(),
4967        };
4968        updatable_entry.rebuild(device, quirks_mode, collection, guard, difference)?;
4969        Ok(Arc::new(updatable_entry))
4970    }
4971
4972    #[cfg(feature = "gecko")]
4973    fn add_size_of(&self, ops: &mut MallocSizeOfOps, sizes: &mut ServoStyleSetSizes) {
4974        self.normal_rules.add_size_of(ops, sizes);
4975        if let Some(ref slotted_rules) = self.slotted_rules {
4976            slotted_rules.add_size_of(ops, sizes);
4977        }
4978        if let Some(ref part_rules) = self.part_rules {
4979            part_rules.add_size_of(ops, sizes);
4980        }
4981        if let Some(ref host_rules) = self.featureless_host_rules {
4982            host_rules.add_size_of(ops, sizes);
4983        }
4984        sizes.mInvalidationMap += self.invalidation_map.size_of(ops);
4985        sizes.mRevalidationSelectors += self.selectors_for_cache_revalidation.size_of(ops);
4986        sizes.mOther += self.animations.size_of(ops);
4987        sizes.mOther += self.effective_media_query_results.size_of(ops);
4988        sizes.mOther += self.extra_data.size_of(ops);
4989    }
4990}
4991
4992impl Default for CascadeData {
4993    fn default() -> Self {
4994        CascadeData::new()
4995    }
4996}
4997
4998/// A rule, that wraps a style rule, but represents a single selector of the
4999/// rule.
5000#[derive(Clone, Debug, MallocSizeOf)]
5001pub struct Rule {
5002    /// The selector this struct represents. We store this and the
5003    /// any_{important,normal} booleans inline in the Rule to avoid
5004    /// pointer-chasing when gathering applicable declarations, which
5005    /// can ruin performance when there are a lot of rules.
5006    #[ignore_malloc_size_of = "CssRules have primary refs, we measure there"]
5007    pub selector: Selector<SelectorImpl>,
5008
5009    /// The ancestor hashes associated with the selector.
5010    pub hashes: AncestorHashes,
5011
5012    /// The source order this style rule appears in. Note that we only use
5013    /// three bytes to store this value in ApplicableDeclarationsBlock, so
5014    /// we could repurpose that storage here if we needed to.
5015    pub source_order: u32,
5016
5017    /// The current layer id of this style rule.
5018    pub layer_id: LayerId,
5019
5020    /// The current @container rule id.
5021    pub container_condition_id: ContainerConditionId,
5022
5023    /// Flags for special cascade behaviors.
5024    pub cascade_flags: RuleCascadeFlags,
5025
5026    /// The current @scope rule id.
5027    pub scope_condition_id: ScopeConditionId,
5028
5029    /// Whether the selector map always covers our selector.
5030    pub bucket_matches: BucketMatches,
5031
5032    /// The actual style rule.
5033    #[ignore_malloc_size_of = "Secondary ref. Primary ref is in StyleRule under Stylesheet."]
5034    pub style_source: StyleSource,
5035}
5036
5037impl SelectorMapEntry for Rule {
5038    fn selector(&self) -> SelectorIter<'_, SelectorImpl> {
5039        self.selector.iter()
5040    }
5041
5042    fn set_bucket_matches(&mut self, bucket_matches: BucketMatches) {
5043        self.bucket_matches = bucket_matches;
5044    }
5045}
5046
5047impl Rule {
5048    /// Returns the specificity of the rule.
5049    pub fn specificity(&self) -> u32 {
5050        self.selector.specificity()
5051    }
5052
5053    /// Turns this rule into an `ApplicableDeclarationBlock` for the given
5054    /// cascade level.
5055    pub fn to_applicable_declaration_block(
5056        &self,
5057        level: CascadeLevel,
5058        cascade_data: &CascadeData,
5059        scope_proximity: ScopeProximity,
5060    ) -> ApplicableDeclarationBlock<'_> {
5061        ApplicableDeclarationBlock::new(
5062            self.style_source.borrow(),
5063            self.source_order,
5064            level,
5065            self.specificity(),
5066            cascade_data.layer_order_for(self.layer_id),
5067            scope_proximity,
5068            self.cascade_flags,
5069        )
5070    }
5071
5072    /// Creates a new Rule.
5073    pub fn new(
5074        selector: Selector<SelectorImpl>,
5075        hashes: AncestorHashes,
5076        style_source: StyleSource,
5077        source_order: u32,
5078        layer_id: LayerId,
5079        container_condition_id: ContainerConditionId,
5080        cascade_flags: RuleCascadeFlags,
5081        scope_condition_id: ScopeConditionId,
5082    ) -> Self {
5083        Self {
5084            selector,
5085            hashes,
5086            style_source,
5087            source_order,
5088            layer_id,
5089            container_condition_id,
5090            cascade_flags,
5091            scope_condition_id,
5092            bucket_matches: BucketMatches::Unknown,
5093        }
5094    }
5095
5096    fn iter_past_subject<'a, E: TElement>(
5097        selector: &'a Selector<SelectorImpl>,
5098        mut element: E,
5099        context: &mut MatchingContext<E::Impl>,
5100    ) -> (E, SelectorIter<'a, SelectorImpl>) {
5101        let mut offset = 0;
5102        let mut skipped_pseudo = false;
5103        // Skip the subject + pseudo bit. Note that nested selector lists are dealt with in
5104        // find_bucket.
5105        let mut iter = selector.iter();
5106        loop {
5107            for _ in &mut iter {
5108                offset += 1;
5109            }
5110            if iter.next_sequence() != Some(Combinator::PseudoElement) {
5111                break;
5112            }
5113            if skipped_pseudo || context.matching_mode() != MatchingMode::ForStatelessPseudoElement
5114            {
5115                element = element.pseudo_element_originating_element().unwrap();
5116            }
5117            skipped_pseudo = true;
5118            offset += 1;
5119        }
5120        (element, selector.iter_from(offset))
5121    }
5122
5123    /// Tests a given element against our selector.
5124    #[inline(always)]
5125    pub fn matches_selector<E: TElement>(
5126        &self,
5127        mut element: E,
5128        context: &mut MatchingContext<E::Impl>,
5129    ) -> bool {
5130        if context
5131            .bloom_filter
5132            .is_some_and(|f| !selector_may_match(&self.hashes, f))
5133        {
5134            return false;
5135        }
5136        if self.bucket_matches == BucketMatches::Full {
5137            return true;
5138        }
5139        let mut iter = self.selector.iter();
5140        let mut subject = SubjectOrPseudoElement::Yes;
5141        if self.bucket_matches == BucketMatches::Subject {
5142            (element, iter) = Self::iter_past_subject(&self.selector, element, context);
5143            subject = SubjectOrPseudoElement::No;
5144        }
5145        matches_complex_selector(iter, element, context, subject).to_bool(true)
5146    }
5147}
5148
5149// The size of this is critical to performance on the bloom-basic
5150// microbenchmark.
5151// When iterating over a large Rule array, we want to be able to fast-reject
5152// selectors (with the inline hashes) with as few cache misses as possible.
5153size_of_test!(Rule, 40);
5154
5155/// A function to be able to test the revalidation stuff.
5156pub fn needs_revalidation_for_testing(s: &Selector<SelectorImpl>) -> bool {
5157    let mut needs_revalidation = false;
5158    let mut mapped_ids = Default::default();
5159    let mut nth_of_mapped_ids = Default::default();
5160    let mut attribute_dependencies = Default::default();
5161    let mut nth_of_class_dependencies = Default::default();
5162    let mut nth_of_attribute_dependencies = Default::default();
5163    let mut nth_of_custom_state_dependencies = Default::default();
5164    let mut state_dependencies = ElementState::empty();
5165    let mut nth_of_state_dependencies = ElementState::empty();
5166    let mut document_state_dependencies = DocumentState::empty();
5167    let mut non_link_visited_dependency = false;
5168    let mut visitor = StylistSelectorVisitor {
5169        passed_rightmost_selector: false,
5170        needs_revalidation: &mut needs_revalidation,
5171        non_link_visited_dependency: &mut non_link_visited_dependency,
5172        in_selector_list_of: SelectorListKind::default(),
5173        mapped_ids: &mut mapped_ids,
5174        nth_of_mapped_ids: &mut nth_of_mapped_ids,
5175        attribute_dependencies: &mut attribute_dependencies,
5176        nth_of_class_dependencies: &mut nth_of_class_dependencies,
5177        nth_of_attribute_dependencies: &mut nth_of_attribute_dependencies,
5178        nth_of_custom_state_dependencies: &mut nth_of_custom_state_dependencies,
5179        state_dependencies: &mut state_dependencies,
5180        nth_of_state_dependencies: &mut nth_of_state_dependencies,
5181        document_state_dependencies: &mut document_state_dependencies,
5182    };
5183    s.visit(&mut visitor);
5184    needs_revalidation
5185}