1#![deny(missing_docs)]
8
9use crate::derives::*;
10use crate::stylesheets::{Namespaces, Origin, UrlExtraData};
11use crate::values::serialize_atom_identifier;
12use crate::Atom;
13use cssparser::{match_ignore_ascii_case, Parser as CssParser};
14use dom::ElementState;
15use selectors::parser::{ParseRelative, SelectorList};
16use std::fmt::{self, Debug, Write};
17use style_traits::{CssWriter, ParseError, ToCss};
18
19pub type AttrValue = <SelectorImpl as ::selectors::SelectorImpl>::AttrValue;
22
23#[cfg(feature = "servo")]
24pub use crate::servo::selector_parser::*;
25
26#[cfg(feature = "gecko")]
27pub use crate::gecko::selector_parser::*;
28
29#[cfg(feature = "servo")]
30pub use crate::servo::selector_parser::ServoElementSnapshot as Snapshot;
31
32#[cfg(feature = "gecko")]
33pub use crate::gecko::snapshot::GeckoElementSnapshot as Snapshot;
34
35#[cfg(feature = "servo")]
36pub use crate::servo::restyle_damage::ServoRestyleDamage as RestyleDamage;
37
38#[cfg(feature = "gecko")]
39pub use crate::gecko::restyle_damage::GeckoRestyleDamage as RestyleDamage;
40
41#[derive(MallocSizeOf)]
43pub struct SelectorParser<'a> {
44 pub stylesheet_origin: Origin,
46 pub namespaces: &'a Namespaces,
48 pub url_data: &'a UrlExtraData,
51 pub for_supports_rule: bool,
53}
54
55impl<'a> SelectorParser<'a> {
56 pub fn parse_author_origin_no_namespace(
61 input: &str,
62 url_data: &UrlExtraData,
63 ) -> Result<SelectorList<SelectorImpl>, ParseError> {
64 let namespaces = Namespaces::default();
65 let parser = SelectorParser {
66 stylesheet_origin: Origin::Author,
67 namespaces: &namespaces,
68 url_data,
69 for_supports_rule: false,
70 };
71 SelectorList::parse(&parser, &mut CssParser::new(input), ParseRelative::No)
72 }
73
74 pub fn in_user_agent_stylesheet(&self) -> bool {
76 matches!(self.stylesheet_origin, Origin::UserAgent)
77 }
78
79 pub fn chrome_rules_enabled(&self) -> bool {
82 self.url_data.chrome_rules_enabled() || self.stylesheet_origin == Origin::User
83 }
84}
85
86#[derive(Clone, Debug, Eq, PartialEq)]
88pub enum PseudoElementCascadeType {
89 Eager,
97 Lazy,
103 Precomputed,
111}
112
113#[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 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 pub fn clear(&mut self) {
166 self.dense.clear();
167 self.sparse.fill(-1);
168 }
169
170 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 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 pub fn iter(&self) -> impl Iterator<Item = &T> {
204 self.dense.iter()
205 }
206
207 pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> {
209 self.dense.iter_mut()
210 }
211}
212
213#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, ToShmem)]
217pub struct Direction(pub Atom);
218
219#[derive(Clone, Debug, Eq, PartialEq)]
221pub enum HorizontalDirection {
222 Ltr,
224 Rtl,
226}
227
228impl Direction {
229 pub fn parse(parser: &mut CssParser) -> Result<Self, ParseError> {
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 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 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::Marker), None);
281 map.set(&PseudoElement::Marker, 8);
282 assert_eq!(map.get(&PseudoElement::Marker), Some(8).as_ref());
283
284 assert_eq!(
285 map.get_or_insert_with(&PseudoElement::Marker, || { 10 }),
286 &8
287 );
288 map.set(&PseudoElement::Marker, 9);
289 assert_eq!(map.get(&PseudoElement::Marker), Some(9).as_ref());
290
291 assert_eq!(
292 map.get_or_insert_with(&PseudoElement::FirstLetter, || { 10 }),
293 &10
294 );
295 assert_eq!(map.get(&PseudoElement::FirstLetter), 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::Marker, 8);
303 assert_eq!(map.iter().cloned().collect::<Vec<_>>(), vec![3, 8]);
304 }
305}