1#![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
18pub 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#[cfg_attr(feature = "servo", derive(MallocSizeOf))]
42pub struct SelectorParser<'a> {
43 pub stylesheet_origin: Origin,
45 pub namespaces: &'a Namespaces,
47 pub url_data: &'a UrlExtraData,
50 pub for_supports_rule: bool,
52}
53
54impl<'a> SelectorParser<'a> {
55 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 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<'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 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::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}