style/
selector_parser.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//! The pseudo-classes and pseudo-elements supported by the style system.
6
7#![deny(missing_docs)]
8
9use crate::stylesheets::{Namespaces, Origin, UrlExtraData};
10use crate::values::serialize_atom_identifier;
11use crate::Atom;
12use cssparser::{Parser as CssParser, ParserInput};
13use dom::ElementState;
14use selectors::parser::{ParseRelative, SelectorList};
15use std::fmt::{self, Debug, Write};
16use style_traits::{CssWriter, ParseError, ToCss};
17
18/// A convenient alias for the type that represents an attribute value used for
19/// selector parser implementation.
20pub type AttrValue = <SelectorImpl as ::selectors::SelectorImpl>::AttrValue;
21
22#[cfg(feature = "servo")]
23pub use crate::servo::selector_parser::*;
24
25#[cfg(feature = "gecko")]
26pub use crate::gecko::selector_parser::*;
27
28#[cfg(feature = "servo")]
29pub use crate::servo::selector_parser::ServoElementSnapshot as Snapshot;
30
31#[cfg(feature = "gecko")]
32pub use crate::gecko::snapshot::GeckoElementSnapshot as Snapshot;
33
34#[cfg(feature = "servo")]
35pub use crate::servo::restyle_damage::ServoRestyleDamage as RestyleDamage;
36
37#[cfg(feature = "gecko")]
38pub use crate::gecko::restyle_damage::GeckoRestyleDamage as RestyleDamage;
39
40/// Servo's selector parser.
41#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
42pub struct SelectorParser<'a> {
43    /// The origin of the stylesheet we're parsing.
44    pub stylesheet_origin: Origin,
45    /// The namespace set of the stylesheet.
46    pub namespaces: &'a Namespaces,
47    /// The extra URL data of the stylesheet, which is used to look up
48    /// whether we are parsing a chrome:// URL style sheet.
49    pub url_data: &'a UrlExtraData,
50    /// Whether we're parsing selectors for `@supports`
51    pub for_supports_rule: bool,
52}
53
54impl<'a> SelectorParser<'a> {
55    /// Parse a selector list with an author origin and without taking into
56    /// account namespaces.
57    ///
58    /// This is used for some DOM APIs like `querySelector`.
59    pub fn parse_author_origin_no_namespace<'i>(
60        input: &'i str,
61        url_data: &UrlExtraData,
62    ) -> Result<SelectorList<SelectorImpl>, ParseError<'i>> {
63        let namespaces = Namespaces::default();
64        let parser = SelectorParser {
65            stylesheet_origin: Origin::Author,
66            namespaces: &namespaces,
67            url_data,
68            for_supports_rule: false,
69        };
70        let mut input = ParserInput::new(input);
71        SelectorList::parse(&parser, &mut CssParser::new(&mut input), ParseRelative::No)
72    }
73
74    /// Whether we're parsing selectors in a user-agent stylesheet.
75    pub fn in_user_agent_stylesheet(&self) -> bool {
76        matches!(self.stylesheet_origin, Origin::UserAgent)
77    }
78
79    /// Whether we're parsing selectors in a stylesheet that has chrome
80    /// privilege.
81    pub fn chrome_rules_enabled(&self) -> bool {
82        self.url_data.chrome_rules_enabled() || self.stylesheet_origin == Origin::User
83    }
84}
85
86/// This enumeration determines how a pseudo-element cascades.
87#[derive(Clone, Debug, Eq, PartialEq)]
88pub enum PseudoElementCascadeType {
89    /// Eagerly cascaded pseudo-elements are "normal" pseudo-elements (i.e.
90    /// `::before` and `::after`). They inherit styles normally as another
91    /// selector would do, and they're computed as part of the cascade.
92    ///
93    /// These kind of pseudo-elements require more up-front computation and
94    /// storage and thus should used for public pseudo-elements that can be used
95    /// on many element types (such as `::before` and `::after`).
96    Eager,
97    /// Lazy pseudo-elements are affected by selector matching, but they're only
98    /// computed when needed, and not before. They're useful for general
99    /// pseudo-elements that are not very common or that do not apply to many
100    /// elements. For instance in Servo this is used for `::backdrop` and
101    /// `::marker`.
102    Lazy,
103    /// Precomputed pseudo-elements skip the cascade process entirely, mostly as
104    /// an optimisation since they are private pseudo-elements (like
105    /// `::-servo-details-content`).
106    ///
107    /// This pseudo-elements are resolved on the fly using *only* global rules
108    /// (rules of the form `*|*`), and applying them to the parent style so are
109    /// mainly useful for user-agent stylesheets.
110    Precomputed,
111}
112
113/// A per-pseudo map, from a given pseudo to a `T`.
114#[derive(Clone, MallocSizeOf)]
115pub struct PerPseudoElementMap<T> {
116    sparse: [i8; PSEUDO_COUNT],
117    dense: Vec<T>,
118}
119
120impl<T> Default for PerPseudoElementMap<T> {
121    fn default() -> Self {
122        Self {
123            dense: Vec::new(),
124            sparse: [const { -1 }; PSEUDO_COUNT],
125        }
126    }
127}
128
129impl<T> Debug for PerPseudoElementMap<T>
130where
131    T: Debug,
132{
133    fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
134        f.write_char('[')?;
135        for idx in 0..=PSEUDO_COUNT {
136            if idx > 0 {
137                f.write_str(", ")?;
138            }
139            debug_assert!(self.sparse.get(idx).is_some());
140            let i = self.sparse[idx];
141            if i < 0 {
142                None::<T>.fmt(f)?;
143            } else {
144                Some(&self.dense[i as usize]).fmt(f)?;
145            }
146        }
147        f.write_char(']')
148    }
149}
150
151impl<T> PerPseudoElementMap<T> {
152    /// Get an entry in the map.
153    pub fn get(&self, pseudo: &PseudoElement) -> Option<&T> {
154        let idx = pseudo.index();
155        debug_assert!(self.sparse.get(idx).is_some());
156        let i = self.sparse[idx];
157        if i < 0 {
158            None
159        } else {
160            Some(&self.dense[i as usize])
161        }
162    }
163
164    /// Clear this enumerated array.
165    pub fn clear(&mut self) {
166        self.dense.clear();
167        self.sparse.fill(-1);
168    }
169
170    /// Set an entry value.
171    ///
172    /// Returns an error if the element is not a simple pseudo.
173    pub fn set(&mut self, pseudo: &PseudoElement, value: T) {
174        let idx = pseudo.index();
175        let i = self.sparse[idx];
176        if i < 0 {
177            let i = self.dense.len() as i8;
178            self.dense.push(value);
179            self.sparse[idx] = i
180        } else {
181            self.dense[i as usize] = value
182        }
183    }
184
185    /// Get an entry for `pseudo`, or create it with calling `f`.
186    pub fn get_or_insert_with<F>(&mut self, pseudo: &PseudoElement, f: F) -> &mut T
187    where
188        F: FnOnce() -> T,
189    {
190        let idx = pseudo.index();
191        let mut i = self.sparse[idx];
192        if i < 0 {
193            i = self.dense.len() as i8;
194            debug_assert!(self.dense.len() < PSEUDO_COUNT);
195            self.dense.push(f());
196            self.sparse[idx] = i;
197        }
198        debug_assert!(self.dense.get(i as usize).is_some());
199        &mut self.dense[i as usize]
200    }
201
202    /// Get an iterator for the entries.
203    pub fn iter(&self) -> impl Iterator<Item = &T> {
204        self.dense.iter()
205    }
206
207    /// Get a mutable iterator for the entries.
208    pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> {
209        self.dense.iter_mut()
210    }
211}
212
213/// Values for the :dir() pseudo class
214///
215/// "ltr" and "rtl" values are normalized to lowercase.
216#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, ToShmem)]
217pub struct Direction(pub Atom);
218
219/// Horizontal values for the :dir() pseudo class
220#[derive(Clone, Debug, Eq, PartialEq)]
221pub enum HorizontalDirection {
222    /// :dir(ltr)
223    Ltr,
224    /// :dir(rtl)
225    Rtl,
226}
227
228impl Direction {
229    /// Parse a direction value.
230    pub fn parse<'i, 't>(parser: &mut CssParser<'i, 't>) -> Result<Self, ParseError<'i>> {
231        let ident = parser.expect_ident()?;
232        Ok(Direction(match_ignore_ascii_case! { &ident,
233            "rtl" => atom!("rtl"),
234            "ltr" => atom!("ltr"),
235            _ => Atom::from(ident.as_ref()),
236        }))
237    }
238
239    /// Convert this Direction into a HorizontalDirection, if applicable
240    pub fn as_horizontal_direction(&self) -> Option<HorizontalDirection> {
241        if self.0 == atom!("ltr") {
242            Some(HorizontalDirection::Ltr)
243        } else if self.0 == atom!("rtl") {
244            Some(HorizontalDirection::Rtl)
245        } else {
246            None
247        }
248    }
249
250    /// Gets the element state relevant to this :dir() selector.
251    pub fn element_state(&self) -> ElementState {
252        match self.as_horizontal_direction() {
253            Some(HorizontalDirection::Ltr) => ElementState::LTR,
254            Some(HorizontalDirection::Rtl) => ElementState::RTL,
255            None => ElementState::empty(),
256        }
257    }
258}
259
260impl ToCss for Direction {
261    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
262    where
263        W: Write,
264    {
265        serialize_atom_identifier(&self.0, dest)
266    }
267}
268
269#[cfg(test)]
270mod tests {
271    use super::*;
272
273    #[test]
274    fn can_build_and_set_arbitrary_index() {
275        let mut map = <PerPseudoElementMap<i32>>::default();
276        assert_eq!(map.get(&PseudoElement::After), None);
277        map.set(&PseudoElement::After, 3);
278        assert_eq!(map.get(&PseudoElement::After), Some(3).as_ref());
279
280        assert_eq!(map.get(&PseudoElement::RubyText), None);
281        map.set(&PseudoElement::RubyText, 8);
282        assert_eq!(map.get(&PseudoElement::RubyText), Some(8).as_ref());
283
284        assert_eq!(
285            map.get_or_insert_with(&PseudoElement::RubyText, || { 10 }),
286            &8
287        );
288        map.set(&PseudoElement::RubyText, 9);
289        assert_eq!(map.get(&PseudoElement::RubyText), Some(9).as_ref());
290
291        assert_eq!(
292            map.get_or_insert_with(&PseudoElement::FirstLine, || { 10 }),
293            &10
294        );
295        assert_eq!(map.get(&PseudoElement::FirstLine), Some(10).as_ref());
296    }
297
298    #[test]
299    fn can_iter() {
300        let mut map = <PerPseudoElementMap<i32>>::default();
301        map.set(&PseudoElement::After, 3);
302        map.set(&PseudoElement::RubyText, 8);
303        assert_eq!(map.iter().cloned().collect::<Vec<_>>(), vec![3, 8]);
304    }
305}