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, ParserInput};
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#[cfg_attr(feature = "servo", 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<'i>(
61 input: &'i str,
62 url_data: &UrlExtraData,
63 ) -> Result<SelectorList<SelectorImpl>, ParseError<'i>> {
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 let mut input = ParserInput::new(input);
72 SelectorList::parse(&parser, &mut CssParser::new(&mut input), ParseRelative::No)
73 }
74
75 pub fn in_user_agent_stylesheet(&self) -> bool {
77 matches!(self.stylesheet_origin, Origin::UserAgent)
78 }
79
80 pub fn chrome_rules_enabled(&self) -> bool {
83 self.url_data.chrome_rules_enabled() || self.stylesheet_origin == Origin::User
84 }
85}
86
87#[derive(Clone, Debug, Eq, PartialEq)]
89pub enum PseudoElementCascadeType {
90 Eager,
98 Lazy,
104 Precomputed,
112}
113
114#[derive(Clone, MallocSizeOf)]
116pub struct PerPseudoElementMap<T> {
117 sparse: [i8; PSEUDO_COUNT],
118 dense: Vec<T>,
119}
120
121impl<T> Default for PerPseudoElementMap<T> {
122 fn default() -> Self {
123 Self {
124 dense: Vec::new(),
125 sparse: [const { -1 }; PSEUDO_COUNT],
126 }
127 }
128}
129
130impl<T> Debug for PerPseudoElementMap<T>
131where
132 T: Debug,
133{
134 fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
135 f.write_char('[')?;
136 for idx in 0..=PSEUDO_COUNT {
137 if idx > 0 {
138 f.write_str(", ")?;
139 }
140 debug_assert!(self.sparse.get(idx).is_some());
141 let i = self.sparse[idx];
142 if i < 0 {
143 None::<T>.fmt(f)?;
144 } else {
145 Some(&self.dense[i as usize]).fmt(f)?;
146 }
147 }
148 f.write_char(']')
149 }
150}
151
152impl<T> PerPseudoElementMap<T> {
153 pub fn get(&self, pseudo: &PseudoElement) -> Option<&T> {
155 let idx = pseudo.index();
156 debug_assert!(self.sparse.get(idx).is_some());
157 let i = self.sparse[idx];
158 if i < 0 {
159 None
160 } else {
161 Some(&self.dense[i as usize])
162 }
163 }
164
165 pub fn clear(&mut self) {
167 self.dense.clear();
168 self.sparse.fill(-1);
169 }
170
171 pub fn set(&mut self, pseudo: &PseudoElement, value: T) {
175 let idx = pseudo.index();
176 let i = self.sparse[idx];
177 if i < 0 {
178 let i = self.dense.len() as i8;
179 self.dense.push(value);
180 self.sparse[idx] = i
181 } else {
182 self.dense[i as usize] = value
183 }
184 }
185
186 pub fn get_or_insert_with<F>(&mut self, pseudo: &PseudoElement, f: F) -> &mut T
188 where
189 F: FnOnce() -> T,
190 {
191 let idx = pseudo.index();
192 let mut i = self.sparse[idx];
193 if i < 0 {
194 i = self.dense.len() as i8;
195 debug_assert!(self.dense.len() < PSEUDO_COUNT);
196 self.dense.push(f());
197 self.sparse[idx] = i;
198 }
199 debug_assert!(self.dense.get(i as usize).is_some());
200 &mut self.dense[i as usize]
201 }
202
203 pub fn iter(&self) -> impl Iterator<Item = &T> {
205 self.dense.iter()
206 }
207
208 pub fn iter_mut(&mut self) -> impl Iterator<Item = &mut T> {
210 self.dense.iter_mut()
211 }
212}
213
214#[derive(Clone, Debug, Eq, MallocSizeOf, PartialEq, ToShmem)]
218pub struct Direction(pub Atom);
219
220#[derive(Clone, Debug, Eq, PartialEq)]
222pub enum HorizontalDirection {
223 Ltr,
225 Rtl,
227}
228
229impl Direction {
230 pub fn parse<'i, 't>(parser: &mut CssParser<'i, 't>) -> Result<Self, ParseError<'i>> {
232 let ident = parser.expect_ident()?;
233 Ok(Direction(match_ignore_ascii_case! { &ident,
234 "rtl" => atom!("rtl"),
235 "ltr" => atom!("ltr"),
236 _ => Atom::from(ident.as_ref()),
237 }))
238 }
239
240 pub fn as_horizontal_direction(&self) -> Option<HorizontalDirection> {
242 if self.0 == atom!("ltr") {
243 Some(HorizontalDirection::Ltr)
244 } else if self.0 == atom!("rtl") {
245 Some(HorizontalDirection::Rtl)
246 } else {
247 None
248 }
249 }
250
251 pub fn element_state(&self) -> ElementState {
253 match self.as_horizontal_direction() {
254 Some(HorizontalDirection::Ltr) => ElementState::LTR,
255 Some(HorizontalDirection::Rtl) => ElementState::RTL,
256 None => ElementState::empty(),
257 }
258 }
259}
260
261impl ToCss for Direction {
262 fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
263 where
264 W: Write,
265 {
266 serialize_atom_identifier(&self.0, dest)
267 }
268}
269
270#[cfg(test)]
271mod tests {
272 use super::*;
273
274 #[test]
275 fn can_build_and_set_arbitrary_index() {
276 let mut map = <PerPseudoElementMap<i32>>::default();
277 assert_eq!(map.get(&PseudoElement::After), None);
278 map.set(&PseudoElement::After, 3);
279 assert_eq!(map.get(&PseudoElement::After), Some(3).as_ref());
280
281 assert_eq!(map.get(&PseudoElement::RubyText), None);
282 map.set(&PseudoElement::RubyText, 8);
283 assert_eq!(map.get(&PseudoElement::RubyText), Some(8).as_ref());
284
285 assert_eq!(
286 map.get_or_insert_with(&PseudoElement::RubyText, || { 10 }),
287 &8
288 );
289 map.set(&PseudoElement::RubyText, 9);
290 assert_eq!(map.get(&PseudoElement::RubyText), Some(9).as_ref());
291
292 assert_eq!(
293 map.get_or_insert_with(&PseudoElement::FirstLine, || { 10 }),
294 &10
295 );
296 assert_eq!(map.get(&PseudoElement::FirstLine), Some(10).as_ref());
297 }
298
299 #[test]
300 fn can_iter() {
301 let mut map = <PerPseudoElementMap<i32>>::default();
302 map.set(&PseudoElement::After, 3);
303 map.set(&PseudoElement::RubyText, 8);
304 assert_eq!(map.iter().cloned().collect::<Vec<_>>(), vec![3, 8]);
305 }
306}