Skip to main content

style/
rule_collector.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//! Collects a series of applicable rules for a given element.
6
7use crate::applicable_declarations::{ApplicableDeclarationBlock, ApplicableDeclarationList};
8use crate::dom::{TElement, TNode, TShadowRoot};
9use crate::properties::{AnimationDeclarations, PropertyDeclarationBlock};
10use crate::rule_tree::{CascadeLevel, CascadeOrigin, ShadowCascadeOrder};
11use crate::selector_map::SelectorMap;
12use crate::selector_parser::PseudoElement;
13use crate::shared_lock::Locked;
14use crate::stylesheets::{Origin, layer_rule::LayerOrder};
15use crate::stylist::{AuthorStylesEnabled, CascadeData, Rule, RuleInclusion, Stylist};
16use selectors::matching::MatchingContext;
17use servo_arc::ArcBorrow;
18use smallvec::SmallVec;
19
20/// This is a bit of a hack so <svg:use> matches the rules of the enclosing
21/// tree.
22///
23/// This function returns the containing shadow host ignoring <svg:use> shadow
24/// trees, since those match the enclosing tree's rules.
25///
26/// Only a handful of places need to really care about this. This is not a
27/// problem for invalidation and that kind of stuff because they still don't
28/// match rules based on elements outside of the shadow tree, and because the
29/// <svg:use> subtrees are immutable and recreated each time the source tree
30/// changes.
31///
32/// We historically allow cross-document <svg:use> to have these rules applied,
33/// but I think that's not great. Gecko is the only engine supporting that.
34///
35/// See https://github.com/w3c/svgwg/issues/504 for the relevant spec
36/// discussion.
37#[inline]
38pub fn containing_shadow_ignoring_svg_use<E: TElement>(
39    element: E,
40) -> Option<<E::ConcreteNode as TNode>::ConcreteShadowRoot> {
41    let mut shadow = element.containing_shadow()?;
42    loop {
43        let host = shadow.host();
44        let host_is_svg_use_element =
45            host.is_svg_element() && host.local_name() == &**local_name!("use");
46        if !host_is_svg_use_element {
47            return Some(shadow);
48        }
49        debug_assert!(
50            shadow.style_data().is_none(),
51            "We allow no stylesheets in <svg:use> subtrees"
52        );
53        shadow = host.containing_shadow()?;
54    }
55}
56
57/// An object that we use with all the intermediate state needed for the
58/// cascade.
59///
60/// This is done basically to be able to organize the cascade in smaller
61/// functions, and be able to reason about it easily.
62pub struct RuleCollector<'a, 'b: 'a, E>
63where
64    E: TElement,
65{
66    element: E,
67    rule_hash_target: E,
68    stylist: &'a Stylist,
69    // NOTE: The pseudo-elements are in reverse order from what you'd see in a selector. E.g. for
70    // details::details-content::marker, the list is [::marker, ::details-content], and `element` is
71    // the `::marker`.
72    pseudo_elements: &'a [PseudoElement],
73    style_attribute: Option<ArcBorrow<'a, Locked<PropertyDeclarationBlock>>>,
74    smil_override: Option<ArcBorrow<'a, Locked<PropertyDeclarationBlock>>>,
75    animation_declarations: AnimationDeclarations,
76    rule_inclusion: RuleInclusion,
77    rules: &'a mut ApplicableDeclarationList,
78    context: &'a mut MatchingContext<'b, E::Impl>,
79    matches_user_and_content_rules: bool,
80    matches_document_author_rules: bool,
81    in_sort_scope: bool,
82}
83
84impl<'a, 'b: 'a, E> RuleCollector<'a, 'b, E>
85where
86    E: TElement,
87{
88    /// Trivially construct a new collector.
89    pub fn new(
90        stylist: &'a Stylist,
91        element: E,
92        rule_hash_target: E,
93        pseudo_elements: &'a [PseudoElement],
94        style_attribute: Option<ArcBorrow<'a, Locked<PropertyDeclarationBlock>>>,
95        smil_override: Option<ArcBorrow<'a, Locked<PropertyDeclarationBlock>>>,
96        animation_declarations: AnimationDeclarations,
97        rule_inclusion: RuleInclusion,
98        rules: &'a mut ApplicableDeclarationList,
99        context: &'a mut MatchingContext<'b, E::Impl>,
100    ) -> Self {
101        debug_assert_eq!(rule_hash_target, element.ultimate_originating_element());
102        debug_assert!(pseudo_elements.iter().all(|p| !p.is_precomputed()));
103
104        let matches_user_and_content_rules = rule_hash_target.matches_user_and_content_rules();
105        Self {
106            element,
107            rule_hash_target,
108            stylist,
109            pseudo_elements,
110            style_attribute,
111            smil_override,
112            animation_declarations,
113            rule_inclusion,
114            context,
115            rules,
116            matches_user_and_content_rules,
117            matches_document_author_rules: matches_user_and_content_rules,
118            in_sort_scope: false,
119        }
120    }
121
122    /// Sets up the state necessary to collect rules from a given DOM tree
123    /// (either the document tree, or a shadow tree).
124    ///
125    /// All rules in the same tree need to be matched together, and this
126    /// function takes care of sorting them by specificity and source order.
127    #[inline]
128    fn in_tree(&mut self, host: Option<E>, f: impl FnOnce(&mut Self)) {
129        debug_assert!(!self.in_sort_scope, "Nested sorting makes no sense");
130        let start = self.rules.len();
131        self.in_sort_scope = true;
132        let old_host = self.context.current_host.take();
133        self.context.current_host = host.map(|e| e.opaque());
134        f(self);
135        if start != self.rules.len() {
136            self.rules[start..].sort_unstable_by_key(|block| block.sort_key());
137        }
138        self.context.current_host = old_host;
139        self.in_sort_scope = false;
140    }
141
142    #[inline]
143    fn in_shadow_tree(&mut self, host: E, f: impl FnOnce(&mut Self)) {
144        self.in_tree(Some(host), f);
145    }
146
147    fn collect_stylist_rules(&mut self, origin: Origin) {
148        let cascade_level = match origin {
149            Origin::UserAgent => CascadeLevel::new(CascadeOrigin::UA),
150            Origin::User => CascadeLevel::new(CascadeOrigin::User),
151            Origin::Author => CascadeLevel::same_tree_author_normal(),
152        };
153
154        self.in_tree(None, |collector| {
155            let cascade_data = collector.stylist.cascade_data().borrow_for_origin(origin);
156            // Element-backed pseudo-elements (e.g. ::picker), also apply UA rules that target
157            // underlying element directly (like [popover] rules).
158            if origin == Origin::UserAgent
159                && collector.is_element_backed_pseudo_element()
160                && let Some(map) = cascade_data.normal_rules(&[])
161            {
162                collector.collect_rules_in_map_with_target(
163                    map,
164                    cascade_level,
165                    cascade_data,
166                    collector.element,
167                );
168            }
169            if let Some(map) = cascade_data.normal_rules(collector.pseudo_elements) {
170                collector.collect_rules_in_map(map, cascade_level, cascade_data);
171            }
172        });
173    }
174
175    fn collect_user_agent_rules(&mut self) {
176        self.collect_stylist_rules(Origin::UserAgent);
177        #[cfg(feature = "gecko")]
178        self.collect_view_transition_dynamic_rules();
179    }
180
181    #[cfg(feature = "gecko")]
182    fn collect_view_transition_dynamic_rules(&mut self) {
183        if !self
184            .pseudo_elements
185            .first()
186            .is_some_and(|p| p.is_named_view_transition())
187        {
188            return;
189        }
190        let len_before_vt_rules = self.rules.len();
191        self.element
192            .synthesize_view_transition_dynamic_rules(self.rules);
193        if cfg!(debug_assertions) && self.rules.len() != len_before_vt_rules {
194            for declaration in &self.rules[len_before_vt_rules..] {
195                assert_eq!(declaration.level(), CascadeLevel::new(CascadeOrigin::UA));
196            }
197        }
198    }
199
200    fn collect_user_rules(&mut self) {
201        if !self.matches_user_and_content_rules {
202            return;
203        }
204
205        self.collect_stylist_rules(Origin::User);
206    }
207
208    /// Presentational hints.
209    ///
210    /// These go before author rules, but after user rules, see:
211    /// https://drafts.csswg.org/css-cascade/#preshint
212    fn collect_presentational_hints(&mut self) {
213        if !self.pseudo_elements.is_empty() {
214            return;
215        }
216
217        let length_before_preshints = self.rules.len();
218        self.element
219            .synthesize_presentational_hints_for_legacy_attributes(
220                self.context.visited_handling(),
221                self.rules,
222            );
223        if cfg!(debug_assertions) && self.rules.len() != length_before_preshints {
224            for declaration in &self.rules[length_before_preshints..] {
225                assert_eq!(
226                    declaration.level(),
227                    CascadeLevel::new(CascadeOrigin::PresHints)
228                );
229            }
230        }
231    }
232
233    #[inline]
234    fn collect_rules_in_list(
235        &mut self,
236        part_rules: &[Rule],
237        cascade_level: CascadeLevel,
238        cascade_data: &CascadeData,
239    ) {
240        debug_assert!(self.in_sort_scope, "Rules gotta be sorted");
241        SelectorMap::get_matching_rules(
242            self.element,
243            part_rules,
244            self.rules,
245            self.context,
246            cascade_level,
247            cascade_data,
248            self.stylist,
249        );
250    }
251
252    #[inline]
253    fn collect_rules_in_map(
254        &mut self,
255        map: &SelectorMap<Rule>,
256        cascade_level: CascadeLevel,
257        cascade_data: &CascadeData,
258    ) {
259        self.collect_rules_in_map_with_target(
260            map,
261            cascade_level,
262            cascade_data,
263            self.rule_hash_target,
264        );
265    }
266
267    #[inline]
268    fn collect_rules_in_map_with_target(
269        &mut self,
270        map: &SelectorMap<Rule>,
271        cascade_level: CascadeLevel,
272        cascade_data: &CascadeData,
273        rule_hash_target: E,
274    ) {
275        debug_assert!(self.in_sort_scope, "Rules gotta be sorted");
276        map.get_all_matching_rules(
277            self.element,
278            rule_hash_target,
279            self.rules,
280            self.context,
281            cascade_level,
282            cascade_data,
283            self.stylist,
284        );
285    }
286
287    /// Whether we're styling an element-backed pseudo-element.
288    /// TODO: We could support, with some effort, other pseudo-elements attached to the
289    /// element-backed pseudo. That'd be more consistent with how ::part() works, but it's a bit
290    /// weird.
291    #[inline]
292    fn is_element_backed_pseudo_element(&self) -> bool {
293        self.rule_hash_target != self.element
294            && self.pseudo_elements.len() == 1
295            && self.pseudo_elements[0].is_element_backed()
296    }
297
298    /// Collects the rules for the ::slotted pseudo-element and the :host pseudo-class.
299    fn collect_host_and_slotted_rules(&mut self) {
300        let mut slots = SmallVec::<[_; 3]>::new();
301        let mut current = self.rule_hash_target.assigned_slot();
302        let mut shadow_cascade_order = ShadowCascadeOrder::for_outermost_shadow_tree();
303
304        while let Some(slot) = current {
305            debug_assert!(
306                self.matches_user_and_content_rules,
307                "We should not slot NAC anywhere"
308            );
309            slots.push(slot);
310            current = slot.assigned_slot();
311            shadow_cascade_order.dec();
312        }
313
314        self.collect_host_rules(shadow_cascade_order);
315
316        // Match slotted rules in reverse order, so that the outer slotted rules
317        // come before the inner rules (and thus have less priority).
318        for slot in slots.iter().rev() {
319            shadow_cascade_order.inc();
320
321            let shadow = slot.containing_shadow().unwrap();
322            let data = match shadow.style_data() {
323                Some(d) => d,
324                None => continue,
325            };
326
327            let slotted_rules = match data.slotted_rules(self.pseudo_elements) {
328                Some(r) => r,
329                None => continue,
330            };
331
332            self.in_shadow_tree(shadow.host(), |collector| {
333                let cascade_level = CascadeLevel::author_normal(shadow_cascade_order);
334                collector.collect_rules_in_map(slotted_rules, cascade_level, data);
335            });
336        }
337    }
338
339    fn collect_rules_from_containing_shadow_tree(&mut self) {
340        if !self.matches_user_and_content_rules {
341            return;
342        }
343
344        let containing_shadow = containing_shadow_ignoring_svg_use(self.rule_hash_target);
345        let containing_shadow = match containing_shadow {
346            Some(s) => s,
347            None => return,
348        };
349
350        self.matches_document_author_rules = false;
351
352        let cascade_data = match containing_shadow.style_data() {
353            Some(c) => c,
354            None => return,
355        };
356
357        let cascade_level = CascadeLevel::same_tree_author_normal();
358        self.in_shadow_tree(containing_shadow.host(), |collector| {
359            if let Some(map) = cascade_data.normal_rules(collector.pseudo_elements) {
360                collector.collect_rules_in_map(map, cascade_level, cascade_data);
361            }
362
363            // Collect rules from :host::part() and such
364            let hash_target = collector.rule_hash_target;
365            if !hash_target.has_part_attr() {
366                return;
367            }
368
369            let part_rules = match cascade_data.part_rules(collector.pseudo_elements) {
370                Some(p) => p,
371                None => return,
372            };
373
374            hash_target.each_part(|part| {
375                if let Some(part_rules) = part_rules.get(&part.0) {
376                    collector.collect_rules_in_list(part_rules, cascade_level, cascade_data);
377                }
378            });
379        });
380    }
381
382    /// Collects the rules for the :host pseudo-class.
383    fn collect_host_rules(&mut self, shadow_cascade_order: ShadowCascadeOrder) {
384        let Some(shadow) = self.rule_hash_target.shadow_root() else {
385            return;
386        };
387        let Some(cascade_data) = shadow.style_data() else {
388            return;
389        };
390        let rule_hash_target = self.rule_hash_target;
391        let cascade_level = CascadeLevel::author_normal(shadow_cascade_order);
392        self.in_shadow_tree(rule_hash_target, |collector| {
393            if let Some(host_rules) = cascade_data.featureless_host_rules(collector.pseudo_elements)
394            {
395                debug_assert!(!collector.context.featureless(), "How?");
396                collector.context.featureless = true;
397                collector.collect_rules_in_map(host_rules, cascade_level, cascade_data);
398                collector.context.featureless = false;
399            }
400            // We allow stylesheets in the UA tree style the pseudo-element as the real element as
401            // well.
402            if collector.is_element_backed_pseudo_element()
403                && let Some(map) = cascade_data.normal_rules(&[])
404            {
405                collector.collect_rules_in_map_with_target(
406                    map,
407                    cascade_level,
408                    cascade_data,
409                    collector.element,
410                );
411            }
412        });
413    }
414
415    fn collect_document_author_rules(&mut self) {
416        if !self.matches_document_author_rules {
417            return;
418        }
419
420        self.collect_stylist_rules(Origin::Author);
421    }
422
423    fn collect_part_rules_from_outer_trees(&mut self) {
424        if !self.rule_hash_target.has_part_attr() {
425            return;
426        }
427
428        let mut inner_shadow = match self.rule_hash_target.containing_shadow() {
429            Some(s) => s,
430            None => return,
431        };
432
433        let mut shadow_cascade_order = ShadowCascadeOrder::for_innermost_containing_tree();
434
435        let mut parts = SmallVec::<[_; 3]>::new();
436        self.rule_hash_target.each_part(|p| parts.push(p.clone()));
437
438        loop {
439            if parts.is_empty() {
440                return;
441            }
442
443            let inner_shadow_host = inner_shadow.host();
444            let outer_shadow = inner_shadow_host.containing_shadow();
445            let cascade_data = match outer_shadow {
446                Some(shadow) => shadow.style_data(),
447                None => Some(
448                    self.stylist
449                        .cascade_data()
450                        .borrow_for_origin(Origin::Author),
451                ),
452            };
453
454            if let Some(cascade_data) = cascade_data
455                && let Some(part_rules) = cascade_data.part_rules(self.pseudo_elements)
456            {
457                let containing_host = outer_shadow.map(|s| s.host());
458                let cascade_level = CascadeLevel::author_normal(shadow_cascade_order);
459                self.in_tree(containing_host, |collector| {
460                    for p in &parts {
461                        if let Some(part_rules) = part_rules.get(&p.0) {
462                            collector.collect_rules_in_list(
463                                part_rules,
464                                cascade_level,
465                                cascade_data,
466                            );
467                        }
468                    }
469                });
470                shadow_cascade_order.inc();
471            }
472
473            inner_shadow = match outer_shadow {
474                Some(s) => s,
475                None => break, // Nowhere to export to.
476            };
477
478            let mut new_parts = SmallVec::new();
479            for part in &parts {
480                inner_shadow_host.each_exported_part(part, |exported_part| {
481                    new_parts.push(exported_part.clone());
482                });
483            }
484            parts = new_parts;
485        }
486    }
487
488    fn collect_style_attribute(&mut self) {
489        if let Some(sa) = self.style_attribute {
490            self.rules
491                .push(ApplicableDeclarationBlock::from_declarations(
492                    sa.clone_arc(),
493                    CascadeLevel::same_tree_author_normal(),
494                    LayerOrder::style_attribute(),
495                ));
496        }
497    }
498
499    fn collect_animation_rules(&mut self) {
500        if let Some(so) = self.smil_override {
501            self.rules
502                .push(ApplicableDeclarationBlock::from_declarations(
503                    so.clone_arc(),
504                    CascadeLevel::new(CascadeOrigin::SMILOverride),
505                    LayerOrder::root(),
506                ));
507        }
508
509        // The animations sheet (CSS animations, script-generated
510        // animations, and CSS transitions that are no longer tied to CSS
511        // markup).
512        if let Some(anim) = self.animation_declarations.animations.take() {
513            self.rules
514                .push(ApplicableDeclarationBlock::from_declarations(
515                    anim,
516                    CascadeLevel::new(CascadeOrigin::Animations),
517                    LayerOrder::root(),
518                ));
519        }
520
521        // The transitions sheet (CSS transitions that are tied to CSS
522        // markup).
523        if let Some(anim) = self.animation_declarations.transitions.take() {
524            self.rules
525                .push(ApplicableDeclarationBlock::from_declarations(
526                    anim,
527                    CascadeLevel::new(CascadeOrigin::Transitions),
528                    LayerOrder::root(),
529                ));
530        }
531    }
532
533    /// Collects all the rules, leaving the result in `self.rules`.
534    ///
535    /// Note that `!important` rules are handled during rule tree insertion.
536    pub fn collect_all(mut self) {
537        self.collect_user_agent_rules();
538        self.collect_user_rules();
539        if self.rule_inclusion == RuleInclusion::DefaultOnly {
540            return;
541        }
542        self.collect_presentational_hints();
543        // FIXME(emilio): Should the author styles enabled stuff avoid the
544        // presentational hints from getting pushed? See bug 1505770.
545        if self.stylist.author_styles_enabled() == AuthorStylesEnabled::No {
546            return;
547        }
548        self.collect_host_and_slotted_rules();
549        self.collect_rules_from_containing_shadow_tree();
550        self.collect_document_author_rules();
551        self.collect_style_attribute();
552        self.collect_part_rules_from_outer_trees();
553        self.collect_animation_rules();
554    }
555}