Skip to main content

style/
applicable_declarations.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//! Applicable declarations management.
6
7use crate::derives::*;
8use crate::rule_tree::{CascadeLevel, CascadeOrigin, RuleCascadeFlags, StyleSourceBorrow};
9use crate::stylesheets::layer_rule::LayerOrder;
10use smallvec::SmallVec;
11
12/// List of applicable declarations. This is a transient structure that shuttles
13/// declarations between selector matching and inserting into the rule tree, and
14/// therefore we want to avoid heap-allocation where possible.
15///
16/// In measurements on wikipedia, we pretty much never have more than 8 applicable
17/// declarations, so we could consider making this 8 entries instead of 16.
18/// However, it may depend a lot on workload, and stack space is cheap.
19pub type ApplicableDeclarationList<'a> = SmallVec<[ApplicableDeclarationBlock<'a>; 16]>;
20
21/// Blink uses 18 bits to store source order, and does not check overflow [1].
22/// That's a limit that could be reached in realistic webpages, so we use
23/// 24 bits and enforce defined behavior in the overflow case.
24///
25/// Note that right now this restriction could be lifted if wanted (because we
26/// no longer stash the cascade level in the remaining bits), but we keep it in
27/// place in case we come up with a use-case for them, lacking reports of the
28/// current limit being too small.
29///
30/// [1] https://cs.chromium.org/chromium/src/third_party/WebKit/Source/core/css/
31///     RuleSet.h?l=128&rcl=90140ab80b84d0f889abc253410f44ed54ae04f3
32const SOURCE_ORDER_BITS: usize = 24;
33const SOURCE_ORDER_MAX: u32 = (1 << SOURCE_ORDER_BITS) - 1;
34const SOURCE_ORDER_MASK: u32 = SOURCE_ORDER_MAX;
35
36/// The cascade-level+layer order of this declaration.
37#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, PartialEq)]
38pub struct CascadePriority {
39    cascade_level: CascadeLevel,
40    flags: RuleCascadeFlags,
41    layer_order: LayerOrder,
42}
43
44const_assert_eq!(
45    std::mem::size_of::<CascadePriority>(),
46    std::mem::size_of::<u32>()
47);
48
49impl PartialOrd for CascadePriority {
50    #[inline]
51    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
52        Some(self.cmp(other))
53    }
54}
55
56impl Ord for CascadePriority {
57    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
58        self.cascade_level.cmp(&other.cascade_level).then_with(|| {
59            let ordering = self.layer_order.cmp(&other.layer_order);
60            if ordering == std::cmp::Ordering::Equal {
61                return ordering;
62            }
63            // https://drafts.csswg.org/css-cascade-5/#cascade-layering
64            //
65            //     Cascade layers (like declarations) are ordered by order
66            //     of appearance. When comparing declarations that belong to
67            //     different layers, then for normal rules the declaration
68            //     whose cascade layer is last wins, and for important rules
69            //     the declaration whose cascade layer is first wins.
70            //
71            // But the style attribute layer for some reason is special.
72            if self.cascade_level.is_important()
73                && !self.layer_order.is_style_attribute_layer()
74                && !other.layer_order.is_style_attribute_layer()
75            {
76                ordering.reverse()
77            } else {
78                ordering
79            }
80        })
81    }
82}
83
84/// The kind of revert that we're applying.
85#[derive(Clone, Copy, Debug, Eq, PartialEq)]
86pub enum RevertKind {
87    /// revert
88    Origin,
89    /// revert-layer
90    Layer,
91    /// revert-rule
92    Rule,
93}
94
95impl CascadePriority {
96    /// The transitions cascade priority. There's only one transition, and it's unassociated with any layer or so.
97    pub const TRANSITIONS: Self = Self::new(
98        CascadeLevel::new(CascadeOrigin::Transitions),
99        LayerOrder::root(),
100        RuleCascadeFlags::empty(),
101    );
102
103    /// Construct a new CascadePriority for a given (level, order, flags) triple.
104    pub const fn new(
105        cascade_level: CascadeLevel,
106        layer_order: LayerOrder,
107        flags: RuleCascadeFlags,
108    ) -> Self {
109        Self {
110            cascade_level,
111            flags,
112            layer_order,
113        }
114    }
115
116    /// Returns the flags.
117    #[inline]
118    pub fn flags(&self) -> RuleCascadeFlags {
119        self.flags
120    }
121
122    /// Set given flags.
123    #[inline]
124    pub fn set_flags(&mut self, flags: RuleCascadeFlags) {
125        self.flags.insert(flags);
126    }
127
128    /// Returns the layer order.
129    #[inline]
130    pub fn layer_order(&self) -> LayerOrder {
131        self.layer_order
132    }
133
134    /// Returns the cascade level.
135    #[inline]
136    pub fn cascade_level(&self) -> CascadeLevel {
137        self.cascade_level
138    }
139
140    /// Whether this declaration should be allowed if `revert` / `revert-layer` / `revert-rule`
141    /// have been specified on a given origin.
142    ///
143    /// `self` is the priority at which the revert has been specified.
144    pub fn allows_when_reverted(&self, other: &Self, kind: RevertKind) -> bool {
145        match kind {
146            RevertKind::Origin => {
147                other.cascade_level.origin().origin() < self.cascade_level.origin().origin()
148            },
149            RevertKind::Layer => other.unimportant() < self.unimportant(),
150            // Any other declaration for the same property we apply in the cascade needs to come
151            // from another rule effectively.
152            RevertKind::Rule => true,
153        }
154    }
155
156    /// Convert this priority from "important" to "non-important", if needed.
157    pub fn unimportant(&self) -> Self {
158        Self {
159            cascade_level: self.cascade_level.unimportant(),
160            flags: self.flags,
161            layer_order: self.layer_order,
162        }
163    }
164
165    /// Convert this priority from "non-important" to "important", if needed.
166    pub fn important(&self) -> Self {
167        Self {
168            cascade_level: self.cascade_level.important(),
169            flags: self.flags,
170            layer_order: self.layer_order,
171        }
172    }
173
174    /// The same tree, in author origin, at the root layer.
175    pub fn same_tree_author_normal_at_root_layer() -> Self {
176        Self::new(
177            CascadeLevel::same_tree_author_normal(),
178            LayerOrder::root(),
179            RuleCascadeFlags::empty(),
180        )
181    }
182}
183
184/// Proximity to the scope root.
185///
186/// https://drafts.csswg.org/css-cascade-6/#cascade-proximity
187#[derive(Clone, Copy, Debug, Eq, Hash, MallocSizeOf, PartialEq)]
188pub struct ScopeProximity(u16);
189
190impl PartialOrd for ScopeProximity {
191    #[inline]
192    fn partial_cmp(&self, other: &Self) -> Option<std::cmp::Ordering> {
193        Some(self.cmp(other))
194    }
195}
196
197impl Ord for ScopeProximity {
198    fn cmp(&self, other: &Self) -> std::cmp::Ordering {
199        // Lower proximity to scope root wins
200        other.0.cmp(&self.0)
201    }
202}
203
204/// Sacrifice the largest possible value for infinity. This makes the comparison
205/// trivial.
206const PROXIMITY_INFINITY: u16 = u16::MAX;
207
208impl ScopeProximity {
209    /// Construct a new scope proximity.
210    pub fn new(proximity: usize) -> Self {
211        if cfg!(debug_assertions) && proximity >= PROXIMITY_INFINITY as usize {
212            warn!("Proximity out of bounds");
213        }
214        Self(proximity.clamp(0, (PROXIMITY_INFINITY - 1) as usize) as u16)
215    }
216
217    /// Create a scope proximity for delcarations outside of any scope root.
218    pub fn infinity() -> Self {
219        Self(PROXIMITY_INFINITY)
220    }
221
222    /// If the proximity is finite, get the value.
223    pub fn get(&self) -> Option<u16> {
224        (self.0 != PROXIMITY_INFINITY).then_some(self.0)
225    }
226}
227
228/// A property declaration together with its precedence among rules of equal
229/// specificity so that we can sort them.
230///
231/// This represents the declarations in a given declaration block for a given
232/// importance.
233#[derive(Clone, Copy, Debug, MallocSizeOf, PartialEq)]
234pub struct ApplicableDeclarationBlock<'a> {
235    /// The style source.
236    pub source: StyleSourceBorrow<'a>,
237    /// Order of appearance in which this rule appears - Set to 0 if not relevant
238    /// (e.g. Declaration from `style="/*...*/"`, presentation hints, animations
239    /// - See `CascadePriority` instead).
240    source_order: u32,
241    /// The specificity of the selector.
242    pub specificity: u32,
243    /// The proximity to the scope root.
244    pub scope_proximity: ScopeProximity,
245    /// The cascade priority of the rule.
246    pub cascade_priority: CascadePriority,
247}
248
249impl<'a> ApplicableDeclarationBlock<'a> {
250    /// Constructs an applicable declaration block from a given property declaration block borrow
251    /// and importance.
252    #[inline]
253    pub fn from_declarations(
254        source: StyleSourceBorrow<'a>,
255        level: CascadeLevel,
256        layer_order: LayerOrder,
257    ) -> Self {
258        Self::new(
259            source,
260            /* source_order = */ 0,
261            level,
262            /* specificity = */ 0,
263            layer_order,
264            ScopeProximity::infinity(),
265            RuleCascadeFlags::empty(),
266        )
267    }
268
269    /// Constructs an applicable declaration block from the given components.
270    #[inline]
271    pub fn new(
272        source: StyleSourceBorrow<'a>,
273        source_order: u32,
274        level: CascadeLevel,
275        specificity: u32,
276        layer_order: LayerOrder,
277        scope_proximity: ScopeProximity,
278        flags: RuleCascadeFlags,
279    ) -> Self {
280        Self {
281            source,
282            source_order: source_order & SOURCE_ORDER_MASK,
283            specificity,
284            scope_proximity,
285            cascade_priority: CascadePriority::new(level, layer_order, flags),
286        }
287    }
288
289    /// Returns the source order of the block.
290    #[inline]
291    pub fn source_order(&self) -> u32 {
292        self.source_order
293    }
294
295    /// Returns the cascade level of the block.
296    #[inline]
297    pub fn level(&self) -> CascadeLevel {
298        self.cascade_priority.cascade_level()
299    }
300
301    /// Returns the cascade level of the block.
302    #[inline]
303    pub fn layer_order(&self) -> LayerOrder {
304        self.cascade_priority.layer_order()
305    }
306
307    /// Returns the scope proximity of the block.
308    #[inline]
309    pub fn scope_proximity(&self) -> ScopeProximity {
310        self.scope_proximity
311    }
312
313    /// Convenience method to consume self and return the right thing for the
314    /// rule tree to iterate over.
315    #[inline]
316    pub fn for_rule_tree(self) -> (StyleSourceBorrow<'a>, CascadePriority) {
317        (self.source, self.cascade_priority)
318    }
319
320    /// Return the key used to sort applicable declarations.
321    #[inline]
322    pub fn sort_key(&self) -> (LayerOrder, u32, ScopeProximity, u32) {
323        (
324            self.layer_order(),
325            self.specificity,
326            self.scope_proximity(),
327            self.source_order(),
328        )
329    }
330}
331
332// Size of this struct determines sorting and selector-matching performance.
333size_of_test!(ApplicableDeclarationBlock<'static>, 24);