Skip to main content

style/
lib.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//! Calculate [specified][specified] and [computed values][computed] from a
6//! tree of DOM nodes and a set of stylesheets.
7//!
8//! [computed]: https://drafts.csswg.org/css-cascade/#computed
9//! [specified]: https://drafts.csswg.org/css-cascade/#specified
10//!
11//! In particular, this crate contains the definitions of supported properties,
12//! the code to parse them into specified values and calculate the computed
13//! values based on the specified values, as well as the code to serialize both
14//! specified and computed values.
15//!
16//! The main entry point is [`recalc_style_at`][recalc_style_at].
17//!
18//! [recalc_style_at]: traversal/fn.recalc_style_at.html
19//!
20//! A list of supported style properties can be found as [docs::supported_properties]
21//!
22//! Major dependencies are the [cssparser][cssparser] and [selectors][selectors]
23//! crates.
24//!
25//! [cssparser]: ../cssparser/index.html
26//! [selectors]: ../selectors/index.html
27
28#![deny(missing_docs)]
29
30// Needed by macros that refer to `$crate::cssparser`.
31#[allow(clippy::single_component_path_imports)]
32pub(crate) use cssparser;
33
34#[macro_use]
35extern crate bitflags;
36#[macro_use]
37#[cfg(feature = "gecko")]
38extern crate gecko_profiler;
39#[cfg(feature = "gecko")]
40#[macro_use]
41pub mod gecko_string_cache;
42#[macro_use]
43extern crate log;
44#[macro_use]
45extern crate serde;
46pub use servo_arc;
47#[cfg(feature = "servo")]
48#[macro_use]
49extern crate stylo_atoms;
50#[macro_use]
51extern crate static_assertions;
52
53#[macro_use]
54mod macros;
55
56mod derives {
57    pub(crate) use derive_more::{Add, AddAssign, Deref, DerefMut, From};
58    pub(crate) use malloc_size_of_derive::MallocSizeOf;
59    pub(crate) use num_derive::FromPrimitive;
60    pub(crate) use style_derive::{
61        Animate, ComputeSquaredDistance, Parse, SpecifiedValueInfo, ToAnimatedValue,
62        ToAnimatedZero, ToComputedValue, ToCss, ToResolvedValue, ToTyped,
63    };
64    pub(crate) use to_shmem_derive::ToShmem;
65}
66
67pub mod applicable_declarations;
68pub mod author_styles;
69pub mod bezier;
70pub mod bloom;
71pub mod color;
72#[path = "properties/computed_value_flags.rs"]
73pub mod computed_value_flags;
74pub mod context;
75pub mod counter_style;
76pub mod custom_properties;
77pub mod custom_properties_map;
78pub mod data;
79pub mod device;
80pub mod dom;
81pub mod dom_apis;
82pub mod driver;
83pub mod error_reporting;
84pub mod font_face;
85pub mod font_metrics;
86#[cfg(feature = "gecko")]
87#[allow(unsafe_code)]
88pub mod gecko_bindings;
89pub mod global_style_data;
90pub mod invalidation;
91#[allow(missing_docs)] // TODO.
92pub mod logical_geometry;
93pub mod matching;
94pub mod media_queries;
95pub mod parallel;
96pub mod parser;
97pub mod piecewise_linear;
98pub mod prefs;
99pub mod properties_and_values;
100#[macro_use]
101pub mod queries;
102pub mod rule_cache;
103pub mod rule_collector;
104pub mod rule_tree;
105pub mod scoped_tls;
106pub mod selector_map;
107pub mod selector_parser;
108pub mod shared_lock;
109pub mod sharing;
110mod simple_buckets_map;
111pub mod str;
112pub mod style_adjuster;
113pub mod style_resolver;
114pub mod stylesheet_set;
115pub mod stylesheets;
116pub mod stylist;
117pub mod substitution;
118pub mod thread_state;
119pub mod traversal;
120pub mod traversal_flags;
121pub mod typed_om;
122pub mod url;
123pub mod use_counters;
124
125#[macro_use]
126#[allow(non_camel_case_types)]
127pub mod values;
128
129#[cfg(all(doc, feature = "servo"))]
130/// Documentation
131pub mod docs {
132    /// The CSS properties supported by the style system.
133    /// Generated from the `properties.mako.rs` template by `build.rs`
134    pub mod supported_properties {
135        #![doc = include_str!(concat!(env!("OUT_DIR"), "/css-properties.html"))]
136    }
137}
138
139#[cfg(feature = "gecko")]
140pub use crate::gecko_string_cache as string_cache;
141#[cfg(feature = "gecko")]
142pub use crate::gecko_string_cache::Atom;
143/// The namespace prefix type for Gecko, which is just an atom.
144#[cfg(feature = "gecko")]
145pub type Prefix = crate::values::AtomIdent;
146/// The local name of an element for Gecko, which is just an atom.
147#[cfg(feature = "gecko")]
148pub type LocalName = crate::values::AtomIdent;
149#[cfg(feature = "gecko")]
150pub use crate::gecko_string_cache::Namespace;
151
152#[cfg(feature = "servo")]
153pub use stylo_atoms::Atom;
154
155#[cfg(feature = "servo")]
156#[allow(missing_docs)]
157pub type LocalName = crate::values::GenericAtomIdent<web_atoms::LocalNameStaticSet>;
158#[cfg(feature = "servo")]
159#[allow(missing_docs)]
160pub type Namespace = crate::values::GenericAtomIdent<web_atoms::NamespaceStaticSet>;
161#[cfg(feature = "servo")]
162#[allow(missing_docs)]
163pub type Prefix = crate::values::GenericAtomIdent<web_atoms::PrefixStaticSet>;
164
165pub use style_traits::arc_slice::ArcSlice;
166pub use style_traits::owned_array::OwnedArray;
167pub use style_traits::owned_slice::OwnedSlice;
168pub use style_traits::owned_str::OwnedStr;
169
170use std::hash::{BuildHasher, Hash};
171
172#[cfg_attr(feature = "servo", macro_use)]
173pub mod properties;
174
175#[cfg(feature = "gecko")]
176#[allow(unsafe_code)]
177pub mod gecko;
178
179// uses a macro from properties
180#[cfg(feature = "servo")]
181#[allow(unsafe_code)]
182pub mod servo;
183#[cfg(feature = "servo")]
184pub use servo::{animation, attr};
185
186macro_rules! reexport_computed_values {
187    ( $( { $name: ident } )+ ) => {
188        /// Types for [computed values][computed].
189        ///
190        /// [computed]: https://drafts.csswg.org/css-cascade/#computed
191        pub mod computed_values {
192            $(
193                pub use crate::properties::longhands::$name::computed_value as $name;
194            )+
195            // Don't use a side-specific name needlessly:
196            pub use crate::properties::longhands::border_top_style::computed_value as border_style;
197        }
198    }
199}
200longhand_properties_idents!(reexport_computed_values);
201#[cfg(feature = "gecko")]
202use crate::gecko_string_cache::WeakAtom;
203#[cfg(feature = "servo")]
204use stylo_atoms::Atom as WeakAtom;
205
206/// Extension methods for selectors::attr::CaseSensitivity
207pub trait CaseSensitivityExt {
208    /// Return whether two atoms compare equal according to this case sensitivity.
209    fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool;
210}
211
212impl CaseSensitivityExt for selectors::attr::CaseSensitivity {
213    #[inline]
214    fn eq_atom(self, a: &WeakAtom, b: &WeakAtom) -> bool {
215        match self {
216            selectors::attr::CaseSensitivity::CaseSensitive => a == b,
217            selectors::attr::CaseSensitivity::AsciiCaseInsensitive => a.eq_ignore_ascii_case(b),
218        }
219    }
220}
221
222/// A trait pretty much similar to num_traits::Zero, but without the need of
223/// implementing `Add`.
224pub trait Zero {
225    /// Returns the zero value.
226    fn zero() -> Self;
227
228    /// Returns whether this value is zero.
229    fn is_zero(&self) -> bool;
230}
231
232impl<T> Zero for T
233where
234    T: num_traits::Zero,
235{
236    fn zero() -> Self {
237        <Self as num_traits::Zero>::zero()
238    }
239
240    fn is_zero(&self) -> bool {
241        <Self as num_traits::Zero>::is_zero(self)
242    }
243}
244
245/// A trait implementing a function to tell if the number is zero without a percent
246pub trait ZeroNoPercent {
247    /// So, `0px` should return `true`, but `0%` or `1px` should return `false`
248    fn is_zero_no_percent(&self) -> bool;
249}
250
251/// A trait pretty much similar to num_traits::One, but without the need of
252/// implementing `Mul`.
253pub trait One {
254    /// Reutrns the one value.
255    fn one() -> Self;
256
257    /// Returns whether this value is one.
258    fn is_one(&self) -> bool;
259}
260
261impl<T> One for T
262where
263    T: num_traits::One + PartialEq,
264{
265    fn one() -> Self {
266        <Self as num_traits::One>::one()
267    }
268
269    fn is_one(&self) -> bool {
270        *self == One::one()
271    }
272}
273
274/// An allocation error.
275///
276/// TODO(emilio): Would be nice to have more information here, or for SmallVec
277/// to return the standard error type (and then we can just return that).
278///
279/// But given we use these mostly to bail out and ignore them, it's not a big
280/// deal.
281#[derive(Debug)]
282pub struct AllocErr;
283
284impl From<smallvec::CollectionAllocErr> for AllocErr {
285    #[inline]
286    fn from(_: smallvec::CollectionAllocErr) -> Self {
287        Self
288    }
289}
290
291impl From<std::collections::TryReserveError> for AllocErr {
292    #[inline]
293    fn from(_: std::collections::TryReserveError) -> Self {
294        Self
295    }
296}
297
298impl From<hashbrown::TryReserveError> for AllocErr {
299    #[inline]
300    fn from(_: hashbrown::TryReserveError) -> Self {
301        Self
302    }
303}
304
305/// A hash map using the Fx hasher.
306pub type FxHashMap<K, V> = hashbrown::HashMap<K, V, rustc_hash::FxBuildHasher>;
307
308/// A hash set using the Fx hasher.
309pub type FxHashSet<T> = hashbrown::HashSet<T, rustc_hash::FxBuildHasher>;
310
311/// Shrink the capacity of the collection if needed.
312pub(crate) trait ShrinkIfNeeded {
313    fn shrink_if_needed(&mut self);
314}
315
316/// We shrink the capacity of a collection if we're wasting more than a 25% of
317/// its capacity, and if the collection is arbitrarily big enough
318/// (>= CAPACITY_THRESHOLD entries).
319#[inline]
320fn should_shrink(len: usize, capacity: usize) -> bool {
321    const CAPACITY_THRESHOLD: usize = 64;
322    capacity >= CAPACITY_THRESHOLD && len + capacity / 4 < capacity
323}
324
325impl<K, V, H> ShrinkIfNeeded for hashbrown::HashMap<K, V, H>
326where
327    K: Eq + Hash,
328    H: BuildHasher,
329{
330    fn shrink_if_needed(&mut self) {
331        if should_shrink(self.len(), self.capacity()) {
332            self.shrink_to_fit();
333        }
334    }
335}
336
337impl<T, H> ShrinkIfNeeded for hashbrown::HashSet<T, H>
338where
339    T: Eq + Hash,
340    H: BuildHasher,
341{
342    fn shrink_if_needed(&mut self) {
343        if should_shrink(self.len(), self.capacity()) {
344            self.shrink_to_fit();
345        }
346    }
347}
348
349// TODO(emilio): Measure and see if we're wasting a lot of memory on Vec /
350// SmallVec, and if so consider shrinking those as well.