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