Skip to main content

style/rule_tree/
mod.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5#![deny(unsafe_code)]
6
7//! The rule tree.
8
9use crate::applicable_declarations::{ApplicableDeclarationList, CascadePriority};
10use crate::properties::{LonghandIdSet, PropertyDeclarationBlock};
11use crate::shared_lock::{Locked, StylesheetGuards};
12use crate::stylesheets::layer_rule::LayerOrder;
13use servo_arc::ArcBorrow;
14use smallvec::SmallVec;
15use std::io::{self, Write};
16
17mod core;
18pub mod level;
19mod map;
20mod source;
21mod unsafe_box;
22
23pub use self::core::{RuleTree, StrongRuleNode};
24pub use self::level::{CascadeLevel, CascadeOrigin, ShadowCascadeOrder};
25pub use self::source::{StyleSource, StyleSourceBorrow};
26
27bitflags! {
28    /// Flags that are part of the cascade priority, and that we use to track
29    /// information about where the rule came from.
30    #[derive(Clone, Copy, Debug, Default, Eq, Hash, PartialEq)]
31    pub struct RuleCascadeFlags: u8 {
32        /// Whether the rule is inside a @starting-style block.
33        const STARTING_STYLE = 1 << 0;
34        /// Whether the rule is inside an @appearance-base block.
35        const APPEARANCE_BASE = 1 << 1;
36    }
37}
38
39malloc_size_of::malloc_size_of_is_0!(RuleCascadeFlags);
40
41impl RuleTree {
42    fn dump<W: Write>(&self, guards: &StylesheetGuards, writer: &mut W) {
43        let _ = writeln!(writer, " + RuleTree");
44        self.root().dump(guards, writer, 0);
45    }
46
47    /// Dump the rule tree to stdout.
48    pub fn dump_stdout(&self, guards: &StylesheetGuards) {
49        let mut stdout = io::stdout();
50        self.dump(guards, &mut stdout);
51    }
52
53    /// Inserts the given rules, that must be in proper order by specifity, and
54    /// returns the corresponding rule node representing the last inserted one.
55    ///
56    /// !important rules are detected and inserted into the appropriate position
57    /// in the rule tree. This allows selector matching to ignore importance,
58    /// while still maintaining the appropriate cascade order in the rule tree.
59    pub fn insert_ordered_rules_with_important<'a, I>(
60        &self,
61        iter: I,
62        guards: &StylesheetGuards,
63    ) -> StrongRuleNode
64    where
65        I: Iterator<Item = (StyleSourceBorrow<'a>, CascadePriority)>,
66    {
67        let mut current = self.root().clone();
68
69        let mut found_important = false;
70
71        let mut important_author = SmallVec::<[(StyleSourceBorrow, CascadePriority); 4]>::new();
72        let mut important_user = SmallVec::<[(StyleSourceBorrow, CascadePriority); 4]>::new();
73        let mut important_ua = SmallVec::<[(StyleSourceBorrow, CascadePriority); 4]>::new();
74        let mut transition = None;
75
76        for (source, priority) in iter {
77            let level = priority.cascade_level();
78            debug_assert!(!level.is_important(), "Important levels handled internally");
79
80            let any_important = {
81                let pdb = source.read(level.guard(guards));
82                pdb.any_important()
83            };
84
85            if any_important {
86                found_important = true;
87                match level.origin() {
88                    CascadeOrigin::Author => important_author.push((source, priority.important())),
89                    CascadeOrigin::UA => important_ua.push((source, priority.important())),
90                    CascadeOrigin::User => important_user.push((source, priority.important())),
91                    _ => {},
92                };
93            }
94
95            // We don't optimize out empty rules, even though we could.
96            //
97            // Inspector relies on every rule being inserted in the normal level
98            // at least once, in order to return the rules with the correct
99            // specificity order.
100            //
101            // TODO(emilio): If we want to apply these optimizations without
102            // breaking inspector's expectations, we'd need to run
103            // selector-matching again at the inspector's request. That may or
104            // may not be a better trade-off.
105            if level.origin() == CascadeOrigin::Transitions && found_important {
106                // There can be at most one transition, and it will come at
107                // the end of the iterator. Stash it and apply it after
108                // !important rules.
109                debug_assert!(transition.is_none());
110                transition = Some(source);
111            } else {
112                current = current.ensure_child(self.root(), source, priority);
113            }
114        }
115
116        // Early-return in the common case of no !important declarations.
117        if !found_important {
118            return current;
119        }
120
121        // Insert important declarations, in order of increasing importance,
122        // followed by any transition rule.
123        //
124        // Important rules are sorted differently from unimportant ones by
125        // shadow order and cascade order.
126        if !important_author.is_empty()
127            && important_author.first().unwrap().1 != important_author.last().unwrap().1
128        {
129            // We only need to sort if the important rules come from
130            // different trees, but we need this sort to be stable.
131            //
132            // FIXME(emilio): This could maybe be smarter, probably by chunking
133            // the important rules while inserting, and iterating the outer
134            // chunks in reverse order.
135            //
136            // That is, if we have rules with levels like: -1 -1 -1 0 0 0 1 1 1,
137            // we're really only sorting the chunks, while keeping elements
138            // inside the same chunk already sorted. Seems like we could try to
139            // keep a SmallVec-of-SmallVecs with the chunks and just iterate the
140            // outer in reverse.
141            important_author.sort_by_key(|&(_, priority)| priority);
142        }
143
144        for (source, priority) in important_author.drain(..) {
145            current = current.ensure_child(self.root(), source, priority);
146        }
147
148        for (source, priority) in important_user.drain(..) {
149            current = current.ensure_child(self.root(), source, priority);
150        }
151
152        if !crate::pref!("layout.css.transitions-override-ua")
153            && let Some(source) = transition.take()
154        {
155            current = current.ensure_child(self.root(), source, CascadePriority::TRANSITIONS);
156        }
157
158        for (source, priority) in important_ua.drain(..) {
159            current = current.ensure_child(self.root(), source, priority);
160        }
161
162        if let Some(source) = transition {
163            current = current.ensure_child(self.root(), source, CascadePriority::TRANSITIONS);
164        }
165
166        current
167    }
168
169    /// Given a list of applicable declarations, insert the rules and return the
170    /// corresponding rule node.
171    pub fn compute_rule_node(
172        &self,
173        applicable_declarations: &mut ApplicableDeclarationList,
174        guards: &StylesheetGuards,
175    ) -> StrongRuleNode {
176        let mut prev = None;
177        self.insert_ordered_rules_with_important(
178            applicable_declarations.drain(..).filter_map(|d| {
179                // for_rule_tree keeps only these two, so adjacent entries that
180                // agree on them contribute the same thing to the rule path.
181                let key = (d.source.key(), d.cascade_priority);
182                if prev == Some(key) {
183                    return None;
184                }
185                prev = Some(key);
186                Some(d.for_rule_tree())
187            }),
188            guards,
189        )
190    }
191
192    /// Insert the given rules, that must be in proper order by specifity, and
193    /// return the corresponding rule node representing the last inserted one.
194    pub fn insert_ordered_rules<'a, I>(&self, iter: I) -> StrongRuleNode
195    where
196        I: Iterator<Item = (StyleSourceBorrow<'a>, CascadePriority)>,
197    {
198        self.insert_ordered_rules_from(self.root().clone(), iter)
199    }
200
201    fn insert_ordered_rules_from<'a, I>(&self, from: StrongRuleNode, iter: I) -> StrongRuleNode
202    where
203        I: Iterator<Item = (StyleSourceBorrow<'a>, CascadePriority)>,
204    {
205        let mut current = from;
206        for (source, priority) in iter {
207            current = current.ensure_child(self.root(), source, priority);
208        }
209        current
210    }
211
212    /// Replaces a rule in a given level (if present) for another rule.
213    ///
214    /// Returns the resulting node that represents the new path, or None if
215    /// the old path is still valid.
216    pub fn update_rule_at_level(
217        &self,
218        level: CascadeLevel,
219        layer_order: LayerOrder,
220        pdb: Option<ArcBorrow<Locked<PropertyDeclarationBlock>>>,
221        path: &StrongRuleNode,
222        guards: &StylesheetGuards,
223        important_rules_changed: &mut bool,
224    ) -> Option<StrongRuleNode> {
225        // TODO(emilio): Being smarter with lifetimes we could avoid a bit of
226        // the refcount churn.
227        let mut current = path.clone();
228        *important_rules_changed = false;
229
230        // First walk up until the first less-or-equally specific rule.
231        let mut children = SmallVec::<[_; 10]>::new();
232        while current.cascade_priority().cascade_level() > level {
233            children.push((
234                current.style_source().unwrap().clone(),
235                current.cascade_priority(),
236            ));
237            current = current.parent().unwrap().clone();
238        }
239
240        let cascade_priority = CascadePriority::new(level, layer_order, RuleCascadeFlags::empty());
241
242        // Then remove the one at the level we want to replace, if any.
243        //
244        // NOTE: Here we assume that only one rule can be at the level + priority we're replacing,
245        // which holds because we only use this for HTML style attribute, animations and transition
246        // rules.
247        //
248        // This is certainly true for HTML style attribute rules, animations, transitions, and
249        // SMIL.
250        if current.cascade_priority() == cascade_priority {
251            *important_rules_changed |= level.is_important();
252
253            let current_decls = current.style_source().unwrap().get();
254
255            // If the only rule at the level we're replacing is exactly the
256            // same as `pdb`, we're done, and `path` is still valid.
257            if let Some(ref pdb) = pdb {
258                // If the only rule at the level we're replacing is exactly the
259                // same as `pdb`, we're done, and `path` is still valid.
260                //
261                // TODO(emilio): Another potential optimization is the one where
262                // we can just replace the rule at that level for `pdb`, and
263                // then we don't need to re-create the children, and `path` is
264                // also equally valid. This is less likely, and would require an
265                // in-place mutation of the source, which is, at best, fiddly,
266                // so let's skip it for now.
267                let is_here_already = ArcBorrow::ptr_eq(pdb, &current_decls.borrow_arc());
268                if is_here_already {
269                    debug!("Picking the fast path in rule replacement");
270                    return None;
271                }
272            }
273
274            current = current.parent().unwrap().clone();
275        }
276
277        // Insert the rule if it's relevant at this level in the cascade.
278        //
279        // These optimizations are likely to be important, because the levels where replacements
280        // apply (style and animations) tend to trigger pretty bad styling cases already.
281        if let Some(pdb) = pdb {
282            let source = StyleSourceBorrow::from_declarations(pdb);
283            if level.is_important() {
284                if pdb.read_with(level.guard(guards)).any_important() {
285                    current = current.ensure_child(self.root(), source, cascade_priority);
286                    *important_rules_changed = true;
287                }
288            } else if pdb.read_with(level.guard(guards)).any_normal() {
289                current = current.ensure_child(self.root(), source, cascade_priority);
290            }
291        }
292
293        // Now the rule is in the relevant place, push the children as
294        // necessary.
295        let rule = self.insert_ordered_rules_from(
296            current,
297            children.iter().rev().map(|(s, p)| (s.borrow(), *p)),
298        );
299        Some(rule)
300    }
301
302    /// Returns whether this rule node has any @starting-style rule.
303    pub fn has_starting_style(path: &StrongRuleNode) -> bool {
304        path.self_and_ancestors().any(|node| {
305            node.cascade_priority()
306                .flags()
307                .intersects(RuleCascadeFlags::STARTING_STYLE)
308        })
309    }
310
311    /// Returns new rule nodes without transitions level rule.
312    pub fn remove_transition_rule_if_applicable(&self, path: &StrongRuleNode) -> StrongRuleNode {
313        let transitions = CascadeLevel::new(CascadeOrigin::Transitions);
314        self.remove_rules_at_levels(path, transitions, |l| l == transitions)
315    }
316
317    /// Returns new rule node without rules from declarative animations.
318    /// `lowest_level` is the lowest level we should look at, levels lower than that we're not
319    /// interested in.
320    fn remove_rules_at_levels(
321        &self,
322        path: &StrongRuleNode,
323        lowest_level: CascadeLevel,
324        mut should_remove: impl FnMut(CascadeLevel) -> bool,
325    ) -> StrongRuleNode {
326        let mut last = path;
327        let iter = path
328            .self_and_ancestors()
329            .take_while(|node| node.cascade_level() >= lowest_level);
330        let mut any_to_remove = false;
331        let mut children = SmallVec::<[_; 10]>::new();
332        for node in iter {
333            if !should_remove(node.cascade_level()) {
334                children.push((
335                    node.style_source().unwrap().clone(),
336                    node.cascade_priority(),
337                ));
338            } else {
339                any_to_remove = true;
340            }
341            last = node;
342        }
343
344        if !any_to_remove {
345            return path.clone();
346        }
347
348        self.insert_ordered_rules_from(
349            last.parent().unwrap().clone(),
350            children.iter().rev().map(|(s, p)| (s.borrow(), *p)),
351        )
352    }
353
354    /// Returns new rule node without rules from declarative animations.
355    pub fn remove_animation_rules(&self, path: &StrongRuleNode) -> StrongRuleNode {
356        self.remove_rules_at_levels(
357            path,
358            CascadeLevel::new(CascadeOrigin::SMILOverride),
359            CascadeLevel::is_animation,
360        )
361    }
362}
363
364impl StrongRuleNode {
365    /// Get an iterator for this rule node and its ancestors.
366    pub fn self_and_ancestors(&self) -> SelfAndAncestors<'_> {
367        SelfAndAncestors {
368            current: Some(self),
369        }
370    }
371
372    /// Get a set of properties whose CascadeLevel are higher than Animations
373    /// but not equal to Transitions.
374    ///
375    /// If there are any custom properties, we set the boolean value of the
376    /// returned tuple to true.
377    pub fn get_properties_overriding_animations(
378        &self,
379        guards: &StylesheetGuards,
380    ) -> (LonghandIdSet, bool) {
381        use crate::properties::PropertyDeclarationId;
382
383        // We want to iterate over cascade levels that override the animations
384        // level, i.e.  !important levels and the transitions level.
385        //
386        // However, we actually want to skip the transitions level because
387        // although it is higher in the cascade than animations, when both
388        // transitions and animations are present for a given element and
389        // property, transitions are suppressed so that they don't actually
390        // override animations.
391        let iter = self
392            .self_and_ancestors()
393            .take_while(|node| node.cascade_level() > CascadeLevel::new(CascadeOrigin::Animations));
394        let mut result = (LonghandIdSet::new(), false);
395        for node in iter {
396            if node.cascade_level().is_animation() {
397                // Note that this skips transitions too.
398                continue;
399            }
400            let style = node.style_source().unwrap();
401            for (decl, important) in style
402                .read(node.cascade_level().guard(guards))
403                .declaration_importance_iter()
404            {
405                // Although we are only iterating over cascade levels that
406                // override animations, in a given property declaration block we
407                // can have a mixture of !important and non-!important
408                // declarations but only the !important declarations actually
409                // override animations.
410                if important.important() {
411                    match decl.id() {
412                        PropertyDeclarationId::Longhand(id) => result.0.insert(id),
413                        PropertyDeclarationId::Custom(_) => result.1 = true,
414                    }
415                }
416            }
417        }
418        result
419    }
420}
421
422/// An iterator over a rule node and its ancestors.
423#[derive(Clone)]
424pub struct SelfAndAncestors<'a> {
425    current: Option<&'a StrongRuleNode>,
426}
427
428impl<'a> Iterator for SelfAndAncestors<'a> {
429    type Item = &'a StrongRuleNode;
430
431    fn next(&mut self) -> Option<Self::Item> {
432        self.current.inspect(|node| {
433            self.current = node.parent();
434        })
435    }
436}