Skip to main content

rspack_lightningcss_selectors/
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
5use crate::attr::{AttrSelectorOperator, AttrSelectorWithOptionalNamespace};
6use crate::attr::{NamespaceConstraint, ParsedAttrSelectorOperation};
7use crate::attr::{ParsedCaseSensitivity, SELECTOR_WHITESPACE};
8use crate::bloom::BLOOM_HASH_MASK;
9use crate::builder::{SelectorBuilder, SelectorFlags, SpecificityAndFlags};
10use crate::context::QuirksMode;
11use crate::sink::Push;
12pub use crate::visitor::SelectorVisitor;
13use cssparser::parse_nth;
14use cssparser::{BasicParseError, BasicParseErrorKind, ParseError, ParseErrorKind};
15use cssparser::{CowRcStr, Delimiter, SourceLocation};
16use cssparser::{Parser as CssParser, ToCss, Token};
17use precomputed_hash::PrecomputedHash;
18use smallvec::{smallvec, SmallVec};
19use std::borrow::Borrow;
20use std::fmt::{self, Debug};
21use std::iter::Rev;
22use std::slice;
23
24/// A trait that represents a pseudo-element.
25pub trait PseudoElement<'i>: Sized + ToCss {
26  /// The `SelectorImpl` this pseudo-element is used for.
27  type Impl: SelectorImpl<'i>;
28
29  /// Whether the pseudo-element supports a given state selector to the right
30  /// of it.
31  fn accepts_state_pseudo_classes(&self) -> bool {
32    false
33  }
34
35  /// Whether this pseudo-element is valid after a ::slotted(..) pseudo.
36  fn valid_after_slotted(&self) -> bool {
37    false
38  }
39
40  fn is_webkit_scrollbar(&self) -> bool {
41    false
42  }
43
44  fn is_view_transition(&self) -> bool {
45    false
46  }
47
48  fn is_unknown(&self) -> bool {
49    false
50  }
51}
52
53/// A trait that represents a pseudo-class.
54pub trait NonTSPseudoClass<'i>: Sized + ToCss {
55  /// The `SelectorImpl` this pseudo-element is used for.
56  type Impl: SelectorImpl<'i>;
57
58  /// Whether this pseudo-class is :active or :hover.
59  fn is_active_or_hover(&self) -> bool;
60
61  /// Whether this pseudo-class belongs to:
62  ///
63  /// https://drafts.csswg.org/selectors-4/#useraction-pseudos
64  fn is_user_action_state(&self) -> bool;
65
66  fn is_valid_before_webkit_scrollbar(&self) -> bool {
67    true
68  }
69
70  fn is_valid_after_webkit_scrollbar(&self) -> bool {
71    false
72  }
73
74  fn visit<V>(&self, _visitor: &mut V) -> bool
75  where
76    V: SelectorVisitor<'i, Impl = Self::Impl>,
77  {
78    true
79  }
80}
81
82/// Returns a Cow::Borrowed if `s` is already ASCII lowercase, and a
83/// Cow::Owned if `s` had to be converted into ASCII lowercase.
84fn to_ascii_lowercase<'i>(s: CowRcStr<'i>) -> CowRcStr<'i> {
85  if let Some(first_uppercase) = s.bytes().position(|byte: u8| byte.is_ascii_uppercase()) {
86    let mut string = s.to_string();
87    string[first_uppercase..].make_ascii_lowercase();
88    string.into()
89  } else {
90    s
91  }
92}
93
94bitflags! {
95    /// Flags that indicate at which point of parsing a selector are we.
96    #[derive(PartialEq, Eq, Clone, Copy)]
97    struct SelectorParsingState: u16 {
98        /// Whether we should avoid adding default namespaces to selectors that
99        /// aren't type or universal selectors.
100        const SKIP_DEFAULT_NAMESPACE = 1 << 0;
101
102        /// Whether we've parsed a ::slotted() pseudo-element already.
103        ///
104        /// If so, then we can only parse a subset of pseudo-elements, and
105        /// whatever comes after them if so.
106        const AFTER_SLOTTED = 1 << 1;
107        /// Whether we've parsed a ::part() pseudo-element already.
108        ///
109        /// If so, then we can only parse a subset of pseudo-elements, and
110        /// whatever comes after them if so.
111        const AFTER_PART = 1 << 2;
112        /// Whether we've parsed a pseudo-element (as in, an
113        /// `Impl::PseudoElement` thus not accounting for `::slotted` or
114        /// `::part`) already.
115        ///
116        /// If so, then other pseudo-elements and most other selectors are
117        /// disallowed.
118        const AFTER_PSEUDO_ELEMENT = 1 << 3;
119        /// Whether we've parsed a non-stateful pseudo-element (again, as-in
120        /// `Impl::PseudoElement`) already. If so, then other pseudo-classes are
121        /// disallowed. If this flag is set, `AFTER_PSEUDO_ELEMENT` must be set
122        /// as well.
123        const AFTER_NON_STATEFUL_PSEUDO_ELEMENT = 1 << 4;
124
125        /// Whether we are after any of the pseudo-like things.
126        const AFTER_PSEUDO = Self::AFTER_PART.bits() | Self::AFTER_SLOTTED.bits() | Self::AFTER_PSEUDO_ELEMENT.bits();
127
128        /// Whether we explicitly disallow combinators.
129        const DISALLOW_COMBINATORS = 1 << 5;
130
131        /// Whether we explicitly disallow pseudo-element-like things.
132        const DISALLOW_PSEUDOS = 1 << 6;
133
134        /// Whether we have seen a nesting selector.
135        const AFTER_NESTING = 1 << 7;
136
137        const AFTER_WEBKIT_SCROLLBAR = 1 << 8;
138        const AFTER_VIEW_TRANSITION = 1 << 9;
139        const AFTER_UNKNOWN_PSEUDO_ELEMENT = 1 << 10;
140    }
141}
142
143impl SelectorParsingState {
144  #[inline]
145  fn allows_pseudos(self) -> bool {
146    // NOTE(emilio): We allow pseudos after ::part and such.
147    !self.intersects(Self::AFTER_PSEUDO_ELEMENT | Self::DISALLOW_PSEUDOS)
148  }
149
150  #[inline]
151  fn allows_slotted(self) -> bool {
152    !self.intersects(Self::AFTER_PSEUDO | Self::DISALLOW_PSEUDOS)
153  }
154
155  #[inline]
156  fn allows_part(self) -> bool {
157    !self.intersects(Self::AFTER_PSEUDO | Self::DISALLOW_PSEUDOS)
158  }
159
160  // TODO(emilio): Maybe some of these should be allowed, but this gets us on
161  // the safe side for now, matching previous behavior. Gotta be careful with
162  // the ones like :-moz-any, which allow nested selectors but don't carry the
163  // state, and so on.
164  #[inline]
165  fn allows_custom_functional_pseudo_classes(self) -> bool {
166    !self.intersects(Self::AFTER_PSEUDO)
167  }
168
169  #[inline]
170  fn allows_non_functional_pseudo_classes(self) -> bool {
171    !self.intersects(Self::AFTER_SLOTTED | Self::AFTER_NON_STATEFUL_PSEUDO_ELEMENT)
172  }
173
174  #[inline]
175  fn allows_tree_structural_pseudo_classes(self) -> bool {
176    !self.intersects(Self::AFTER_PSEUDO)
177  }
178
179  #[inline]
180  fn allows_combinators(self) -> bool {
181    !self.intersects(Self::DISALLOW_COMBINATORS)
182  }
183}
184
185pub type SelectorParseError<'i> = ParseError<'i, SelectorParseErrorKind<'i>>;
186
187#[derive(Clone, Debug, PartialEq)]
188pub enum SelectorParseErrorKind<'i> {
189  NoQualifiedNameInAttributeSelector(Token<'i>),
190  EmptySelector,
191  DanglingCombinator,
192  InvalidPseudoClassBeforeWebKitScrollbar,
193  InvalidPseudoClassAfterWebKitScrollbar,
194  InvalidPseudoClassAfterPseudoElement,
195  InvalidState,
196  MissingNestingSelector,
197  MissingNestingPrefix,
198  UnexpectedTokenInAttributeSelector(Token<'i>),
199  PseudoElementExpectedIdent(Token<'i>),
200  UnsupportedPseudoElement(CowRcStr<'i>),
201  UnsupportedPseudoClass(CowRcStr<'i>),
202  AmbiguousCssModuleClass(CowRcStr<'i>),
203  UnexpectedIdent(CowRcStr<'i>),
204  ExpectedNamespace(CowRcStr<'i>),
205  ExpectedBarInAttr(Token<'i>),
206  BadValueInAttr(Token<'i>),
207  InvalidQualNameInAttr(Token<'i>),
208  ExplicitNamespaceUnexpectedToken(Token<'i>),
209  ClassNeedsIdent(Token<'i>),
210  UnexpectedSelectorAfterPseudoElement(Token<'i>),
211}
212
213macro_rules! with_all_bounds {
214    (
215        [ $( $InSelector: tt )* ]
216        [ $( $CommonBounds: tt )* ]
217        [ $( $FromStr: tt )* ]
218    ) => {
219        /// This trait allows to define the parser implementation in regards
220        /// of pseudo-classes/elements
221        ///
222        /// NB: We need Clone so that we can derive(Clone) on struct with that
223        /// are parameterized on SelectorImpl. See
224        /// <https://github.com/rust-lang/rust/issues/26925>
225        pub trait SelectorImpl<'i>: Clone + Debug + Sized + 'static {
226            type ExtraMatchingData: Sized + Default + 'static;
227            type AttrValue: $($InSelector)*;
228            type Identifier: $($InSelector)*;
229            type LocalName: $($InSelector)* + Borrow<Self::BorrowedLocalName>;
230            type NamespaceUrl: $($CommonBounds)* + $($FromStr)* + Default + Borrow<Self::BorrowedNamespaceUrl>;
231            type NamespacePrefix: $($InSelector)* + Default;
232            type BorrowedNamespaceUrl: ?Sized + Eq;
233            type BorrowedLocalName: ?Sized + Eq;
234
235            /// non tree-structural pseudo-classes
236            /// (see: https://drafts.csswg.org/selectors/#structural-pseudos)
237            type NonTSPseudoClass: $($CommonBounds)* + NonTSPseudoClass<'i, Impl = Self>;
238            type VendorPrefix: Sized + Eq + $($CommonBounds)* + ToCss;
239
240            /// pseudo-elements
241            type PseudoElement: $($CommonBounds)* + PseudoElement<'i, Impl = Self>;
242
243            fn to_css<W: fmt::Write>(selectors: &SelectorList<'i, Self>, dest: &mut W) -> fmt::Result {
244                serialize_selector_list(selectors.0.iter(), dest)
245            }
246        }
247    }
248}
249
250macro_rules! with_bounds {
251    ( [ $( $CommonBounds: tt )* ] [ $( $FromStr: tt )* ]) => {
252        with_all_bounds! {
253            [$($CommonBounds)* + $($FromStr)* + ToCss]
254            [$($CommonBounds)*]
255            [$($FromStr)*]
256        }
257    }
258}
259
260#[cfg(feature = "serde")]
261with_bounds! {
262    [Clone + PartialEq + Eq + std::hash::Hash]
263    [From<CowRcStr<'i>> + From<std::borrow::Cow<'i, str>> + AsRef<str>]
264}
265
266#[cfg(not(feature = "serde"))]
267with_bounds! {
268    [Clone + PartialEq + Eq + std::hash::Hash]
269    [From<CowRcStr<'i>>]
270}
271
272pub trait Parser<'i> {
273  type Impl: SelectorImpl<'i>;
274  type Error: 'i + From<SelectorParseErrorKind<'i>>;
275
276  /// Whether to parse the `::slotted()` pseudo-element.
277  fn parse_slotted(&self) -> bool {
278    false
279  }
280
281  /// Whether to parse the `::part()` pseudo-element.
282  fn parse_part(&self) -> bool {
283    false
284  }
285
286  /// Whether to parse the `:where` pseudo-class.
287  fn parse_is_and_where(&self) -> bool {
288    false
289  }
290
291  /// The error recovery that selector lists inside :is() and :where() have.
292  fn is_and_where_error_recovery(&self) -> ParseErrorRecovery {
293    ParseErrorRecovery::IgnoreInvalidSelector
294  }
295
296  /// Whether the given function name is an alias for the `:is()` function.
297  fn parse_any_prefix(&self, _name: &str) -> Option<<Self::Impl as SelectorImpl<'i>>::VendorPrefix> {
298    None
299  }
300
301  /// Whether to parse the `:host` pseudo-class.
302  fn parse_host(&self) -> bool {
303    false
304  }
305
306  /// Parses non-tree-structural pseudo-classes. Tree structural pseudo-classes,
307  /// like `:first-child`, are built into this library.
308  ///
309  /// This function can return an "Err" pseudo-element in order to support CSS2.1
310  /// pseudo-elements.
311  fn parse_non_ts_pseudo_class(
312    &self,
313    location: SourceLocation,
314    name: CowRcStr<'i>,
315  ) -> Result<<Self::Impl as SelectorImpl<'i>>::NonTSPseudoClass, ParseError<'i, Self::Error>> {
316    Err(location.new_custom_error(SelectorParseErrorKind::UnsupportedPseudoClass(name)))
317  }
318
319  fn parse_non_ts_functional_pseudo_class<'t>(
320    &self,
321    name: CowRcStr<'i>,
322    arguments: &mut CssParser<'i, 't>,
323  ) -> Result<<Self::Impl as SelectorImpl<'i>>::NonTSPseudoClass, ParseError<'i, Self::Error>> {
324    Err(arguments.new_custom_error(SelectorParseErrorKind::UnsupportedPseudoClass(name)))
325  }
326
327  fn parse_pseudo_element(
328    &self,
329    location: SourceLocation,
330    name: CowRcStr<'i>,
331  ) -> Result<<Self::Impl as SelectorImpl<'i>>::PseudoElement, ParseError<'i, Self::Error>> {
332    Err(location.new_custom_error(SelectorParseErrorKind::UnsupportedPseudoElement(name)))
333  }
334
335  fn parse_functional_pseudo_element<'t>(
336    &self,
337    name: CowRcStr<'i>,
338    arguments: &mut CssParser<'i, 't>,
339  ) -> Result<<Self::Impl as SelectorImpl<'i>>::PseudoElement, ParseError<'i, Self::Error>> {
340    Err(arguments.new_custom_error(SelectorParseErrorKind::UnsupportedPseudoElement(name)))
341  }
342
343  fn default_namespace(&self) -> Option<<Self::Impl as SelectorImpl<'i>>::NamespaceUrl> {
344    None
345  }
346
347  fn namespace_for_prefix(
348    &self,
349    _prefix: &<Self::Impl as SelectorImpl<'i>>::NamespacePrefix,
350  ) -> Option<<Self::Impl as SelectorImpl<'i>>::NamespaceUrl> {
351    None
352  }
353
354  fn is_nesting_allowed(&self) -> bool {
355    false
356  }
357
358  fn deep_combinator_enabled(&self) -> bool {
359    false
360  }
361}
362
363#[derive(Clone, Debug, PartialEq, Eq, Hash)]
364#[cfg_attr(
365  feature = "serde",
366  derive(serde::Serialize, serde::Deserialize),
367  serde(bound(
368    serialize = "Impl::NonTSPseudoClass: serde::Serialize, Impl::PseudoElement: serde::Serialize, Impl::VendorPrefix: serde::Serialize",
369    deserialize = "Impl::NonTSPseudoClass: serde::Deserialize<'de>, Impl::PseudoElement: serde::Deserialize<'de>, Impl::VendorPrefix: serde::Deserialize<'de>"
370  ))
371)]
372#[cfg_attr(
373  feature = "jsonschema",
374  derive(schemars::JsonSchema),
375  schemars(
376    rename = "SelectorList",
377    bound = "Impl: schemars::JsonSchema, Impl::NonTSPseudoClass: schemars::JsonSchema, Impl::PseudoElement: schemars::JsonSchema, Impl::VendorPrefix: schemars::JsonSchema"
378  )
379)]
380pub struct SelectorList<'i, Impl: SelectorImpl<'i>>(
381  #[cfg_attr(feature = "serde", serde(borrow))] pub SmallVec<[Selector<'i, Impl>; 1]>,
382);
383
384#[cfg(feature = "into_owned")]
385impl<'any, 'i, Impl: SelectorImpl<'i>, NewSel> rspack_lightningcss_static_self::IntoOwned<'any>
386  for SelectorList<'i, Impl>
387where
388  Impl: rspack_lightningcss_static_self::IntoOwned<'any, Owned = NewSel>,
389  NewSel: SelectorImpl<'any>,
390  Component<'i, Impl>: rspack_lightningcss_static_self::IntoOwned<'any, Owned = Component<'any, NewSel>>,
391{
392  type Owned = SelectorList<'any, NewSel>;
393
394  fn into_owned(self) -> Self::Owned {
395    SelectorList(self.0.into_owned())
396  }
397}
398
399/// How to treat invalid selectors in a selector list.
400pub enum ParseErrorRecovery {
401  /// Discard the entire selector list, this is the default behavior for
402  /// almost all of CSS.
403  DiscardList,
404  /// Ignore invalid selectors, potentially creating an empty selector list.
405  ///
406  /// This is the error recovery mode of :is() and :where()
407  IgnoreInvalidSelector,
408}
409
410#[derive(Eq, PartialEq, Clone, Copy)]
411pub enum NestingRequirement {
412  None,
413  Prefixed,
414  Contained,
415  Implicit,
416}
417
418impl<'i, Impl: SelectorImpl<'i>> SelectorList<'i, Impl> {
419  /// Parse a comma-separated list of Selectors.
420  /// <https://drafts.csswg.org/selectors/#grouping>
421  ///
422  /// Return the Selectors or Err if there is an invalid selector.
423  pub fn parse<'t, P>(
424    parser: &P,
425    input: &mut CssParser<'i, 't>,
426    error_recovery: ParseErrorRecovery,
427    nesting_requirement: NestingRequirement,
428  ) -> Result<Self, ParseError<'i, P::Error>>
429  where
430    P: Parser<'i, Impl = Impl>,
431  {
432    Self::parse_with_state(
433      parser,
434      input,
435      &mut SelectorParsingState::empty(),
436      error_recovery,
437      nesting_requirement,
438    )
439  }
440
441  #[inline]
442  fn parse_with_state<'t, P>(
443    parser: &P,
444    input: &mut CssParser<'i, 't>,
445    state: &mut SelectorParsingState,
446    recovery: ParseErrorRecovery,
447    nesting_requirement: NestingRequirement,
448  ) -> Result<Self, ParseError<'i, P::Error>>
449  where
450    P: Parser<'i, Impl = Impl>,
451  {
452    let original_state = *state;
453    let mut values = SmallVec::new();
454    loop {
455      let selector = input.parse_until_before(Delimiter::Comma, |input| {
456        let mut selector_state = original_state;
457        let result = parse_selector(parser, input, &mut selector_state, nesting_requirement);
458        if selector_state.contains(SelectorParsingState::AFTER_NESTING) {
459          state.insert(SelectorParsingState::AFTER_NESTING)
460        }
461        result
462      });
463
464      let was_ok = selector.is_ok();
465      match selector {
466        Ok(selector) => values.push(selector),
467        Err(err) => match recovery {
468          ParseErrorRecovery::DiscardList => return Err(err),
469          ParseErrorRecovery::IgnoreInvalidSelector => {}
470        },
471      }
472
473      loop {
474        match input.next() {
475          Err(_) => return Ok(SelectorList(values)),
476          Ok(&Token::Comma) => break,
477          Ok(_) => {
478            debug_assert!(!was_ok, "Shouldn't have got a selector if getting here");
479          }
480        }
481      }
482    }
483  }
484
485  pub fn parse_relative<'t, P>(
486    parser: &P,
487    input: &mut CssParser<'i, 't>,
488    error_recovery: ParseErrorRecovery,
489    nesting_requirement: NestingRequirement,
490  ) -> Result<Self, ParseError<'i, P::Error>>
491  where
492    P: Parser<'i, Impl = Impl>,
493  {
494    Self::parse_relative_with_state(
495      parser,
496      input,
497      &mut SelectorParsingState::empty(),
498      error_recovery,
499      nesting_requirement,
500    )
501  }
502
503  #[inline]
504  fn parse_relative_with_state<'t, P>(
505    parser: &P,
506    input: &mut CssParser<'i, 't>,
507    state: &mut SelectorParsingState,
508    recovery: ParseErrorRecovery,
509    nesting_requirement: NestingRequirement,
510  ) -> Result<Self, ParseError<'i, P::Error>>
511  where
512    P: Parser<'i, Impl = Impl>,
513  {
514    let original_state = *state;
515    let mut values = SmallVec::new();
516    loop {
517      let selector = input.parse_until_before(Delimiter::Comma, |input| {
518        let mut selector_state = original_state;
519        let result = parse_relative_selector(parser, input, &mut selector_state, nesting_requirement);
520        if selector_state.contains(SelectorParsingState::AFTER_NESTING) {
521          state.insert(SelectorParsingState::AFTER_NESTING)
522        }
523        result
524      });
525
526      let was_ok = selector.is_ok();
527      match selector {
528        Ok(selector) => values.push(selector),
529        Err(err) => match recovery {
530          ParseErrorRecovery::DiscardList => return Err(err),
531          ParseErrorRecovery::IgnoreInvalidSelector => {}
532        },
533      }
534
535      loop {
536        match input.next() {
537          Err(_) => return Ok(SelectorList(values)),
538          Ok(&Token::Comma) => break,
539          Ok(_) => {
540            debug_assert!(!was_ok, "Shouldn't have got a selector if getting here");
541          }
542        }
543      }
544    }
545  }
546
547  /// Creates a new SelectorList.
548  pub fn new(v: SmallVec<[Selector<'i, Impl>; 1]>) -> Self {
549    SelectorList(v)
550  }
551
552  /// Creates a SelectorList from a Vec of selectors. Used in tests.
553  pub fn from_vec(v: Vec<Selector<'i, Impl>>) -> Self {
554    SelectorList(SmallVec::from_vec(v))
555  }
556}
557
558impl<'i, Impl: SelectorImpl<'i>> From<Selector<'i, Impl>> for SelectorList<'i, Impl> {
559  fn from(selector: Selector<'i, Impl>) -> Self {
560    SelectorList(smallvec![selector])
561  }
562}
563
564impl<'i, Impl: SelectorImpl<'i>> From<Component<'i, Impl>> for SelectorList<'i, Impl> {
565  fn from(component: Component<'i, Impl>) -> Self {
566    SelectorList::from(Selector::from(component))
567  }
568}
569
570/// Parses one compound selector suitable for nested stuff like :-moz-any, etc.
571fn parse_inner_compound_selector<'i, 't, P, Impl>(
572  parser: &P,
573  input: &mut CssParser<'i, 't>,
574  state: &mut SelectorParsingState,
575) -> Result<Selector<'i, Impl>, ParseError<'i, P::Error>>
576where
577  P: Parser<'i, Impl = Impl>,
578  Impl: SelectorImpl<'i>,
579{
580  let mut child_state =
581    *state | SelectorParsingState::DISALLOW_PSEUDOS | SelectorParsingState::DISALLOW_COMBINATORS;
582  let result = parse_selector(parser, input, &mut child_state, NestingRequirement::None)?;
583  if child_state.contains(SelectorParsingState::AFTER_NESTING) {
584    state.insert(SelectorParsingState::AFTER_NESTING)
585  }
586  Ok(result)
587}
588
589/// Ancestor hashes for the bloom filter. We precompute these and store them
590/// inline with selectors to optimize cache performance during matching.
591/// This matters a lot.
592///
593/// We use 4 hashes, which is copied from Gecko, who copied it from WebKit.
594/// Note that increasing the number of hashes here will adversely affect the
595/// cache hit when fast-rejecting long lists of Rules with inline hashes.
596///
597/// Because the bloom filter only uses the bottom 24 bits of the hash, we pack
598/// the fourth hash into the upper bits of the first three hashes in order to
599/// shrink Rule (whose size matters a lot). This scheme minimizes the runtime
600/// overhead of the packing for the first three hashes (we just need to mask
601/// off the upper bits) at the expense of making the fourth somewhat more
602/// complicated to assemble, because we often bail out before checking all the
603/// hashes.
604#[derive(Clone, Debug, Eq, PartialEq)]
605pub struct AncestorHashes {
606  pub packed_hashes: [u32; 3],
607}
608
609fn collect_ancestor_hashes<'i, Impl: SelectorImpl<'i>>(
610  iter: SelectorIter<'_, 'i, Impl>,
611  quirks_mode: QuirksMode,
612  hashes: &mut [u32; 4],
613  len: &mut usize,
614) -> bool
615where
616  Impl::Identifier: PrecomputedHash,
617  Impl::LocalName: PrecomputedHash,
618  Impl::NamespaceUrl: PrecomputedHash,
619{
620  for component in AncestorIter::new(iter) {
621    let hash = match *component {
622      Component::LocalName(LocalName {
623        ref name,
624        ref lower_name,
625      }) => {
626        // Only insert the local-name into the filter if it's all
627        // lowercase.  Otherwise we would need to test both hashes, and
628        // our data structures aren't really set up for that.
629        if name != lower_name {
630          continue;
631        }
632        name.precomputed_hash()
633      }
634      Component::DefaultNamespace(ref url) | Component::Namespace(_, ref url) => url.precomputed_hash(),
635      // In quirks mode, class and id selectors should match
636      // case-insensitively, so just avoid inserting them into the filter.
637      Component::ID(ref id) if quirks_mode != QuirksMode::Quirks => id.precomputed_hash(),
638      Component::Class(ref class) if quirks_mode != QuirksMode::Quirks => class.precomputed_hash(),
639      Component::Is(ref list) | Component::Where(ref list) => {
640        // :where and :is OR their selectors, so we can't put any hash
641        // in the filter if there's more than one selector, as that'd
642        // exclude elements that may match one of the other selectors.
643        if list.len() == 1 && !collect_ancestor_hashes(list[0].iter(), quirks_mode, hashes, len) {
644          return false;
645        }
646        continue;
647      }
648      _ => continue,
649    };
650
651    hashes[*len] = hash & BLOOM_HASH_MASK;
652    *len += 1;
653    if *len == hashes.len() {
654      return false;
655    }
656  }
657  true
658}
659
660impl AncestorHashes {
661  pub fn new<'i, Impl: SelectorImpl<'i>>(selector: &Selector<'i, Impl>, quirks_mode: QuirksMode) -> Self
662  where
663    Impl::Identifier: PrecomputedHash,
664    Impl::LocalName: PrecomputedHash,
665    Impl::NamespaceUrl: PrecomputedHash,
666  {
667    // Compute ancestor hashes for the bloom filter.
668    let mut hashes = [0u32; 4];
669    let mut len = 0;
670    collect_ancestor_hashes(selector.iter(), quirks_mode, &mut hashes, &mut len);
671    debug_assert!(len <= 4);
672
673    // Now, pack the fourth hash (if it exists) into the upper byte of each of
674    // the other three hashes.
675    if len == 4 {
676      let fourth = hashes[3];
677      hashes[0] |= (fourth & 0x000000ff) << 24;
678      hashes[1] |= (fourth & 0x0000ff00) << 16;
679      hashes[2] |= (fourth & 0x00ff0000) << 8;
680    }
681
682    AncestorHashes {
683      packed_hashes: [hashes[0], hashes[1], hashes[2]],
684    }
685  }
686
687  /// Returns the fourth hash, reassembled from parts.
688  pub fn fourth_hash(&self) -> u32 {
689    ((self.packed_hashes[0] & 0xff000000) >> 24)
690      | ((self.packed_hashes[1] & 0xff000000) >> 16)
691      | ((self.packed_hashes[2] & 0xff000000) >> 8)
692  }
693}
694
695pub fn namespace_empty_string<'i, Impl: SelectorImpl<'i>>() -> Impl::NamespaceUrl {
696  // Rust type’s default, not default namespace
697  Impl::NamespaceUrl::default()
698}
699
700/// A Selector stores a sequence of simple selectors and combinators. The
701/// iterator classes allow callers to iterate at either the raw sequence level or
702/// at the level of sequences of simple selectors separated by combinators. Most
703/// callers want the higher-level iterator.
704///
705/// We store compound selectors internally right-to-left (in matching order).
706/// Additionally, we invert the order of top-level compound selectors so that
707/// each one matches left-to-right. This is because matching namespace, local name,
708/// id, and class are all relatively cheap, whereas matching pseudo-classes might
709/// be expensive (depending on the pseudo-class). Since authors tend to put the
710/// pseudo-classes on the right, it's faster to start matching on the left.
711///
712/// This reordering doesn't change the semantics of selector matching, and we
713/// handle it in to_css to make it invisible to serialization.
714#[derive(Clone, PartialEq, Eq, Hash)]
715pub struct Selector<'i, Impl: SelectorImpl<'i>>(SpecificityAndFlags, Vec<Component<'i, Impl>>);
716
717#[cfg(feature = "into_owned")]
718impl<'any, 'i, Impl: SelectorImpl<'i>, NewSel> rspack_lightningcss_static_self::IntoOwned<'any>
719  for Selector<'i, Impl>
720where
721  Impl: rspack_lightningcss_static_self::IntoOwned<'any, Owned = NewSel>,
722  NewSel: SelectorImpl<'any>,
723  Component<'i, Impl>: rspack_lightningcss_static_self::IntoOwned<'any, Owned = Component<'any, NewSel>>,
724{
725  type Owned = Selector<'any, NewSel>;
726
727  fn into_owned(self) -> Self::Owned {
728    Selector(self.0, self.1.into_owned())
729  }
730}
731
732impl<'i, Impl: SelectorImpl<'i>> Selector<'i, Impl> {
733  #[inline]
734  pub fn specificity(&self) -> u32 {
735    self.0.specificity()
736  }
737
738  #[inline]
739  pub fn has_pseudo_element(&self) -> bool {
740    self.0.has_pseudo_element()
741  }
742
743  #[inline]
744  pub fn is_slotted(&self) -> bool {
745    self.0.is_slotted()
746  }
747
748  #[inline]
749  pub fn is_part(&self) -> bool {
750    self.0.is_part()
751  }
752
753  #[inline]
754  pub fn append(&mut self, component: Component<'i, Impl>) {
755    let index = self
756      .1
757      .iter()
758      .position(|c| matches!(*c, Component::Combinator(..) | Component::PseudoElement(..)))
759      .unwrap_or(self.1.len());
760    self.1.insert(index, component);
761  }
762
763  #[inline]
764  pub fn parts(&self) -> Option<&[Impl::Identifier]> {
765    if !self.is_part() {
766      return None;
767    }
768
769    let mut iter = self.iter();
770    if self.has_pseudo_element() {
771      // Skip the pseudo-element.
772      for _ in &mut iter {}
773
774      let combinator = iter.next_sequence()?;
775      debug_assert_eq!(combinator, Combinator::PseudoElement);
776    }
777
778    for component in iter {
779      if let Component::Part(ref part) = *component {
780        return Some(part);
781      }
782    }
783
784    debug_assert!(false, "is_part() lied somehow?");
785    None
786  }
787
788  #[inline]
789  pub fn pseudo_element(&self) -> Option<&Impl::PseudoElement> {
790    if !self.has_pseudo_element() {
791      return None;
792    }
793
794    for component in self.iter() {
795      if let Component::PseudoElement(ref pseudo) = *component {
796        return Some(pseudo);
797      }
798    }
799
800    debug_assert!(false, "has_pseudo_element lied!");
801    None
802  }
803
804  /// Whether this selector (pseudo-element part excluded) matches every element.
805  ///
806  /// Used for "pre-computed" pseudo-elements in components/style/stylist.rs
807  #[inline]
808  pub fn is_universal(&self) -> bool {
809    self.iter_raw_match_order().all(|c| {
810      matches!(
811        *c,
812        Component::ExplicitUniversalType
813          | Component::ExplicitAnyNamespace
814          | Component::Combinator(Combinator::PseudoElement)
815          | Component::PseudoElement(..)
816      )
817    })
818  }
819
820  #[inline]
821  pub fn has_combinator(&self) -> bool {
822    self
823      .iter_raw_match_order()
824      .any(|c| matches!(*c, Component::Combinator(combinator) if combinator.is_tree_combinator()))
825  }
826
827  /// Returns an iterator over this selector in matching order (right-to-left).
828  /// When a combinator is reached, the iterator will return None, and
829  /// next_sequence() may be called to continue to the next sequence.
830  #[inline]
831  pub fn iter(&self) -> SelectorIter<'_, 'i, Impl> {
832    SelectorIter {
833      iter: self.iter_raw_match_order(),
834      next_combinator: None,
835    }
836  }
837
838  /// Whether this selector is a featureless :host selector, with no
839  /// combinators to the left, and optionally has a pseudo-element to the
840  /// right.
841  #[inline]
842  pub fn is_featureless_host_selector_or_pseudo_element(&self) -> bool {
843    let mut iter = self.iter();
844    if !self.has_pseudo_element() {
845      return iter.is_featureless_host_selector();
846    }
847
848    // Skip the pseudo-element.
849    for _ in &mut iter {}
850
851    match iter.next_sequence() {
852      None => return false,
853      Some(combinator) => {
854        debug_assert_eq!(combinator, Combinator::PseudoElement);
855      }
856    }
857
858    iter.is_featureless_host_selector()
859  }
860
861  /// Returns an iterator over this selector in matching order (right-to-left),
862  /// skipping the rightmost |offset| Components.
863  #[inline]
864  pub fn iter_from(&self, offset: usize) -> SelectorIter<'_, 'i, Impl> {
865    let iter = self.1[offset..].iter();
866    SelectorIter {
867      iter,
868      next_combinator: None,
869    }
870  }
871
872  /// Returns the combinator at index `index` (zero-indexed from the right),
873  /// or panics if the component is not a combinator.
874  #[inline]
875  pub fn combinator_at_match_order(&self, index: usize) -> Combinator {
876    match self.1[index] {
877      Component::Combinator(c) => c,
878      ref other => panic!("Not a combinator: {:?}, {:?}, index: {}", other, self, index),
879    }
880  }
881
882  /// Returns an iterator over the entire sequence of simple selectors and
883  /// combinators, in matching order (from right to left).
884  #[inline]
885  pub fn iter_raw_match_order(&self) -> slice::Iter<'_, Component<'i, Impl>> {
886    self.1.iter()
887  }
888
889  #[inline]
890  pub fn iter_mut_raw_match_order(&mut self) -> slice::IterMut<'_, Component<'i, Impl>> {
891    self.1.iter_mut()
892  }
893
894  /// Returns the combinator at index `index` (zero-indexed from the left),
895  /// or panics if the component is not a combinator.
896  #[inline]
897  pub fn combinator_at_parse_order(&self, index: usize) -> Combinator {
898    match self.1[self.len() - index - 1] {
899      Component::Combinator(c) => c,
900      ref other => panic!("Not a combinator: {:?}, {:?}, index: {}", other, self, index),
901    }
902  }
903
904  /// Returns an iterator over the sequence of simple selectors and
905  /// combinators, in parse order (from left to right), starting from
906  /// `offset`.
907  #[inline]
908  pub fn iter_raw_parse_order_from(&self, offset: usize) -> Rev<slice::Iter<'_, Component<'i, Impl>>> {
909    self.1[..self.len() - offset].iter().rev()
910  }
911
912  /// Creates a Selector from a vec of Components, specified in parse order. Used in tests.
913  #[allow(unused)]
914  pub(crate) fn from_vec(vec: Vec<Component<'i, Impl>>, specificity: u32, flags: SelectorFlags) -> Self {
915    let mut builder = SelectorBuilder::default();
916    for component in vec.into_iter() {
917      if let Some(combinator) = component.as_combinator() {
918        builder.push_combinator(combinator);
919      } else {
920        builder.push_simple_selector(component);
921      }
922    }
923    let spec = SpecificityAndFlags { specificity, flags };
924    let (spec, components) = builder.build_with_specificity_and_flags(spec);
925    Selector(spec, components)
926  }
927
928  #[cfg(feature = "serde")]
929  #[inline]
930  pub(crate) fn new(spec: SpecificityAndFlags, components: Vec<Component<'i, Impl>>) -> Self {
931    Selector(spec, components)
932  }
933
934  /// Returns count of simple selectors and combinators in the Selector.
935  #[inline]
936  pub fn len(&self) -> usize {
937    self.1.len()
938  }
939
940  /// Traverse selector components inside `self`.
941  ///
942  /// Implementations of this method should call `SelectorVisitor` methods
943  /// or other impls of `Visit` as appropriate based on the fields of `Self`.
944  ///
945  /// A return value of `false` indicates terminating the traversal.
946  /// It should be propagated with an early return.
947  /// On the contrary, `true` indicates that all fields of `self` have been traversed:
948  ///
949  /// ```rust,ignore
950  /// if !visitor.visit_simple_selector(&self.some_simple_selector) {
951  ///     return false;
952  /// }
953  /// if !self.some_component.visit(visitor) {
954  ///     return false;
955  /// }
956  /// true
957  /// ```
958  pub fn visit<V>(&self, visitor: &mut V) -> bool
959  where
960    V: SelectorVisitor<'i, Impl = Impl>,
961  {
962    let mut current = self.iter();
963    let mut combinator = None;
964    loop {
965      if !visitor.visit_complex_selector(combinator) {
966        return false;
967      }
968
969      for selector in &mut current {
970        if !selector.visit(visitor) {
971          return false;
972        }
973      }
974
975      combinator = current.next_sequence();
976      if combinator.is_none() {
977        break;
978      }
979    }
980
981    true
982  }
983}
984
985impl<'i, Impl: SelectorImpl<'i>> From<Component<'i, Impl>> for Selector<'i, Impl> {
986  fn from(component: Component<'i, Impl>) -> Self {
987    let mut builder = SelectorBuilder::default();
988    if let Some(combinator) = component.as_combinator() {
989      builder.push_combinator(combinator);
990    } else {
991      builder.push_simple_selector(component);
992    }
993    let (spec, components) = builder.build(false, false, false);
994    Selector(spec, components)
995  }
996}
997
998impl<'i, Impl: SelectorImpl<'i>> From<Vec<Component<'i, Impl>>> for Selector<'i, Impl> {
999  fn from(vec: Vec<Component<'i, Impl>>) -> Self {
1000    let mut builder = SelectorBuilder::default();
1001    for component in vec.into_iter() {
1002      if let Some(combinator) = component.as_combinator() {
1003        builder.push_combinator(combinator);
1004      } else {
1005        builder.push_simple_selector(component);
1006      }
1007    }
1008    let (spec, components) = builder.build(false, false, false);
1009    Selector(spec, components)
1010  }
1011}
1012
1013#[derive(Clone)]
1014pub struct SelectorIter<'a, 'i, Impl: SelectorImpl<'i>> {
1015  iter: slice::Iter<'a, Component<'i, Impl>>,
1016  next_combinator: Option<Combinator>,
1017}
1018
1019impl<'a, 'i, Impl: 'a + SelectorImpl<'i>> SelectorIter<'a, 'i, Impl> {
1020  /// Prepares this iterator to point to the next sequence to the left,
1021  /// returning the combinator if the sequence was found.
1022  #[inline]
1023  pub fn next_sequence(&mut self) -> Option<Combinator> {
1024    self.next_combinator.take()
1025  }
1026
1027  /// Whether this selector is a featureless host selector, with no
1028  /// combinators to the left.
1029  #[inline]
1030  pub(crate) fn is_featureless_host_selector(&mut self) -> bool {
1031    self.selector_length() > 0
1032      && self.all(|component| matches!(*component, Component::Host(..)))
1033      && self.next_sequence().is_none()
1034  }
1035
1036  #[inline]
1037  pub(crate) fn matches_for_stateless_pseudo_element(&mut self) -> bool {
1038    let first = match self.next() {
1039      Some(c) => c,
1040      // Note that this is the common path that we keep inline: the
1041      // pseudo-element not having anything to its right.
1042      None => return true,
1043    };
1044    self.matches_for_stateless_pseudo_element_internal(first)
1045  }
1046
1047  #[inline(never)]
1048  fn matches_for_stateless_pseudo_element_internal(&mut self, first: &Component<'i, Impl>) -> bool {
1049    if !first.matches_for_stateless_pseudo_element() {
1050      return false;
1051    }
1052    for component in self {
1053      // The only other parser-allowed Components in this sequence are
1054      // state pseudo-classes, or one of the other things that can contain
1055      // them.
1056      if !component.matches_for_stateless_pseudo_element() {
1057        return false;
1058      }
1059    }
1060    true
1061  }
1062
1063  /// Returns remaining count of the simple selectors and combinators in the Selector.
1064  #[inline]
1065  pub fn selector_length(&self) -> usize {
1066    self.iter.len()
1067  }
1068}
1069
1070impl<'a, 'i, Impl: SelectorImpl<'i>> Iterator for SelectorIter<'a, 'i, Impl> {
1071  type Item = &'a Component<'i, Impl>;
1072
1073  #[inline]
1074  fn next(&mut self) -> Option<Self::Item> {
1075    debug_assert!(self.next_combinator.is_none(), "You should call next_sequence!");
1076    match *self.iter.next()? {
1077      Component::Combinator(c) => {
1078        self.next_combinator = Some(c);
1079        None
1080      }
1081      ref x => Some(x),
1082    }
1083  }
1084}
1085
1086impl<'a, 'i, Impl: SelectorImpl<'i>> fmt::Debug for SelectorIter<'a, 'i, Impl> {
1087  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1088    let iter = self.iter.clone().rev();
1089    for component in iter {
1090      component.to_css(f)?
1091    }
1092    Ok(())
1093  }
1094}
1095
1096/// An iterator over all simple selectors belonging to ancestors.
1097struct AncestorIter<'a, 'i, Impl: SelectorImpl<'i>>(SelectorIter<'a, 'i, Impl>);
1098impl<'a, 'i, Impl: 'a + SelectorImpl<'i>> AncestorIter<'a, 'i, Impl> {
1099  /// Creates an AncestorIter. The passed-in iterator is assumed to point to
1100  /// the beginning of the child sequence, which will be skipped.
1101  fn new(inner: SelectorIter<'a, 'i, Impl>) -> Self {
1102    let mut result = AncestorIter(inner);
1103    result.skip_until_ancestor();
1104    result
1105  }
1106
1107  /// Skips a sequence of simple selectors and all subsequent sequences until
1108  /// a non-pseudo-element ancestor combinator is reached.
1109  fn skip_until_ancestor(&mut self) {
1110    loop {
1111      while self.0.next().is_some() {}
1112      // If this is ever changed to stop at the "pseudo-element"
1113      // combinator, we will need to fix the way we compute hashes for
1114      // revalidation selectors.
1115      if self
1116        .0
1117        .next_sequence()
1118        .is_none_or(|x| matches!(x, Combinator::Child | Combinator::Descendant))
1119      {
1120        break;
1121      }
1122    }
1123  }
1124}
1125
1126impl<'a, 'i, Impl: SelectorImpl<'i>> Iterator for AncestorIter<'a, 'i, Impl> {
1127  type Item = &'a Component<'i, Impl>;
1128  fn next(&mut self) -> Option<Self::Item> {
1129    // Grab the next simple selector in the sequence if available.
1130    let next = self.0.next();
1131    if next.is_some() {
1132      return next;
1133    }
1134
1135    // See if there are more sequences. If so, skip any non-ancestor sequences.
1136    if let Some(combinator) = self.0.next_sequence() {
1137      if !matches!(combinator, Combinator::Child | Combinator::Descendant) {
1138        self.skip_until_ancestor();
1139      }
1140    }
1141
1142    self.0.next()
1143  }
1144}
1145
1146#[derive(Clone, Copy, Debug, Eq, PartialEq, Hash)]
1147#[cfg_attr(
1148  feature = "serde",
1149  derive(serde::Serialize, serde::Deserialize),
1150  serde(rename_all = "kebab-case")
1151)]
1152#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1153#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1154pub enum Combinator {
1155  Child,        //  >
1156  Descendant,   // space
1157  NextSibling,  // +
1158  LaterSibling, // ~
1159  /// A dummy combinator we use to the left of pseudo-elements.
1160  ///
1161  /// It serializes as the empty string, and acts effectively as a child
1162  /// combinator in most cases.  If we ever actually start using a child
1163  /// combinator for this, we will need to fix up the way hashes are computed
1164  /// for revalidation selectors.
1165  PseudoElement,
1166  /// Another combinator used for ::slotted(), which represent the jump from
1167  /// a node to its assigned slot.
1168  SlotAssignment,
1169  /// Another combinator used for `::part()`, which represents the jump from
1170  /// the part to the containing shadow host.
1171  Part,
1172
1173  /// Non-standard Vue >>> combinator.
1174  /// https://vue-loader.vuejs.org/guide/scoped-css.html#deep-selectors
1175  DeepDescendant,
1176  /// Non-standard /deep/ combinator.
1177  /// Appeared in early versions of the css-scoping-1 specification:
1178  /// https://www.w3.org/TR/2014/WD-css-scoping-1-20140403/#deep-combinator
1179  /// And still supported as an alias for >>> by Vue.
1180  Deep,
1181}
1182
1183impl Combinator {
1184  /// Returns true if this combinator is a child or descendant combinator.
1185  #[inline]
1186  pub fn is_ancestor(&self) -> bool {
1187    matches!(
1188      *self,
1189      Combinator::Child | Combinator::Descendant | Combinator::PseudoElement | Combinator::SlotAssignment
1190    )
1191  }
1192
1193  /// Returns true if this combinator is a pseudo-element combinator.
1194  #[inline]
1195  pub fn is_pseudo_element(&self) -> bool {
1196    matches!(*self, Combinator::PseudoElement)
1197  }
1198
1199  /// Returns true if this combinator is a next- or later-sibling combinator.
1200  #[inline]
1201  pub fn is_sibling(&self) -> bool {
1202    matches!(*self, Combinator::NextSibling | Combinator::LaterSibling)
1203  }
1204
1205  #[inline]
1206  pub fn is_tree_combinator(&self) -> bool {
1207    matches!(
1208      *self,
1209      Combinator::Child | Combinator::Descendant | Combinator::NextSibling | Combinator::LaterSibling
1210    )
1211  }
1212}
1213
1214/// An enum for the different types of :nth- pseudoclasses
1215#[derive(Copy, Clone, Eq, PartialEq, Hash)]
1216#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1217pub enum NthType {
1218  Child,
1219  LastChild,
1220  OnlyChild,
1221  OfType,
1222  LastOfType,
1223  OnlyOfType,
1224  Col,
1225  LastCol,
1226}
1227
1228impl NthType {
1229  pub fn is_only(self) -> bool {
1230    self == Self::OnlyChild || self == Self::OnlyOfType
1231  }
1232
1233  pub fn is_of_type(self) -> bool {
1234    self == Self::OfType || self == Self::LastOfType || self == Self::OnlyOfType
1235  }
1236
1237  pub fn is_from_end(self) -> bool {
1238    self == Self::LastChild || self == Self::LastOfType || self == Self::LastCol
1239  }
1240
1241  pub fn allows_of_selector(self) -> bool {
1242    self == Self::Child || self == Self::LastChild
1243  }
1244}
1245
1246/// The properties that comprise an :nth- pseudoclass as of Selectors 3 (e.g.,
1247/// nth-child(An+B)).
1248/// https://www.w3.org/TR/selectors-3/#nth-child-pseudo
1249#[derive(Copy, Clone, Eq, PartialEq, Hash)]
1250#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1251pub struct NthSelectorData {
1252  pub ty: NthType,
1253  pub is_function: bool,
1254  pub a: i32,
1255  pub b: i32,
1256}
1257
1258impl NthSelectorData {
1259  /// Returns selector data for :only-{child,of-type}
1260  #[inline]
1261  pub const fn only(of_type: bool) -> Self {
1262    Self {
1263      ty: if of_type {
1264        NthType::OnlyOfType
1265      } else {
1266        NthType::OnlyChild
1267      },
1268      is_function: false,
1269      a: 0,
1270      b: 1,
1271    }
1272  }
1273
1274  /// Returns selector data for :first-{child,of-type}
1275  #[inline]
1276  pub const fn first(of_type: bool) -> Self {
1277    Self {
1278      ty: if of_type { NthType::OfType } else { NthType::Child },
1279      is_function: false,
1280      a: 0,
1281      b: 1,
1282    }
1283  }
1284
1285  /// Returns selector data for :last-{child,of-type}
1286  #[inline]
1287  pub const fn last(of_type: bool) -> Self {
1288    Self {
1289      ty: if of_type {
1290        NthType::LastOfType
1291      } else {
1292        NthType::LastChild
1293      },
1294      is_function: false,
1295      a: 0,
1296      b: 1,
1297    }
1298  }
1299
1300  #[inline]
1301  pub fn is_function(&self) -> bool {
1302    self.a != 0 || self.b != 1
1303  }
1304
1305  /// Writes the beginning of the selector.
1306  #[inline]
1307  pub fn write_start<W: fmt::Write>(&self, dest: &mut W, is_function: bool) -> fmt::Result {
1308    dest.write_str(match self.ty {
1309      NthType::Child if is_function => ":nth-child(",
1310      NthType::Child => ":first-child",
1311      NthType::LastChild if is_function => ":nth-last-child(",
1312      NthType::LastChild => ":last-child",
1313      NthType::OfType if is_function => ":nth-of-type(",
1314      NthType::OfType => ":first-of-type",
1315      NthType::LastOfType if is_function => ":nth-last-of-type(",
1316      NthType::LastOfType => ":last-of-type",
1317      NthType::OnlyChild => ":only-child",
1318      NthType::OnlyOfType => ":only-of-type",
1319      NthType::Col => ":nth-col(",
1320      NthType::LastCol => ":nth-last-col(",
1321    })
1322  }
1323
1324  /// Serialize <an+b> (part of the CSS Syntax spec, but currently only used here).
1325  /// <https://drafts.csswg.org/css-syntax-3/#serialize-an-anb-value>
1326  #[inline]
1327  pub fn write_affine<W: fmt::Write>(&self, dest: &mut W) -> fmt::Result {
1328    match (self.a, self.b) {
1329      (0, 0) => dest.write_char('0'),
1330
1331      (1, 0) => dest.write_char('n'),
1332      (-1, 0) => dest.write_str("-n"),
1333      (_, 0) => write!(dest, "{}n", self.a),
1334
1335      (2, 1) => dest.write_str("odd"),
1336
1337      (0, _) => write!(dest, "{}", self.b),
1338      (1, _) => write!(dest, "n{:+}", self.b),
1339      (-1, _) => write!(dest, "-n{:+}", self.b),
1340      (_, _) => write!(dest, "{}n{:+}", self.a, self.b),
1341    }
1342  }
1343}
1344
1345/// The properties that comprise an :nth- pseudoclass as of Selectors 4 (e.g.,
1346/// nth-child(An+B [of S]?)).
1347/// https://www.w3.org/TR/selectors-4/#nth-child-pseudo
1348#[derive(Clone, PartialEq, Eq, Hash)]
1349pub struct NthOfSelectorData<'i, Impl: SelectorImpl<'i>>(NthSelectorData, Box<[Selector<'i, Impl>]>);
1350
1351#[cfg(feature = "into_owned")]
1352impl<'any, 'i, Impl: SelectorImpl<'i>, NewSel> rspack_lightningcss_static_self::IntoOwned<'any>
1353  for NthOfSelectorData<'i, Impl>
1354where
1355  Impl: rspack_lightningcss_static_self::IntoOwned<'any, Owned = NewSel>,
1356  NewSel: SelectorImpl<'any>,
1357  Component<'i, Impl>: rspack_lightningcss_static_self::IntoOwned<'any, Owned = Component<'any, NewSel>>,
1358{
1359  type Owned = NthOfSelectorData<'any, NewSel>;
1360
1361  fn into_owned(self) -> Self::Owned {
1362    NthOfSelectorData(self.0, self.1.into_owned())
1363  }
1364}
1365
1366impl<'i, Impl: SelectorImpl<'i>> NthOfSelectorData<'i, Impl> {
1367  /// Returns selector data for :nth-{,last-}{child,of-type}(An+B [of S])
1368  #[inline]
1369  pub fn new(nth_data: NthSelectorData, selectors: Box<[Selector<'i, Impl>]>) -> Self {
1370    Self(nth_data, selectors)
1371  }
1372
1373  /// Returns the An+B part of the selector
1374  #[inline]
1375  pub fn nth_data(&self) -> &NthSelectorData {
1376    &self.0
1377  }
1378
1379  /// Returns the selector list part of the selector
1380  #[inline]
1381  pub fn selectors(&self) -> &[Selector<'i, Impl>] {
1382    &self.1
1383  }
1384
1385  pub fn clone_selectors(&self) -> Box<[Selector<'i, Impl>]> {
1386    self.1.clone()
1387  }
1388}
1389
1390/// A CSS simple selector or combinator. We store both in the same enum for
1391/// optimal packing and cache performance, see [1].
1392///
1393/// [1] https://bugzilla.mozilla.org/show_bug.cgi?id=1357973
1394#[derive(Clone, PartialEq, Eq, Hash)]
1395pub enum Component<'i, Impl: SelectorImpl<'i>> {
1396  Combinator(Combinator),
1397
1398  ExplicitAnyNamespace,
1399  ExplicitNoNamespace,
1400  DefaultNamespace(Impl::NamespaceUrl),
1401  Namespace(Impl::NamespacePrefix, Impl::NamespaceUrl),
1402
1403  ExplicitUniversalType,
1404  LocalName(LocalName<'i, Impl>),
1405
1406  ID(Impl::Identifier),
1407  Class(Impl::Identifier),
1408
1409  AttributeInNoNamespaceExists {
1410    local_name: Impl::LocalName,
1411    local_name_lower: Impl::LocalName,
1412  },
1413  // Used only when local_name is already lowercase.
1414  AttributeInNoNamespace {
1415    local_name: Impl::LocalName,
1416    operator: AttrSelectorOperator,
1417    value: Impl::AttrValue,
1418    case_sensitivity: ParsedCaseSensitivity,
1419    never_matches: bool,
1420  },
1421  // Use a Box in the less common cases with more data to keep size_of::<Component>() small.
1422  AttributeOther(Box<AttrSelectorWithOptionalNamespace<'i, Impl>>),
1423
1424  /// Pseudo-classes
1425  Negation(Box<[Selector<'i, Impl>]>),
1426  Root,
1427  Empty,
1428  Scope,
1429  Nth(NthSelectorData),
1430  NthOf(NthOfSelectorData<'i, Impl>),
1431  NonTSPseudoClass(Impl::NonTSPseudoClass),
1432  /// The ::slotted() pseudo-element:
1433  ///
1434  /// https://drafts.csswg.org/css-scoping/#slotted-pseudo
1435  ///
1436  /// The selector here is a compound selector, that is, no combinators.
1437  ///
1438  /// NOTE(emilio): This should support a list of selectors, but as of this
1439  /// writing no other browser does, and that allows them to put ::slotted()
1440  /// in the rule hash, so we do that too.
1441  ///
1442  /// See https://github.com/w3c/csswg-drafts/issues/2158
1443  Slotted(Selector<'i, Impl>),
1444  /// The `::part` pseudo-element.
1445  ///   https://drafts.csswg.org/css-shadow-parts/#part
1446  Part(Box<[Impl::Identifier]>),
1447  /// The `:host` pseudo-class:
1448  ///
1449  /// https://drafts.csswg.org/css-scoping/#host-selector
1450  ///
1451  /// NOTE(emilio): This should support a list of selectors, but as of this
1452  /// writing no other browser does, and that allows them to put :host()
1453  /// in the rule hash, so we do that too.
1454  ///
1455  /// See https://github.com/w3c/csswg-drafts/issues/2158
1456  Host(Option<Selector<'i, Impl>>),
1457  /// The `:where` pseudo-class.
1458  ///
1459  /// https://drafts.csswg.org/selectors/#zero-matches
1460  ///
1461  /// The inner argument is conceptually a SelectorList, but we move the
1462  /// selectors to the heap to keep Component small.
1463  Where(Box<[Selector<'i, Impl>]>),
1464  /// The `:is` pseudo-class.
1465  ///
1466  /// https://drafts.csswg.org/selectors/#matches-pseudo
1467  ///
1468  /// Same comment as above re. the argument.
1469  Is(Box<[Selector<'i, Impl>]>),
1470  Any(Impl::VendorPrefix, Box<[Selector<'i, Impl>]>),
1471  /// The `:has` pseudo-class.
1472  ///
1473  /// https://www.w3.org/TR/selectors/#relational
1474  Has(Box<[Selector<'i, Impl>]>),
1475  /// An implementation-dependent pseudo-element selector.
1476  PseudoElement(Impl::PseudoElement),
1477  /// A nesting selector:
1478  ///
1479  /// https://drafts.csswg.org/css-nesting-1/#nest-selector
1480  ///
1481  /// NOTE: This is a lightningcss addition.
1482  Nesting,
1483}
1484
1485#[cfg(feature = "into_owned")]
1486impl<'any, 'i, Impl: SelectorImpl<'i>, NewSel> rspack_lightningcss_static_self::IntoOwned<'any>
1487  for Component<'i, Impl>
1488where
1489  Impl: rspack_lightningcss_static_self::IntoOwned<'any, Owned = NewSel>,
1490  NewSel: SelectorImpl<'any>,
1491  Impl::NamespaceUrl: rspack_lightningcss_static_self::IntoOwned<'any, Owned = NewSel::NamespaceUrl>,
1492  Impl::NamespacePrefix: rspack_lightningcss_static_self::IntoOwned<'any, Owned = NewSel::NamespacePrefix>,
1493  Impl::Identifier: rspack_lightningcss_static_self::IntoOwned<'any, Owned = NewSel::Identifier>,
1494  Impl::LocalName: rspack_lightningcss_static_self::IntoOwned<'any, Owned = NewSel::LocalName>,
1495  Impl::AttrValue: rspack_lightningcss_static_self::IntoOwned<'any, Owned = NewSel::AttrValue>,
1496  Impl::NonTSPseudoClass: rspack_lightningcss_static_self::IntoOwned<'any, Owned = NewSel::NonTSPseudoClass>,
1497  Impl::PseudoElement: rspack_lightningcss_static_self::IntoOwned<'any, Owned = NewSel::PseudoElement>,
1498  Impl::VendorPrefix: rspack_lightningcss_static_self::IntoOwned<'any, Owned = NewSel::VendorPrefix>,
1499{
1500  type Owned = Component<'any, NewSel>;
1501
1502  fn into_owned(self) -> Self::Owned {
1503    match self {
1504      Component::Combinator(c) => Component::Combinator(c.into_owned()),
1505      Component::ExplicitAnyNamespace => Component::ExplicitAnyNamespace,
1506      Component::ExplicitNoNamespace => Component::ExplicitNoNamespace,
1507      Component::DefaultNamespace(c) => Component::DefaultNamespace(c.into_owned()),
1508      Component::Namespace(a, b) => Component::Namespace(a.into_owned(), b.into_owned()),
1509      Component::ExplicitUniversalType => Component::ExplicitUniversalType,
1510      Component::LocalName(c) => Component::LocalName(c.into_owned()),
1511      Component::ID(c) => Component::ID(c.into_owned()),
1512      Component::Class(c) => Component::Class(c.into_owned()),
1513      Component::AttributeInNoNamespaceExists {
1514        local_name,
1515        local_name_lower,
1516      } => Component::AttributeInNoNamespaceExists {
1517        local_name: local_name.into_owned(),
1518        local_name_lower: local_name_lower.into_owned(),
1519      },
1520      Component::AttributeInNoNamespace {
1521        local_name,
1522        operator,
1523        value,
1524        case_sensitivity,
1525        never_matches,
1526      } => {
1527        let value = value.into_owned();
1528        Component::AttributeInNoNamespace {
1529          local_name: local_name.into_owned(),
1530          operator,
1531          value,
1532          case_sensitivity,
1533          never_matches,
1534        }
1535      }
1536      Component::AttributeOther(c) => Component::AttributeOther(c.into_owned()),
1537      Component::Negation(c) => Component::Negation(c.into_owned()),
1538      Component::Root => Component::Root,
1539      Component::Empty => Component::Empty,
1540      Component::Scope => Component::Scope,
1541      Component::Nth(c) => Component::Nth(c.into_owned()),
1542      Component::NthOf(c) => Component::NthOf(c.into_owned()),
1543      Component::NonTSPseudoClass(c) => Component::NonTSPseudoClass(c.into_owned()),
1544      Component::Slotted(c) => Component::Slotted(c.into_owned()),
1545      Component::Part(c) => Component::Part(c.into_owned()),
1546      Component::Host(c) => Component::Host(c.into_owned()),
1547      Component::Where(c) => Component::Where(c.into_owned()),
1548      Component::Is(c) => Component::Is(c.into_owned()),
1549      Component::Any(a, b) => Component::Any(a.into_owned(), b.into_owned()),
1550      Component::Has(c) => Component::Has(c.into_owned()),
1551      Component::PseudoElement(c) => Component::PseudoElement(c.into_owned()),
1552      Component::Nesting => Component::Nesting,
1553    }
1554  }
1555}
1556
1557impl<'i, Impl: SelectorImpl<'i>> Component<'i, Impl> {
1558  /// Returns true if this is a combinator.
1559  pub fn is_combinator(&self) -> bool {
1560    matches!(*self, Component::Combinator(_))
1561  }
1562
1563  /// Returns the value as a combinator if applicable, None otherwise.
1564  pub fn as_combinator(&self) -> Option<Combinator> {
1565    match *self {
1566      Component::Combinator(c) => Some(c),
1567      _ => None,
1568    }
1569  }
1570
1571  /// Whether this component is valid after a pseudo-element. Only intended
1572  /// for sanity-checking.
1573  pub fn maybe_allowed_after_pseudo_element(&self) -> bool {
1574    match *self {
1575      Component::NonTSPseudoClass(..) => true,
1576      Component::Negation(ref selectors) | Component::Is(ref selectors) | Component::Where(ref selectors) => {
1577        selectors
1578          .iter()
1579          .all(|selector| selector.iter_raw_match_order().all(|c| c.maybe_allowed_after_pseudo_element()))
1580      }
1581      _ => false,
1582    }
1583  }
1584
1585  /// Whether a given selector should match for stateless pseudo-elements.
1586  ///
1587  /// This is a bit subtle: Only selectors that return true in
1588  /// `maybe_allowed_after_pseudo_element` should end up here, and
1589  /// `NonTSPseudoClass` never matches (as it is a stateless pseudo after
1590  /// all).
1591  fn matches_for_stateless_pseudo_element(&self) -> bool {
1592    debug_assert!(
1593      self.maybe_allowed_after_pseudo_element(),
1594      "Someone messed up pseudo-element parsing: {:?}",
1595      *self
1596    );
1597    match *self {
1598      Component::Negation(ref selectors) => !selectors.iter().all(|selector| {
1599        selector
1600          .iter_raw_match_order()
1601          .all(|c| c.matches_for_stateless_pseudo_element())
1602      }),
1603      Component::Is(ref selectors) | Component::Where(ref selectors) => selectors.iter().any(|selector| {
1604        selector
1605          .iter_raw_match_order()
1606          .all(|c| c.matches_for_stateless_pseudo_element())
1607      }),
1608      _ => false,
1609    }
1610  }
1611
1612  pub fn visit<V>(&self, visitor: &mut V) -> bool
1613  where
1614    V: SelectorVisitor<'i, Impl = Impl>,
1615  {
1616    use self::Component::*;
1617    if !visitor.visit_simple_selector(self) {
1618      return false;
1619    }
1620
1621    match *self {
1622      Slotted(ref selector) => {
1623        if !selector.visit(visitor) {
1624          return false;
1625        }
1626      }
1627      Host(Some(ref selector)) => {
1628        if !selector.visit(visitor) {
1629          return false;
1630        }
1631      }
1632      AttributeInNoNamespaceExists {
1633        ref local_name,
1634        ref local_name_lower,
1635      } => {
1636        if !visitor.visit_attribute_selector(
1637          &NamespaceConstraint::Specific(&namespace_empty_string::<Impl>()),
1638          local_name,
1639          local_name_lower,
1640        ) {
1641          return false;
1642        }
1643      }
1644      AttributeInNoNamespace {
1645        ref local_name,
1646        never_matches,
1647        ..
1648      } if !never_matches => {
1649        if !visitor.visit_attribute_selector(
1650          &NamespaceConstraint::Specific(&namespace_empty_string::<Impl>()),
1651          local_name,
1652          local_name,
1653        ) {
1654          return false;
1655        }
1656      }
1657      AttributeOther(ref attr_selector) if !attr_selector.never_matches => {
1658        let empty_string;
1659        let namespace = match attr_selector.namespace() {
1660          Some(ns) => ns,
1661          None => {
1662            empty_string = crate::parser::namespace_empty_string::<Impl>();
1663            NamespaceConstraint::Specific(&empty_string)
1664          }
1665        };
1666        if !visitor.visit_attribute_selector(
1667          &namespace,
1668          &attr_selector.local_name,
1669          &attr_selector.local_name_lower,
1670        ) {
1671          return false;
1672        }
1673      }
1674
1675      NonTSPseudoClass(ref pseudo_class) => {
1676        if !pseudo_class.visit(visitor) {
1677          return false;
1678        }
1679      }
1680
1681      Negation(ref list) | Is(ref list) | Where(ref list) => {
1682        if !visitor.visit_selector_list(list) {
1683          return false;
1684        }
1685      }
1686      NthOf(ref nth_of_data) if !visitor.visit_selector_list(nth_of_data.selectors()) => {
1687        return false;
1688      }
1689      _ => {}
1690    }
1691
1692    true
1693  }
1694}
1695
1696#[derive(Clone, Eq, PartialEq, Hash)]
1697pub struct LocalName<'i, Impl: SelectorImpl<'i>> {
1698  pub name: Impl::LocalName,
1699  pub lower_name: Impl::LocalName,
1700}
1701
1702#[cfg(feature = "into_owned")]
1703impl<'any, 'i, Impl: SelectorImpl<'i>, NewSel> rspack_lightningcss_static_self::IntoOwned<'any>
1704  for LocalName<'i, Impl>
1705where
1706  Impl: rspack_lightningcss_static_self::IntoOwned<'any, Owned = NewSel>,
1707  NewSel: SelectorImpl<'any>,
1708  Impl::LocalName: rspack_lightningcss_static_self::IntoOwned<'any, Owned = NewSel::LocalName>,
1709{
1710  type Owned = LocalName<'any, NewSel>;
1711
1712  fn into_owned(self) -> Self::Owned {
1713    LocalName {
1714      name: self.name.into_owned(),
1715      lower_name: self.lower_name.into_owned(),
1716    }
1717  }
1718}
1719
1720impl<'i, Impl: SelectorImpl<'i>> Debug for Selector<'i, Impl> {
1721  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1722    f.write_str("Selector(")?;
1723    self.to_css(f)?;
1724    write!(f, ", specificity = 0x{:x})", self.specificity())
1725  }
1726}
1727
1728impl<'i, Impl: SelectorImpl<'i>> Debug for Component<'i, Impl> {
1729  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1730    self.to_css(f)
1731  }
1732}
1733impl<'i, Impl: SelectorImpl<'i>> Debug for AttrSelectorWithOptionalNamespace<'i, Impl> {
1734  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1735    self.to_css(f)
1736  }
1737}
1738impl<'i, Impl: SelectorImpl<'i>> Debug for LocalName<'i, Impl> {
1739  fn fmt(&self, f: &mut fmt::Formatter) -> fmt::Result {
1740    self.to_css(f)
1741  }
1742}
1743
1744#[cfg(feature = "serde")]
1745impl<'i, Impl: SelectorImpl<'i>> serde::Serialize for LocalName<'i, Impl>
1746where
1747  Impl::LocalName: serde::Serialize,
1748{
1749  fn serialize<S>(&self, serializer: S) -> Result<S::Ok, S::Error>
1750  where
1751    S: serde::Serializer,
1752  {
1753    self.name.serialize(serializer)
1754  }
1755}
1756
1757#[cfg(feature = "serde")]
1758impl<'i, 'de: 'i, Impl: SelectorImpl<'i>> serde::Deserialize<'de> for LocalName<'i, Impl>
1759where
1760  Impl::LocalName: serde::Deserialize<'de>,
1761{
1762  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
1763  where
1764    D: serde::Deserializer<'de>,
1765  {
1766    let name = Impl::LocalName::deserialize(deserializer)?;
1767    let lower_name = to_ascii_lowercase(name.as_ref().to_string().into()).into();
1768    Ok(LocalName { name, lower_name })
1769  }
1770}
1771
1772fn serialize_selector_list<'a, 'i: 'a, Impl, I, W>(iter: I, dest: &mut W) -> fmt::Result
1773where
1774  Impl: SelectorImpl<'i>,
1775  I: Iterator<Item = &'a Selector<'i, Impl>>,
1776  W: fmt::Write,
1777{
1778  let mut first = true;
1779  for selector in iter {
1780    if !first {
1781      dest.write_str(", ")?;
1782    }
1783    first = false;
1784    selector.to_css(dest)?;
1785  }
1786  Ok(())
1787}
1788
1789impl<'i, Impl: SelectorImpl<'i>> ToCss for SelectorList<'i, Impl> {
1790  fn to_css<W>(&self, dest: &mut W) -> fmt::Result
1791  where
1792    W: fmt::Write,
1793  {
1794    serialize_selector_list(self.0.iter(), dest)
1795  }
1796}
1797
1798impl<'i, Impl: SelectorImpl<'i>> fmt::Display for SelectorList<'i, Impl> {
1799  fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> fmt::Result {
1800    Impl::to_css(self, f)
1801  }
1802}
1803
1804impl<'i, Impl: SelectorImpl<'i>> ToCss for Selector<'i, Impl> {
1805  fn to_css<W>(&self, dest: &mut W) -> fmt::Result
1806  where
1807    W: fmt::Write,
1808  {
1809    // Compound selectors invert the order of their contents, so we need to
1810    // undo that during serialization.
1811    //
1812    // This two-iterator strategy involves walking over the selector twice.
1813    // We could do something more clever, but selector serialization probably
1814    // isn't hot enough to justify it, and the stringification likely
1815    // dominates anyway.
1816    //
1817    // NB: A parse-order iterator is a Rev<>, which doesn't expose as_slice(),
1818    // which we need for |split|. So we split by combinators on a match-order
1819    // sequence and then reverse.
1820
1821    let mut combinators = self.iter_raw_match_order().rev().filter_map(|x| x.as_combinator());
1822    let compound_selectors = self.iter_raw_match_order().as_slice().split(|x| x.is_combinator()).rev();
1823
1824    let mut combinators_exhausted = false;
1825    for compound in compound_selectors {
1826      debug_assert!(!combinators_exhausted);
1827
1828      // https://drafts.csswg.org/cssom/#serializing-selectors
1829      if compound.is_empty() {
1830        continue;
1831      }
1832
1833      // 1. If there is only one simple selector in the compound selectors
1834      //    which is a universal selector, append the result of
1835      //    serializing the universal selector to s.
1836      //
1837      // Check if `!compound.empty()` first--this can happen if we have
1838      // something like `... > ::before`, because we store `>` and `::`
1839      // both as combinators internally.
1840      //
1841      // If we are in this case, after we have serialized the universal
1842      // selector, we skip Step 2 and continue with the algorithm.
1843      let (can_elide_namespace, first_non_namespace) = match compound[0] {
1844        Component::ExplicitAnyNamespace | Component::ExplicitNoNamespace | Component::Namespace(..) => (false, 1),
1845        Component::DefaultNamespace(..) => (true, 1),
1846        _ => (true, 0),
1847      };
1848      let mut perform_step_2 = true;
1849      let next_combinator = combinators.next();
1850      if first_non_namespace == compound.len() - 1 {
1851        match (next_combinator, &compound[first_non_namespace]) {
1852          // We have to be careful here, because if there is a
1853          // pseudo element "combinator" there isn't really just
1854          // the one simple selector. Technically this compound
1855          // selector contains the pseudo element selector as well
1856          // -- Combinator::PseudoElement, just like
1857          // Combinator::SlotAssignment, don't exist in the
1858          // spec.
1859          (Some(Combinator::PseudoElement), _) | (Some(Combinator::SlotAssignment), _) => (),
1860          (_, &Component::ExplicitUniversalType) => {
1861            // Iterate over everything so we serialize the namespace
1862            // too.
1863            for simple in compound.iter() {
1864              simple.to_css(dest)?;
1865            }
1866            // Skip step 2, which is an "otherwise".
1867            perform_step_2 = false;
1868          }
1869          _ => (),
1870        }
1871      }
1872
1873      // 2. Otherwise, for each simple selector in the compound selectors
1874      //    that is not a universal selector of which the namespace prefix
1875      //    maps to a namespace that is not the default namespace
1876      //    serialize the simple selector and append the result to s.
1877      //
1878      // See https://github.com/w3c/csswg-drafts/issues/1606, which is
1879      // proposing to change this to match up with the behavior asserted
1880      // in cssom/serialize-namespaced-type-selectors.html, which the
1881      // following code tries to match.
1882      if perform_step_2 {
1883        for simple in compound.iter() {
1884          if let Component::ExplicitUniversalType = *simple {
1885            // Can't have a namespace followed by a pseudo-element
1886            // selector followed by a universal selector in the same
1887            // compound selector, so we don't have to worry about the
1888            // real namespace being in a different `compound`.
1889            if can_elide_namespace {
1890              continue;
1891            }
1892          }
1893          simple.to_css(dest)?;
1894        }
1895      }
1896
1897      // 3. If this is not the last part of the chain of the selector
1898      //    append a single SPACE (U+0020), followed by the combinator
1899      //    ">", "+", "~", ">>", "||", as appropriate, followed by another
1900      //    single SPACE (U+0020) if the combinator was not whitespace, to
1901      //    s.
1902      match next_combinator {
1903        Some(c) => c.to_css(dest)?,
1904        None => combinators_exhausted = true,
1905      };
1906
1907      // 4. If this is the last part of the chain of the selector and
1908      //    there is a pseudo-element, append "::" followed by the name of
1909      //    the pseudo-element, to s.
1910      //
1911      // (we handle this above)
1912    }
1913
1914    Ok(())
1915  }
1916}
1917
1918impl ToCss for Combinator {
1919  fn to_css<W>(&self, dest: &mut W) -> fmt::Result
1920  where
1921    W: fmt::Write,
1922  {
1923    match *self {
1924      Combinator::Child => dest.write_str(" > "),
1925      Combinator::Descendant => dest.write_str(" "),
1926      Combinator::NextSibling => dest.write_str(" + "),
1927      Combinator::LaterSibling => dest.write_str(" ~ "),
1928      Combinator::DeepDescendant => dest.write_str(" >>> "),
1929      Combinator::Deep => dest.write_str(" /deep/ "),
1930      Combinator::PseudoElement | Combinator::Part | Combinator::SlotAssignment => Ok(()),
1931    }
1932  }
1933}
1934
1935impl<'i, Impl: SelectorImpl<'i>> ToCss for Component<'i, Impl> {
1936  fn to_css<W>(&self, dest: &mut W) -> fmt::Result
1937  where
1938    W: fmt::Write,
1939  {
1940    use self::Component::*;
1941
1942    match *self {
1943      Combinator(ref c) => c.to_css(dest),
1944      Slotted(ref selector) => {
1945        dest.write_str("::slotted(")?;
1946        selector.to_css(dest)?;
1947        dest.write_char(')')
1948      }
1949      Part(ref part_names) => {
1950        dest.write_str("::part(")?;
1951        for (i, name) in part_names.iter().enumerate() {
1952          if i != 0 {
1953            dest.write_char(' ')?;
1954          }
1955          name.to_css(dest)?;
1956        }
1957        dest.write_char(')')
1958      }
1959      PseudoElement(ref p) => p.to_css(dest),
1960      ID(ref s) => {
1961        dest.write_char('#')?;
1962        s.to_css(dest)
1963      }
1964      Class(ref s) => {
1965        dest.write_char('.')?;
1966        s.to_css(dest)
1967      }
1968      LocalName(ref s) => s.to_css(dest),
1969      ExplicitUniversalType => dest.write_char('*'),
1970
1971      DefaultNamespace(_) => Ok(()),
1972      ExplicitNoNamespace => dest.write_char('|'),
1973      ExplicitAnyNamespace => dest.write_str("*|"),
1974      Namespace(ref prefix, _) => {
1975        prefix.to_css(dest)?;
1976        dest.write_char('|')
1977      }
1978
1979      AttributeInNoNamespaceExists { ref local_name, .. } => {
1980        dest.write_char('[')?;
1981        local_name.to_css(dest)?;
1982        dest.write_char(']')
1983      }
1984      AttributeInNoNamespace {
1985        ref local_name,
1986        operator,
1987        ref value,
1988        case_sensitivity,
1989        ..
1990      } => {
1991        dest.write_char('[')?;
1992        local_name.to_css(dest)?;
1993        operator.to_css(dest)?;
1994        value.to_css(dest)?;
1995        match case_sensitivity {
1996          ParsedCaseSensitivity::CaseSensitive
1997          | ParsedCaseSensitivity::AsciiCaseInsensitiveIfInHtmlElementInHtmlDocument => {}
1998          ParsedCaseSensitivity::AsciiCaseInsensitive => dest.write_str(" i")?,
1999          ParsedCaseSensitivity::ExplicitCaseSensitive => dest.write_str(" s")?,
2000        }
2001        dest.write_char(']')
2002      }
2003      AttributeOther(ref attr_selector) => attr_selector.to_css(dest),
2004
2005      // Pseudo-classes
2006      Root => dest.write_str(":root"),
2007      Empty => dest.write_str(":empty"),
2008      Scope => dest.write_str(":scope"),
2009      Host(ref selector) => {
2010        dest.write_str(":host")?;
2011        if let Some(ref selector) = *selector {
2012          dest.write_char('(')?;
2013          selector.to_css(dest)?;
2014          dest.write_char(')')?;
2015        }
2016        Ok(())
2017      }
2018      Nth(ref nth_data) => {
2019        nth_data.write_start(dest, nth_data.is_function())?;
2020        if nth_data.is_function() {
2021          nth_data.write_affine(dest)?;
2022          dest.write_char(')')?;
2023        }
2024        Ok(())
2025      }
2026      NthOf(ref nth_of_data) => {
2027        let nth_data = nth_of_data.nth_data();
2028        nth_data.write_start(dest, true)?;
2029        debug_assert!(
2030          nth_data.is_function,
2031          "A selector must be a function to hold An+B notation"
2032        );
2033        nth_data.write_affine(dest)?;
2034        debug_assert!(
2035          matches!(nth_data.ty, NthType::Child | NthType::LastChild),
2036          "Only :nth-child or :nth-last-child can be of a selector list"
2037        );
2038        debug_assert!(
2039          !nth_of_data.selectors().is_empty(),
2040          "The selector list should not be empty"
2041        );
2042        dest.write_str(" of ")?;
2043        serialize_selector_list(nth_of_data.selectors().iter(), dest)?;
2044        dest.write_char(')')
2045      }
2046      Is(ref list) | Where(ref list) | Negation(ref list) | Has(ref list) | Any(_, ref list) => {
2047        match *self {
2048          Where(..) => dest.write_str(":where(")?,
2049          Is(..) => dest.write_str(":is(")?,
2050          Negation(..) => dest.write_str(":not(")?,
2051          Has(..) => dest.write_str(":has(")?,
2052          Any(ref prefix, _) => {
2053            dest.write_char(':')?;
2054            prefix.to_css(dest)?;
2055            dest.write_str("any(")?;
2056          }
2057          _ => unreachable!(),
2058        }
2059        serialize_selector_list(list.iter(), dest)?;
2060        dest.write_str(")")
2061      }
2062      NonTSPseudoClass(ref pseudo) => pseudo.to_css(dest),
2063      Nesting => dest.write_char('&'),
2064    }
2065  }
2066}
2067
2068impl<'i, Impl: SelectorImpl<'i>> ToCss for AttrSelectorWithOptionalNamespace<'i, Impl> {
2069  fn to_css<W>(&self, dest: &mut W) -> fmt::Result
2070  where
2071    W: fmt::Write,
2072  {
2073    dest.write_char('[')?;
2074    match self.namespace {
2075      Some(NamespaceConstraint::Specific((ref prefix, _))) => {
2076        prefix.to_css(dest)?;
2077        dest.write_char('|')?
2078      }
2079      Some(NamespaceConstraint::Any) => dest.write_str("*|")?,
2080      None => {}
2081    }
2082    self.local_name.to_css(dest)?;
2083    match self.operation {
2084      ParsedAttrSelectorOperation::Exists => {}
2085      ParsedAttrSelectorOperation::WithValue {
2086        operator,
2087        case_sensitivity,
2088        ref expected_value,
2089      } => {
2090        operator.to_css(dest)?;
2091        expected_value.to_css(dest)?;
2092        match case_sensitivity {
2093          ParsedCaseSensitivity::CaseSensitive
2094          | ParsedCaseSensitivity::AsciiCaseInsensitiveIfInHtmlElementInHtmlDocument => {}
2095          ParsedCaseSensitivity::AsciiCaseInsensitive => dest.write_str(" i")?,
2096          ParsedCaseSensitivity::ExplicitCaseSensitive => dest.write_str(" s")?,
2097        }
2098      }
2099    }
2100    dest.write_char(']')
2101  }
2102}
2103
2104impl<'i, Impl: SelectorImpl<'i>> ToCss for LocalName<'i, Impl> {
2105  fn to_css<W>(&self, dest: &mut W) -> fmt::Result
2106  where
2107    W: fmt::Write,
2108  {
2109    self.name.to_css(dest)
2110  }
2111}
2112
2113/// Build up a Selector.
2114/// selector : simple_selector_sequence [ combinator simple_selector_sequence ]* ;
2115///
2116/// `Err` means invalid selector.
2117fn parse_selector<'i, 't, P, Impl>(
2118  parser: &P,
2119  input: &mut CssParser<'i, 't>,
2120  state: &mut SelectorParsingState,
2121  nesting_requirement: NestingRequirement,
2122) -> Result<Selector<'i, Impl>, ParseError<'i, P::Error>>
2123where
2124  P: Parser<'i, Impl = Impl>,
2125  Impl: SelectorImpl<'i>,
2126{
2127  if nesting_requirement == NestingRequirement::Prefixed {
2128    let state = input.state();
2129    if input.expect_delim('&').is_err() {
2130      return Err(input.new_custom_error(SelectorParseErrorKind::MissingNestingPrefix));
2131    }
2132    input.reset(&state);
2133  }
2134
2135  let mut builder = SelectorBuilder::default();
2136
2137  'outer_loop: loop {
2138    // Parse a sequence of simple selectors.
2139    let empty = parse_compound_selector(parser, state, input, &mut builder)?;
2140    if empty {
2141      return Err(input.new_custom_error(if builder.has_combinators() {
2142        SelectorParseErrorKind::DanglingCombinator
2143      } else {
2144        SelectorParseErrorKind::EmptySelector
2145      }));
2146    }
2147
2148    if state.intersects(SelectorParsingState::AFTER_PSEUDO) {
2149      // Input should be exhausted here.
2150      let source_location = input.current_source_location();
2151      if let Ok(next) = input.next() {
2152        let next = next.clone();
2153        return Err(
2154          source_location.new_custom_error(SelectorParseErrorKind::UnexpectedSelectorAfterPseudoElement(next)),
2155        );
2156      }
2157      break;
2158    }
2159
2160    // Parse a combinator.
2161    let combinator;
2162    let mut any_whitespace = false;
2163    loop {
2164      let before_this_token = input.state();
2165      match input.next_including_whitespace() {
2166        Err(_e) => break 'outer_loop,
2167        Ok(&Token::WhiteSpace(_)) => any_whitespace = true,
2168        Ok(&Token::Delim('>')) => {
2169          if parser.deep_combinator_enabled()
2170            && input
2171              .try_parse(|input| {
2172                input.expect_delim('>')?;
2173                input.expect_delim('>')
2174              })
2175              .is_ok()
2176          {
2177            combinator = Combinator::DeepDescendant;
2178          } else {
2179            combinator = Combinator::Child;
2180          }
2181          break;
2182        }
2183        Ok(&Token::Delim('+')) => {
2184          combinator = Combinator::NextSibling;
2185          break;
2186        }
2187        Ok(&Token::Delim('~')) => {
2188          combinator = Combinator::LaterSibling;
2189          break;
2190        }
2191        Ok(&Token::Delim('/')) if parser.deep_combinator_enabled() => {
2192          if input
2193            .try_parse(|input| {
2194              input.expect_ident_matching("deep")?;
2195              input.expect_delim('/')
2196            })
2197            .is_ok()
2198          {
2199            combinator = Combinator::Deep;
2200            break;
2201          } else {
2202            break 'outer_loop;
2203          }
2204        }
2205        Ok(_) => {
2206          input.reset(&before_this_token);
2207          if any_whitespace {
2208            combinator = Combinator::Descendant;
2209            break;
2210          } else {
2211            break 'outer_loop;
2212          }
2213        }
2214      }
2215    }
2216
2217    if !state.allows_combinators() {
2218      return Err(input.new_custom_error(SelectorParseErrorKind::InvalidState));
2219    }
2220
2221    builder.push_combinator(combinator);
2222  }
2223
2224  if !state.contains(SelectorParsingState::AFTER_NESTING) {
2225    match nesting_requirement {
2226      NestingRequirement::Implicit => {
2227        builder.add_nesting_prefix();
2228      }
2229      NestingRequirement::Contained | NestingRequirement::Prefixed => {
2230        return Err(input.new_custom_error(SelectorParseErrorKind::MissingNestingSelector));
2231      }
2232      _ => {}
2233    }
2234  }
2235
2236  let has_pseudo_element = state
2237    .intersects(SelectorParsingState::AFTER_PSEUDO_ELEMENT | SelectorParsingState::AFTER_UNKNOWN_PSEUDO_ELEMENT);
2238  let slotted = state.intersects(SelectorParsingState::AFTER_SLOTTED);
2239  let part = state.intersects(SelectorParsingState::AFTER_PART);
2240  let (spec, components) = builder.build(has_pseudo_element, slotted, part);
2241  Ok(Selector(spec, components))
2242}
2243
2244impl<'i, Impl: SelectorImpl<'i>> Selector<'i, Impl> {
2245  /// Parse a selector, without any pseudo-element.
2246  #[inline]
2247  pub fn parse<'t, P>(parser: &P, input: &mut CssParser<'i, 't>) -> Result<Self, ParseError<'i, P::Error>>
2248  where
2249    P: Parser<'i, Impl = Impl>,
2250  {
2251    parse_selector(
2252      parser,
2253      input,
2254      &mut SelectorParsingState::empty(),
2255      NestingRequirement::None,
2256    )
2257  }
2258}
2259
2260fn parse_relative_selector<'i, 't, P, Impl>(
2261  parser: &P,
2262  input: &mut CssParser<'i, 't>,
2263  state: &mut SelectorParsingState,
2264  mut nesting_requirement: NestingRequirement,
2265) -> Result<Selector<'i, Impl>, ParseError<'i, P::Error>>
2266where
2267  P: Parser<'i, Impl = Impl>,
2268  Impl: SelectorImpl<'i>,
2269{
2270  // https://www.w3.org/TR/selectors-4/#parse-relative-selector
2271  let s = input.state();
2272  let combinator = match input.next()? {
2273    Token::Delim('>') => Some(Combinator::Child),
2274    Token::Delim('+') => Some(Combinator::NextSibling),
2275    Token::Delim('~') => Some(Combinator::LaterSibling),
2276    _ => {
2277      input.reset(&s);
2278      None
2279    }
2280  };
2281
2282  let scope = if nesting_requirement == NestingRequirement::Implicit {
2283    Component::Nesting
2284  } else {
2285    Component::Scope
2286  };
2287
2288  if combinator.is_some() {
2289    nesting_requirement = NestingRequirement::None;
2290  }
2291
2292  let mut selector = parse_selector(parser, input, state, nesting_requirement)?;
2293  if let Some(combinator) = combinator {
2294    // https://www.w3.org/TR/selectors/#absolutizing
2295    selector.1.push(Component::Combinator(combinator));
2296    selector.1.push(scope);
2297  }
2298
2299  Ok(selector)
2300}
2301
2302/// * `Err(())`: Invalid selector, abort
2303/// * `Ok(false)`: Not a type selector, could be something else. `input` was not consumed.
2304/// * `Ok(true)`: Length 0 (`*|*`), 1 (`*|E` or `ns|*`) or 2 (`|E` or `ns|E`)
2305fn parse_type_selector<'i, 't, P, Impl, S>(
2306  parser: &P,
2307  input: &mut CssParser<'i, 't>,
2308  state: SelectorParsingState,
2309  sink: &mut S,
2310) -> Result<bool, ParseError<'i, P::Error>>
2311where
2312  P: Parser<'i, Impl = Impl>,
2313  Impl: SelectorImpl<'i>,
2314  S: Push<Component<'i, Impl>>,
2315{
2316  match parse_qualified_name(parser, input, /* in_attr_selector = */ false) {
2317    Err(ParseError {
2318      kind: ParseErrorKind::Basic(BasicParseErrorKind::EndOfInput),
2319      ..
2320    })
2321    | Ok(OptionalQName::None(_)) => Ok(false),
2322    Ok(OptionalQName::Some(namespace, local_name)) => {
2323      if state.intersects(SelectorParsingState::AFTER_PSEUDO) {
2324        return Err(input.new_custom_error(SelectorParseErrorKind::InvalidState));
2325      }
2326      match namespace {
2327        QNamePrefix::ImplicitAnyNamespace => {}
2328        QNamePrefix::ImplicitDefaultNamespace(url) => sink.push(Component::DefaultNamespace(url)),
2329        QNamePrefix::ExplicitNamespace(prefix, url) => sink.push(match parser.default_namespace() {
2330          Some(ref default_url) if url == *default_url => Component::DefaultNamespace(url),
2331          _ => Component::Namespace(prefix, url),
2332        }),
2333        QNamePrefix::ExplicitNoNamespace => sink.push(Component::ExplicitNoNamespace),
2334        QNamePrefix::ExplicitAnyNamespace => {
2335          // Element type selectors that have no namespace
2336          // component (no namespace separator) represent elements
2337          // without regard to the element's namespace (equivalent
2338          // to "*|") unless a default namespace has been declared
2339          // for namespaced selectors (e.g. in CSS, in the style
2340          // sheet). If a default namespace has been declared,
2341          // such selectors will represent only elements in the
2342          // default namespace.
2343          // -- Selectors § 6.1.1
2344          // So we'll have this act the same as the
2345          // QNamePrefix::ImplicitAnyNamespace case.
2346          // For lightning css this logic was removed, should be handled when matching.
2347          sink.push(Component::ExplicitAnyNamespace)
2348        }
2349        QNamePrefix::ImplicitNoNamespace => {
2350          unreachable!() // Not returned with in_attr_selector = false
2351        }
2352      }
2353      match local_name {
2354        Some(name) => sink.push(Component::LocalName(LocalName {
2355          lower_name: to_ascii_lowercase(name.clone()).into(),
2356          name: name.into(),
2357        })),
2358        None => sink.push(Component::ExplicitUniversalType),
2359      }
2360      Ok(true)
2361    }
2362    Err(e) => Err(e),
2363  }
2364}
2365
2366#[derive(Debug)]
2367enum SimpleSelectorParseResult<'i, Impl: SelectorImpl<'i>> {
2368  SimpleSelector(Component<'i, Impl>),
2369  PseudoElement(Impl::PseudoElement),
2370  SlottedPseudo(Selector<'i, Impl>),
2371  PartPseudo(Box<[Impl::Identifier]>),
2372}
2373
2374#[derive(Debug)]
2375enum QNamePrefix<'i, Impl: SelectorImpl<'i>> {
2376  ImplicitNoNamespace,                                          // `foo` in attr selectors
2377  ImplicitAnyNamespace,                                         // `foo` in type selectors, without a default ns
2378  ImplicitDefaultNamespace(Impl::NamespaceUrl),                 // `foo` in type selectors, with a default ns
2379  ExplicitNoNamespace,                                          // `|foo`
2380  ExplicitAnyNamespace,                                         // `*|foo`
2381  ExplicitNamespace(Impl::NamespacePrefix, Impl::NamespaceUrl), // `prefix|foo`
2382}
2383
2384enum OptionalQName<'i, Impl: SelectorImpl<'i>> {
2385  Some(QNamePrefix<'i, Impl>, Option<CowRcStr<'i>>),
2386  None(Token<'i>),
2387}
2388
2389/// * `Err(())`: Invalid selector, abort
2390/// * `Ok(None(token))`: Not a simple selector, could be something else. `input` was not consumed,
2391///                      but the token is still returned.
2392/// * `Ok(Some(namespace, local_name))`: `None` for the local name means a `*` universal selector
2393fn parse_qualified_name<'i, 't, P, Impl>(
2394  parser: &P,
2395  input: &mut CssParser<'i, 't>,
2396  in_attr_selector: bool,
2397) -> Result<OptionalQName<'i, Impl>, ParseError<'i, P::Error>>
2398where
2399  P: Parser<'i, Impl = Impl>,
2400  Impl: SelectorImpl<'i>,
2401{
2402  let default_namespace = |local_name| {
2403    let namespace = match parser.default_namespace() {
2404      Some(url) => QNamePrefix::ImplicitDefaultNamespace(url),
2405      None => QNamePrefix::ImplicitAnyNamespace,
2406    };
2407    Ok(OptionalQName::Some(namespace, local_name))
2408  };
2409
2410  let explicit_namespace = |input: &mut CssParser<'i, 't>, namespace| {
2411    let location = input.current_source_location();
2412    match input.next_including_whitespace() {
2413      Ok(&Token::Delim('*')) if !in_attr_selector => Ok(OptionalQName::Some(namespace, None)),
2414      Ok(Token::Ident(local_name)) => Ok(OptionalQName::Some(namespace, Some(local_name.clone()))),
2415      Ok(t) if in_attr_selector => {
2416        let e = SelectorParseErrorKind::InvalidQualNameInAttr(t.clone());
2417        Err(location.new_custom_error(e))
2418      }
2419      Ok(t) => Err(location.new_custom_error(SelectorParseErrorKind::ExplicitNamespaceUnexpectedToken(t.clone()))),
2420      Err(e) => Err(e.into()),
2421    }
2422  };
2423
2424  let start = input.state();
2425  // FIXME: remove clone() when lifetimes are non-lexical
2426  match input.next_including_whitespace().cloned() {
2427    Ok(Token::Ident(value)) => {
2428      let after_ident = input.state();
2429      match input.next_including_whitespace() {
2430        Ok(&Token::Delim('|')) => {
2431          let prefix = value.clone().into();
2432          let result = parser.namespace_for_prefix(&prefix);
2433          let url = result.ok_or(
2434            after_ident
2435              .source_location()
2436              .new_custom_error(SelectorParseErrorKind::ExpectedNamespace(value)),
2437          )?;
2438          explicit_namespace(input, QNamePrefix::ExplicitNamespace(prefix, url))
2439        }
2440        _ => {
2441          input.reset(&after_ident);
2442          if in_attr_selector {
2443            Ok(OptionalQName::Some(QNamePrefix::ImplicitNoNamespace, Some(value)))
2444          } else {
2445            default_namespace(Some(value))
2446          }
2447        }
2448      }
2449    }
2450    Ok(Token::Delim('*')) => {
2451      let after_star = input.state();
2452      // FIXME: remove clone() when lifetimes are non-lexical
2453      match input.next_including_whitespace().cloned() {
2454        Ok(Token::Delim('|')) => explicit_namespace(input, QNamePrefix::ExplicitAnyNamespace),
2455        result => {
2456          input.reset(&after_star);
2457          if in_attr_selector {
2458            match result {
2459              Ok(t) => Err(
2460                after_star
2461                  .source_location()
2462                  .new_custom_error(SelectorParseErrorKind::ExpectedBarInAttr(t)),
2463              ),
2464              Err(e) => Err(e.into()),
2465            }
2466          } else {
2467            default_namespace(None)
2468          }
2469        }
2470      }
2471    }
2472    Ok(Token::Delim('|')) => explicit_namespace(input, QNamePrefix::ExplicitNoNamespace),
2473    Ok(t) => {
2474      input.reset(&start);
2475      Ok(OptionalQName::None(t))
2476    }
2477    Err(e) => {
2478      input.reset(&start);
2479      Err(e.into())
2480    }
2481  }
2482}
2483
2484fn parse_attribute_selector<'i, 't, P, Impl>(
2485  parser: &P,
2486  input: &mut CssParser<'i, 't>,
2487) -> Result<Component<'i, Impl>, ParseError<'i, P::Error>>
2488where
2489  P: Parser<'i, Impl = Impl>,
2490  Impl: SelectorImpl<'i>,
2491{
2492  let namespace;
2493  let local_name;
2494
2495  input.skip_whitespace();
2496
2497  match parse_qualified_name(parser, input, /* in_attr_selector = */ true)? {
2498    OptionalQName::None(t) => {
2499      return Err(input.new_custom_error(SelectorParseErrorKind::NoQualifiedNameInAttributeSelector(t)));
2500    }
2501    OptionalQName::Some(_, None) => unreachable!(),
2502    OptionalQName::Some(ns, Some(ln)) => {
2503      local_name = ln;
2504      namespace = match ns {
2505        QNamePrefix::ImplicitNoNamespace | QNamePrefix::ExplicitNoNamespace => None,
2506        QNamePrefix::ExplicitNamespace(prefix, url) => Some(NamespaceConstraint::Specific((prefix, url))),
2507        QNamePrefix::ExplicitAnyNamespace => Some(NamespaceConstraint::Any),
2508        QNamePrefix::ImplicitAnyNamespace | QNamePrefix::ImplicitDefaultNamespace(_) => {
2509          unreachable!() // Not returned with in_attr_selector = true
2510        }
2511      }
2512    }
2513  }
2514
2515  let location = input.current_source_location();
2516  let operator = match input.next() {
2517    // [foo]
2518    Err(_) => {
2519      let local_name_lower = to_ascii_lowercase(local_name.clone()).into();
2520      let local_name = local_name.into();
2521      if let Some(namespace) = namespace {
2522        return Ok(Component::AttributeOther(Box::new(AttrSelectorWithOptionalNamespace {
2523          namespace: Some(namespace),
2524          local_name,
2525          local_name_lower,
2526          operation: ParsedAttrSelectorOperation::Exists,
2527          never_matches: false,
2528        })));
2529      } else {
2530        return Ok(Component::AttributeInNoNamespaceExists {
2531          local_name,
2532          local_name_lower,
2533        });
2534      }
2535    }
2536
2537    // [foo=bar]
2538    Ok(&Token::Delim('=')) => AttrSelectorOperator::Equal,
2539    // [foo~=bar]
2540    Ok(&Token::IncludeMatch) => AttrSelectorOperator::Includes,
2541    // [foo|=bar]
2542    Ok(&Token::DashMatch) => AttrSelectorOperator::DashMatch,
2543    // [foo^=bar]
2544    Ok(&Token::PrefixMatch) => AttrSelectorOperator::Prefix,
2545    // [foo*=bar]
2546    Ok(&Token::SubstringMatch) => AttrSelectorOperator::Substring,
2547    // [foo$=bar]
2548    Ok(&Token::SuffixMatch) => AttrSelectorOperator::Suffix,
2549    Ok(t) => {
2550      return Err(
2551        location.new_custom_error(SelectorParseErrorKind::UnexpectedTokenInAttributeSelector(t.clone())),
2552      );
2553    }
2554  };
2555
2556  let value = match input.expect_ident_or_string() {
2557    Ok(t) => t.clone(),
2558    Err(BasicParseError {
2559      kind: BasicParseErrorKind::UnexpectedToken(t),
2560      location,
2561    }) => return Err(location.new_custom_error(SelectorParseErrorKind::BadValueInAttr(t))),
2562    Err(e) => return Err(e.into()),
2563  };
2564  let never_matches = match operator {
2565    AttrSelectorOperator::Equal | AttrSelectorOperator::DashMatch => false,
2566
2567    AttrSelectorOperator::Includes => value.is_empty() || value.contains(SELECTOR_WHITESPACE),
2568
2569    AttrSelectorOperator::Prefix | AttrSelectorOperator::Substring | AttrSelectorOperator::Suffix => {
2570      value.is_empty()
2571    }
2572  };
2573
2574  let attribute_flags = parse_attribute_flags(input)?;
2575
2576  let value = value.into();
2577
2578  // copied from to_ascii_lowercase function, so we can know whether it is already lower case.
2579  let (local_name_lower_cow, local_name_is_ascii_lowercase) =
2580    if let Some(first_uppercase) = local_name.bytes().position(|byte: u8| byte.is_ascii_uppercase()) {
2581      let mut string = local_name.to_string();
2582      string[first_uppercase..].make_ascii_lowercase();
2583      (string.into(), false)
2584    } else {
2585      (local_name.clone(), true)
2586    };
2587  let case_sensitivity = attribute_flags.to_case_sensitivity(local_name_lower_cow.as_ref(), namespace.is_some());
2588  let local_name_lower = local_name_lower_cow.into();
2589  let local_name = local_name.into();
2590  if namespace.is_some() || !local_name_is_ascii_lowercase {
2591    Ok(Component::AttributeOther(Box::new(AttrSelectorWithOptionalNamespace {
2592      namespace,
2593      local_name,
2594      local_name_lower,
2595      never_matches,
2596      operation: ParsedAttrSelectorOperation::WithValue {
2597        operator,
2598        case_sensitivity,
2599        expected_value: value,
2600      },
2601    })))
2602  } else {
2603    Ok(Component::AttributeInNoNamespace {
2604      local_name,
2605      operator,
2606      value,
2607      case_sensitivity,
2608      never_matches,
2609    })
2610  }
2611}
2612
2613/// An attribute selector can have 's' or 'i' as flags, or no flags at all.
2614enum AttributeFlags {
2615  // Matching should be case-sensitive ('s' flag).
2616  CaseSensitive,
2617  // Matching should be case-insensitive ('i' flag).
2618  AsciiCaseInsensitive,
2619  // No flags.  Matching behavior depends on the name of the attribute.
2620  CaseSensitivityDependsOnName,
2621}
2622
2623impl AttributeFlags {
2624  fn to_case_sensitivity(self, local_name: &str, have_namespace: bool) -> ParsedCaseSensitivity {
2625    match self {
2626      AttributeFlags::CaseSensitive => ParsedCaseSensitivity::ExplicitCaseSensitive,
2627      AttributeFlags::AsciiCaseInsensitive => ParsedCaseSensitivity::AsciiCaseInsensitive,
2628      AttributeFlags::CaseSensitivityDependsOnName => {
2629        if !have_namespace
2630          && include!(concat!(env!("OUT_DIR"), "/ascii_case_insensitive_html_attributes.rs")).contains(local_name)
2631        {
2632          ParsedCaseSensitivity::AsciiCaseInsensitiveIfInHtmlElementInHtmlDocument
2633        } else {
2634          ParsedCaseSensitivity::CaseSensitive
2635        }
2636      }
2637    }
2638  }
2639}
2640
2641fn parse_attribute_flags<'i, 't>(input: &mut CssParser<'i, 't>) -> Result<AttributeFlags, BasicParseError<'i>> {
2642  let location = input.current_source_location();
2643  let token = match input.next() {
2644    Ok(t) => t,
2645    Err(..) => {
2646      // Selectors spec says language-defined; HTML says it depends on the
2647      // exact attribute name.
2648      return Ok(AttributeFlags::CaseSensitivityDependsOnName);
2649    }
2650  };
2651
2652  let ident = match *token {
2653    Token::Ident(ref i) => i,
2654    ref other => return Err(location.new_basic_unexpected_token_error(other.clone())),
2655  };
2656
2657  Ok(match_ignore_ascii_case! {
2658      ident,
2659      "i" => AttributeFlags::AsciiCaseInsensitive,
2660      "s" => AttributeFlags::CaseSensitive,
2661      _ => return Err(location.new_basic_unexpected_token_error(token.clone())),
2662  })
2663}
2664
2665/// Level 3: Parse **one** simple_selector.  (Though we might insert a second
2666/// implied "<defaultns>|*" type selector.)
2667fn parse_negation<'i, 't, P, Impl>(
2668  parser: &P,
2669  input: &mut CssParser<'i, 't>,
2670  state: &mut SelectorParsingState,
2671) -> Result<Component<'i, Impl>, ParseError<'i, P::Error>>
2672where
2673  P: Parser<'i, Impl = Impl>,
2674  Impl: SelectorImpl<'i>,
2675{
2676  let mut child_state =
2677    *state | SelectorParsingState::SKIP_DEFAULT_NAMESPACE | SelectorParsingState::DISALLOW_PSEUDOS;
2678  let list = SelectorList::parse_with_state(
2679    parser,
2680    input,
2681    &mut child_state,
2682    ParseErrorRecovery::DiscardList,
2683    NestingRequirement::None,
2684  )?;
2685
2686  if child_state.contains(SelectorParsingState::AFTER_NESTING) {
2687    state.insert(SelectorParsingState::AFTER_NESTING)
2688  }
2689
2690  Ok(Component::Negation(list.0.into_vec().into_boxed_slice()))
2691}
2692
2693/// simple_selector_sequence
2694/// : [ type_selector | universal ] [ HASH | class | attrib | pseudo | negation ]*
2695/// | [ HASH | class | attrib | pseudo | negation ]+
2696///
2697/// `Err(())` means invalid selector.
2698/// `Ok(true)` is an empty selector
2699fn parse_compound_selector<'i, 't, P, Impl>(
2700  parser: &P,
2701  state: &mut SelectorParsingState,
2702  input: &mut CssParser<'i, 't>,
2703  builder: &mut SelectorBuilder<'i, Impl>,
2704) -> Result<bool, ParseError<'i, P::Error>>
2705where
2706  P: Parser<'i, Impl = Impl>,
2707  Impl: SelectorImpl<'i>,
2708{
2709  input.skip_whitespace();
2710
2711  let mut empty = true;
2712  if parser.is_nesting_allowed() && input.try_parse(|input| input.expect_delim('&')).is_ok() {
2713    state.insert(SelectorParsingState::AFTER_NESTING);
2714    builder.push_simple_selector(Component::Nesting);
2715    empty = false;
2716  }
2717
2718  if parse_type_selector(parser, input, *state, builder)? {
2719    empty = false;
2720  }
2721
2722  loop {
2723    let result = match parse_one_simple_selector(parser, input, state)? {
2724      None => break,
2725      Some(result) => result,
2726    };
2727
2728    if empty {
2729      if let Some(url) = parser.default_namespace() {
2730        // If there was no explicit type selector, but there is a
2731        // default namespace, there is an implicit "<defaultns>|*" type
2732        // selector. Except for :host() or :not() / :is() / :where(),
2733        // where we ignore it.
2734        //
2735        // https://drafts.csswg.org/css-scoping/#host-element-in-tree:
2736        //
2737        //     When considered within its own shadow trees, the shadow
2738        //     host is featureless. Only the :host, :host(), and
2739        //     :host-context() pseudo-classes are allowed to match it.
2740        //
2741        // https://drafts.csswg.org/selectors-4/#featureless:
2742        //
2743        //     A featureless element does not match any selector at all,
2744        //     except those it is explicitly defined to match. If a
2745        //     given selector is allowed to match a featureless element,
2746        //     it must do so while ignoring the default namespace.
2747        //
2748        // https://drafts.csswg.org/selectors-4/#matches
2749        //
2750        //     Default namespace declarations do not affect the compound
2751        //     selector representing the subject of any selector within
2752        //     a :is() pseudo-class, unless that compound selector
2753        //     contains an explicit universal selector or type selector.
2754        //
2755        //     (Similar quotes for :where() / :not())
2756        //
2757        let ignore_default_ns = state.intersects(SelectorParsingState::SKIP_DEFAULT_NAMESPACE)
2758          || matches!(result, SimpleSelectorParseResult::SimpleSelector(Component::Host(..)));
2759        if !ignore_default_ns {
2760          builder.push_simple_selector(Component::DefaultNamespace(url));
2761        }
2762      }
2763    }
2764
2765    empty = false;
2766
2767    match result {
2768      SimpleSelectorParseResult::SimpleSelector(s) => {
2769        builder.push_simple_selector(s);
2770      }
2771      SimpleSelectorParseResult::PartPseudo(part_names) => {
2772        state.insert(SelectorParsingState::AFTER_PART);
2773        builder.push_combinator(Combinator::Part);
2774        builder.push_simple_selector(Component::Part(part_names));
2775      }
2776      SimpleSelectorParseResult::SlottedPseudo(selector) => {
2777        state.insert(SelectorParsingState::AFTER_SLOTTED);
2778        builder.push_combinator(Combinator::SlotAssignment);
2779        builder.push_simple_selector(Component::Slotted(selector));
2780      }
2781      SimpleSelectorParseResult::PseudoElement(p) => {
2782        if !p.is_unknown() {
2783          state.insert(SelectorParsingState::AFTER_PSEUDO_ELEMENT);
2784          builder.push_combinator(Combinator::PseudoElement);
2785        } else {
2786          state.insert(SelectorParsingState::AFTER_UNKNOWN_PSEUDO_ELEMENT);
2787        }
2788        if !p.accepts_state_pseudo_classes() {
2789          state.insert(SelectorParsingState::AFTER_NON_STATEFUL_PSEUDO_ELEMENT);
2790        }
2791        if p.is_webkit_scrollbar() {
2792          state.insert(SelectorParsingState::AFTER_WEBKIT_SCROLLBAR);
2793        }
2794        if p.is_view_transition() {
2795          state.insert(SelectorParsingState::AFTER_VIEW_TRANSITION);
2796        }
2797        builder.push_simple_selector(Component::PseudoElement(p));
2798      }
2799    }
2800  }
2801  Ok(empty)
2802}
2803
2804fn parse_is_or_where<'i, 't, P, Impl>(
2805  parser: &P,
2806  input: &mut CssParser<'i, 't>,
2807  state: &mut SelectorParsingState,
2808  component: impl FnOnce(Box<[Selector<'i, Impl>]>) -> Component<'i, Impl>,
2809) -> Result<Component<'i, Impl>, ParseError<'i, P::Error>>
2810where
2811  P: Parser<'i, Impl = Impl>,
2812  Impl: SelectorImpl<'i>,
2813{
2814  debug_assert!(parser.parse_is_and_where());
2815  // https://drafts.csswg.org/selectors/#matches-pseudo:
2816  //
2817  //     Pseudo-elements cannot be represented by the matches-any
2818  //     pseudo-class; they are not valid within :is().
2819  //
2820  let mut child_state =
2821    *state | SelectorParsingState::SKIP_DEFAULT_NAMESPACE | SelectorParsingState::DISALLOW_PSEUDOS;
2822  let inner = SelectorList::parse_with_state(
2823    parser,
2824    input,
2825    &mut child_state,
2826    parser.is_and_where_error_recovery(),
2827    NestingRequirement::None,
2828  )?;
2829  if child_state.contains(SelectorParsingState::AFTER_NESTING) {
2830    state.insert(SelectorParsingState::AFTER_NESTING)
2831  }
2832  Ok(component(inner.0.into_vec().into_boxed_slice()))
2833}
2834
2835fn parse_has<'i, 't, P, Impl>(
2836  parser: &P,
2837  input: &mut CssParser<'i, 't>,
2838  state: &mut SelectorParsingState,
2839) -> Result<Component<'i, Impl>, ParseError<'i, P::Error>>
2840where
2841  P: Parser<'i, Impl = Impl>,
2842  Impl: SelectorImpl<'i>,
2843{
2844  let mut child_state = *state;
2845  let inner = SelectorList::parse_relative_with_state(
2846    parser,
2847    input,
2848    &mut child_state,
2849    parser.is_and_where_error_recovery(),
2850    NestingRequirement::None,
2851  )?;
2852  if child_state.contains(SelectorParsingState::AFTER_NESTING) {
2853    state.insert(SelectorParsingState::AFTER_NESTING)
2854  }
2855  Ok(Component::Has(inner.0.into_vec().into_boxed_slice()))
2856}
2857
2858fn parse_functional_pseudo_class<'i, 't, P, Impl>(
2859  parser: &P,
2860  input: &mut CssParser<'i, 't>,
2861  name: CowRcStr<'i>,
2862  state: &mut SelectorParsingState,
2863) -> Result<Component<'i, Impl>, ParseError<'i, P::Error>>
2864where
2865  P: Parser<'i, Impl = Impl>,
2866  Impl: SelectorImpl<'i>,
2867{
2868  match_ignore_ascii_case! { &name,
2869      "nth-child" => return parse_nth_pseudo_class(parser, input, *state, NthType::Child),
2870      "nth-of-type" => return parse_nth_pseudo_class(parser, input, *state, NthType::OfType),
2871      "nth-last-child" => return parse_nth_pseudo_class(parser, input, *state, NthType::LastChild),
2872      "nth-last-of-type" => return parse_nth_pseudo_class(parser, input, *state, NthType::LastOfType),
2873      "nth-col" => return parse_nth_pseudo_class(parser, input, *state, NthType::Col),
2874      "nth-last-col" => return parse_nth_pseudo_class(parser, input, *state, NthType::LastCol),
2875      "is" if parser.parse_is_and_where() => return parse_is_or_where(parser, input, state, Component::Is),
2876      "where" if parser.parse_is_and_where() => return parse_is_or_where(parser, input, state, Component::Where),
2877      "has" => return parse_has(parser, input, state),
2878      "host" => {
2879          if !state.allows_tree_structural_pseudo_classes() {
2880              return Err(input.new_custom_error(SelectorParseErrorKind::InvalidState));
2881          }
2882          return Ok(Component::Host(Some(parse_inner_compound_selector(parser, input, state)?)));
2883      },
2884      "not" => {
2885          return parse_negation(parser, input, state)
2886      },
2887      _ => {}
2888  }
2889
2890  if let Some(prefix) = parser.parse_any_prefix(&name) {
2891    return parse_is_or_where(parser, input, state, |selectors| Component::Any(prefix, selectors));
2892  }
2893
2894  if !state.allows_custom_functional_pseudo_classes() {
2895    return Err(input.new_custom_error(SelectorParseErrorKind::InvalidState));
2896  }
2897
2898  P::parse_non_ts_functional_pseudo_class(parser, name, input).map(Component::NonTSPseudoClass)
2899}
2900
2901fn parse_nth_pseudo_class<'i, 't, P, Impl>(
2902  parser: &P,
2903  input: &mut CssParser<'i, 't>,
2904  state: SelectorParsingState,
2905  ty: NthType,
2906) -> Result<Component<'i, Impl>, ParseError<'i, P::Error>>
2907where
2908  P: Parser<'i, Impl = Impl>,
2909  Impl: SelectorImpl<'i>,
2910{
2911  if !state.allows_tree_structural_pseudo_classes() {
2912    return Err(input.new_custom_error(SelectorParseErrorKind::InvalidState));
2913  }
2914  let (a, b) = parse_nth(input)?;
2915  let nth_data = NthSelectorData {
2916    ty,
2917    is_function: true,
2918    a,
2919    b,
2920  };
2921  if !ty.allows_of_selector() {
2922    return Ok(Component::Nth(nth_data));
2923  }
2924
2925  // Try to parse "of <selector-list>".
2926  if input.try_parse(|i| i.expect_ident_matching("of")).is_err() {
2927    return Ok(Component::Nth(nth_data));
2928  }
2929  // Whitespace between "of" and the selector list is optional
2930  // https://github.com/w3c/csswg-drafts/issues/8285
2931  let mut child_state =
2932    state | SelectorParsingState::SKIP_DEFAULT_NAMESPACE | SelectorParsingState::DISALLOW_PSEUDOS;
2933  let selectors = SelectorList::parse_with_state(
2934    parser,
2935    input,
2936    &mut child_state,
2937    ParseErrorRecovery::IgnoreInvalidSelector,
2938    NestingRequirement::None,
2939  )?;
2940  Ok(Component::NthOf(NthOfSelectorData::new(
2941    nth_data,
2942    selectors.0.into_vec().into_boxed_slice(),
2943  )))
2944}
2945
2946/// Returns whether the name corresponds to a CSS2 pseudo-element that
2947/// can be specified with the single colon syntax (in addition to the
2948/// double-colon syntax, which can be used for all pseudo-elements).
2949fn is_css2_pseudo_element(name: &str) -> bool {
2950  // ** Do not add to this list! **
2951  match_ignore_ascii_case! { name,
2952      "before" | "after" | "first-line" | "first-letter" => true,
2953      _ => false,
2954  }
2955}
2956
2957/// Parse a simple selector other than a type selector.
2958///
2959/// * `Err(())`: Invalid selector, abort
2960/// * `Ok(None)`: Not a simple selector, could be something else. `input` was not consumed.
2961/// * `Ok(Some(_))`: Parsed a simple selector or pseudo-element
2962fn parse_one_simple_selector<'i, 't, P, Impl>(
2963  parser: &P,
2964  input: &mut CssParser<'i, 't>,
2965  state: &mut SelectorParsingState,
2966) -> Result<Option<SimpleSelectorParseResult<'i, Impl>>, ParseError<'i, P::Error>>
2967where
2968  P: Parser<'i, Impl = Impl>,
2969  Impl: SelectorImpl<'i>,
2970{
2971  let start = input.state();
2972  let token_location = input.current_source_location();
2973  let token = match input.next_including_whitespace().cloned() {
2974    Ok(t) => t,
2975    Err(..) => {
2976      input.reset(&start);
2977      return Ok(None);
2978    }
2979  };
2980
2981  Ok(Some(match token {
2982    Token::IDHash(id) => {
2983      if state.intersects(SelectorParsingState::AFTER_PSEUDO) {
2984        return Err(token_location.new_custom_error(
2985          SelectorParseErrorKind::UnexpectedSelectorAfterPseudoElement(Token::IDHash(id)),
2986        ));
2987      }
2988      let id = Component::ID(id.into());
2989      SimpleSelectorParseResult::SimpleSelector(id)
2990    }
2991    Token::Delim('.') => {
2992      if state.intersects(SelectorParsingState::AFTER_PSEUDO) {
2993        return Err(token_location.new_custom_error(
2994          SelectorParseErrorKind::UnexpectedSelectorAfterPseudoElement(Token::Delim('.')),
2995        ));
2996      }
2997      let location = input.current_source_location();
2998      let class = match *input.next_including_whitespace()? {
2999        Token::Ident(ref class) => class.clone(),
3000        ref t => {
3001          let e = SelectorParseErrorKind::ClassNeedsIdent(t.clone());
3002          return Err(location.new_custom_error(e));
3003        }
3004      };
3005      let class = Component::Class(class.into());
3006      SimpleSelectorParseResult::SimpleSelector(class)
3007    }
3008    Token::SquareBracketBlock => {
3009      if state.intersects(SelectorParsingState::AFTER_PSEUDO) {
3010        return Err(token_location.new_custom_error(
3011          SelectorParseErrorKind::UnexpectedSelectorAfterPseudoElement(Token::SquareBracketBlock),
3012        ));
3013      }
3014      let attr = input.parse_nested_block(|input| parse_attribute_selector(parser, input))?;
3015      SimpleSelectorParseResult::SimpleSelector(attr)
3016    }
3017    Token::Colon => {
3018      let location = input.current_source_location();
3019      let (is_single_colon, next_token) = match input.next_including_whitespace()?.clone() {
3020        Token::Colon => (false, input.next_including_whitespace()?.clone()),
3021        t => (true, t),
3022      };
3023      let (name, is_functional) = match next_token {
3024        Token::Ident(name) => (name, false),
3025        Token::Function(name) => (name, true),
3026        t => {
3027          let e = SelectorParseErrorKind::PseudoElementExpectedIdent(t);
3028          return Err(input.new_custom_error(e));
3029        }
3030      };
3031      let is_pseudo_element = !is_single_colon || is_css2_pseudo_element(&name);
3032      if is_pseudo_element {
3033        if !state.allows_pseudos() {
3034          return Err(input.new_custom_error(SelectorParseErrorKind::InvalidState));
3035        }
3036        let pseudo_element = if is_functional {
3037          if P::parse_part(parser) && name.eq_ignore_ascii_case("part") {
3038            if !state.allows_part() {
3039              return Err(input.new_custom_error(SelectorParseErrorKind::InvalidState));
3040            }
3041            let names = input.parse_nested_block(|input| {
3042              let mut result = Vec::with_capacity(1);
3043              result.push(input.expect_ident_cloned()?.into());
3044              while !input.is_exhausted() {
3045                result.push(input.expect_ident_cloned()?.into());
3046              }
3047              Ok(result.into_boxed_slice())
3048            })?;
3049            return Ok(Some(SimpleSelectorParseResult::PartPseudo(names)));
3050          }
3051          if P::parse_slotted(parser) && name.eq_ignore_ascii_case("slotted") {
3052            if !state.allows_slotted() {
3053              return Err(input.new_custom_error(SelectorParseErrorKind::InvalidState));
3054            }
3055            let selector =
3056              input.parse_nested_block(|input| parse_inner_compound_selector(parser, input, state))?;
3057            return Ok(Some(SimpleSelectorParseResult::SlottedPseudo(selector)));
3058          }
3059          input.parse_nested_block(|input| P::parse_functional_pseudo_element(parser, name, input))?
3060        } else {
3061          P::parse_pseudo_element(parser, location, name)?
3062        };
3063
3064        if state.intersects(SelectorParsingState::AFTER_SLOTTED) && !pseudo_element.valid_after_slotted() {
3065          return Err(input.new_custom_error(SelectorParseErrorKind::InvalidState));
3066        }
3067        SimpleSelectorParseResult::PseudoElement(pseudo_element)
3068      } else {
3069        let pseudo_class = if is_functional {
3070          input.parse_nested_block(|input| parse_functional_pseudo_class(parser, input, name, state))?
3071        } else {
3072          parse_simple_pseudo_class(parser, location, name, *state)?
3073        };
3074        SimpleSelectorParseResult::SimpleSelector(pseudo_class)
3075      }
3076    }
3077    Token::Delim('&') if parser.is_nesting_allowed() => {
3078      *state |= SelectorParsingState::AFTER_NESTING;
3079      SimpleSelectorParseResult::SimpleSelector(Component::Nesting)
3080    }
3081    _ => {
3082      input.reset(&start);
3083      return Ok(None);
3084    }
3085  }))
3086}
3087
3088fn parse_simple_pseudo_class<'i, P, Impl>(
3089  parser: &P,
3090  location: SourceLocation,
3091  name: CowRcStr<'i>,
3092  state: SelectorParsingState,
3093) -> Result<Component<'i, Impl>, ParseError<'i, P::Error>>
3094where
3095  P: Parser<'i, Impl = Impl>,
3096  Impl: SelectorImpl<'i>,
3097{
3098  if !state.allows_non_functional_pseudo_classes() {
3099    return Err(location.new_custom_error(SelectorParseErrorKind::InvalidState));
3100  }
3101
3102  if state.allows_tree_structural_pseudo_classes() {
3103    match_ignore_ascii_case! { &name,
3104        "first-child" => return Ok(Component::Nth(NthSelectorData::first(/* of_type = */ false))),
3105        "last-child" => return Ok(Component::Nth(NthSelectorData::last(/* of_type = */ false))),
3106        "only-child" => return Ok(Component::Nth(NthSelectorData::only(/* of_type = */ false))),
3107        "root" => return Ok(Component::Root),
3108        "empty" => return Ok(Component::Empty),
3109        "scope" => return Ok(Component::Scope),
3110        "host" if P::parse_host(parser) => return Ok(Component::Host(None)),
3111        "first-of-type" => return Ok(Component::Nth(NthSelectorData::first(/* of_type = */ true))),
3112        "last-of-type" => return Ok(Component::Nth(NthSelectorData::last(/* of_type = */ true))),
3113        "only-of-type" => return Ok(Component::Nth(NthSelectorData::only(/* of_type = */ true))),
3114        _ => {},
3115    }
3116  }
3117
3118  // The view-transition pseudo elements accept the :only-child pseudo class.
3119  // https://w3c.github.io/csswg-drafts/css-view-transitions-1/#pseudo-root
3120  if state.intersects(SelectorParsingState::AFTER_VIEW_TRANSITION) {
3121    match_ignore_ascii_case! { &name,
3122        "only-child" => return Ok(Component::Nth(NthSelectorData::only(/* of_type = */ false))),
3123        _ => {}
3124    }
3125  }
3126
3127  let pseudo_class = P::parse_non_ts_pseudo_class(parser, location, name)?;
3128  if state.intersects(SelectorParsingState::AFTER_WEBKIT_SCROLLBAR) {
3129    if !pseudo_class.is_valid_after_webkit_scrollbar() {
3130      return Err(location.new_custom_error(SelectorParseErrorKind::InvalidPseudoClassAfterWebKitScrollbar));
3131    }
3132  } else if state.intersects(SelectorParsingState::AFTER_PSEUDO_ELEMENT) {
3133    if !pseudo_class.is_user_action_state() {
3134      return Err(location.new_custom_error(SelectorParseErrorKind::InvalidPseudoClassAfterPseudoElement));
3135    }
3136  } else if !pseudo_class.is_valid_before_webkit_scrollbar() {
3137    return Err(location.new_custom_error(SelectorParseErrorKind::InvalidPseudoClassBeforeWebKitScrollbar));
3138  }
3139  Ok(Component::NonTSPseudoClass(pseudo_class))
3140}
3141
3142// NB: pub module in order to access the DummyParser
3143#[cfg(test)]
3144pub mod tests {
3145  use super::*;
3146  use crate::builder::SelectorFlags;
3147  use crate::parser;
3148  use cssparser::{serialize_identifier, serialize_string, Parser as CssParser, ParserInput, ToCss};
3149  use std::collections::HashMap;
3150  use std::fmt;
3151
3152  #[derive(Clone, Debug, Eq, PartialEq, Hash)]
3153  pub enum PseudoClass {
3154    Hover,
3155    Active,
3156    Current,
3157    Lang(String),
3158  }
3159
3160  #[derive(Clone, Debug, Eq, PartialEq, Hash)]
3161  pub enum PseudoElement {
3162    Before,
3163    After,
3164    Named(String),
3165    Functional(String, String),
3166  }
3167
3168  impl<'i> parser::PseudoElement<'i> for PseudoElement {
3169    type Impl = DummySelectorImpl;
3170
3171    fn accepts_state_pseudo_classes(&self) -> bool {
3172      true
3173    }
3174
3175    fn valid_after_slotted(&self) -> bool {
3176      true
3177    }
3178  }
3179
3180  impl<'i> parser::NonTSPseudoClass<'i> for PseudoClass {
3181    type Impl = DummySelectorImpl;
3182
3183    #[inline]
3184    fn is_active_or_hover(&self) -> bool {
3185      matches!(*self, PseudoClass::Active | PseudoClass::Hover)
3186    }
3187
3188    #[inline]
3189    fn is_user_action_state(&self) -> bool {
3190      self.is_active_or_hover()
3191    }
3192  }
3193
3194  impl ToCss for PseudoClass {
3195    fn to_css<W>(&self, dest: &mut W) -> fmt::Result
3196    where
3197      W: fmt::Write,
3198    {
3199      match *self {
3200        PseudoClass::Hover => dest.write_str(":hover"),
3201        PseudoClass::Active => dest.write_str(":active"),
3202        PseudoClass::Current => dest.write_str(":current"),
3203        PseudoClass::Lang(ref lang) => {
3204          dest.write_str(":lang(")?;
3205          serialize_identifier(lang, dest)?;
3206          dest.write_char(')')
3207        }
3208      }
3209    }
3210  }
3211
3212  impl ToCss for PseudoElement {
3213    fn to_css<W>(&self, dest: &mut W) -> fmt::Result
3214    where
3215      W: fmt::Write,
3216    {
3217      match *self {
3218        PseudoElement::Before => dest.write_str("::before"),
3219        PseudoElement::After => dest.write_str("::after"),
3220        PseudoElement::Named(ref name) => write!(dest, "::{}", name),
3221        PseudoElement::Functional(ref name, ref argument) => {
3222          write!(dest, "::{}(", name)?;
3223          serialize_identifier(argument, dest)?;
3224          dest.write_char(')')
3225        }
3226      }
3227    }
3228  }
3229
3230  #[derive(Clone, Debug, PartialEq)]
3231  pub struct DummySelectorImpl;
3232
3233  #[derive(Default)]
3234  pub struct DummyParser {
3235    default_ns: Option<DummyAtom>,
3236    ns_prefixes: HashMap<DummyAtom, DummyAtom>,
3237  }
3238
3239  impl DummyParser {
3240    fn default_with_namespace(default_ns: DummyAtom) -> DummyParser {
3241      DummyParser {
3242        default_ns: Some(default_ns),
3243        ns_prefixes: Default::default(),
3244      }
3245    }
3246  }
3247
3248  impl<'i> SelectorImpl<'i> for DummySelectorImpl {
3249    type ExtraMatchingData = ();
3250    type AttrValue = DummyAttrValue;
3251    type Identifier = DummyAtom;
3252    type LocalName = DummyAtom;
3253    type NamespaceUrl = DummyAtom;
3254    type NamespacePrefix = DummyAtom;
3255    type BorrowedLocalName = DummyAtom;
3256    type BorrowedNamespaceUrl = DummyAtom;
3257    type NonTSPseudoClass = PseudoClass;
3258    type PseudoElement = PseudoElement;
3259    type VendorPrefix = u8;
3260  }
3261
3262  #[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
3263  pub struct DummyAttrValue(String);
3264
3265  impl ToCss for DummyAttrValue {
3266    fn to_css<W>(&self, dest: &mut W) -> fmt::Result
3267    where
3268      W: fmt::Write,
3269    {
3270      serialize_string(&self.0, dest)
3271    }
3272  }
3273
3274  impl AsRef<str> for DummyAttrValue {
3275    fn as_ref(&self) -> &str {
3276      self.0.as_ref()
3277    }
3278  }
3279
3280  impl<'a> From<&'a str> for DummyAttrValue {
3281    fn from(string: &'a str) -> Self {
3282      Self(string.into())
3283    }
3284  }
3285
3286  impl<'a> From<std::borrow::Cow<'a, str>> for DummyAttrValue {
3287    fn from(string: std::borrow::Cow<'a, str>) -> Self {
3288      Self(string.to_string())
3289    }
3290  }
3291
3292  impl<'a> From<CowRcStr<'a>> for DummyAttrValue {
3293    fn from(string: CowRcStr<'a>) -> Self {
3294      Self(string.to_string())
3295    }
3296  }
3297
3298  #[derive(Clone, Debug, Default, Eq, Hash, PartialEq)]
3299  pub struct DummyAtom(String);
3300
3301  impl ToCss for DummyAtom {
3302    fn to_css<W>(&self, dest: &mut W) -> fmt::Result
3303    where
3304      W: fmt::Write,
3305    {
3306      serialize_identifier(&self.0, dest)
3307    }
3308  }
3309
3310  impl From<String> for DummyAtom {
3311    fn from(string: String) -> Self {
3312      DummyAtom(string)
3313    }
3314  }
3315
3316  impl<'a> From<&'a str> for DummyAtom {
3317    fn from(string: &'a str) -> Self {
3318      DummyAtom(string.into())
3319    }
3320  }
3321
3322  impl<'a> From<CowRcStr<'a>> for DummyAtom {
3323    fn from(string: CowRcStr<'a>) -> Self {
3324      DummyAtom(string.to_string())
3325    }
3326  }
3327
3328  impl AsRef<str> for DummyAtom {
3329    fn as_ref(&self) -> &str {
3330      self.0.as_ref()
3331    }
3332  }
3333
3334  impl<'a> From<std::borrow::Cow<'a, str>> for DummyAtom {
3335    fn from(string: std::borrow::Cow<'a, str>) -> Self {
3336      Self(string.to_string())
3337    }
3338  }
3339
3340  impl<'i> Parser<'i> for DummyParser {
3341    type Impl = DummySelectorImpl;
3342    type Error = SelectorParseErrorKind<'i>;
3343
3344    fn parse_slotted(&self) -> bool {
3345      true
3346    }
3347
3348    fn parse_is_and_where(&self) -> bool {
3349      true
3350    }
3351
3352    fn is_and_where_error_recovery(&self) -> ParseErrorRecovery {
3353      ParseErrorRecovery::DiscardList
3354    }
3355
3356    fn parse_part(&self) -> bool {
3357      true
3358    }
3359
3360    fn parse_non_ts_pseudo_class(
3361      &self,
3362      location: SourceLocation,
3363      name: CowRcStr<'i>,
3364    ) -> Result<PseudoClass, SelectorParseError<'i>> {
3365      match_ignore_ascii_case! { &name,
3366          "hover" => return Ok(PseudoClass::Hover),
3367          "active" => return Ok(PseudoClass::Active),
3368          "current" => return Ok(PseudoClass::Current),
3369          _ => {}
3370      }
3371      Err(location.new_custom_error(SelectorParseErrorKind::UnsupportedPseudoClass(name)))
3372    }
3373
3374    fn parse_non_ts_functional_pseudo_class<'t>(
3375      &self,
3376      name: CowRcStr<'i>,
3377      parser: &mut CssParser<'i, 't>,
3378    ) -> Result<PseudoClass, SelectorParseError<'i>> {
3379      match_ignore_ascii_case! { &name,
3380          "lang" => {
3381              let lang = parser.expect_ident_or_string()?.as_ref().to_owned();
3382              return Ok(PseudoClass::Lang(lang));
3383          },
3384          _ => {}
3385      }
3386      Err(parser.new_custom_error(SelectorParseErrorKind::UnsupportedPseudoClass(name)))
3387    }
3388
3389    fn parse_pseudo_element(
3390      &self,
3391      location: SourceLocation,
3392      name: CowRcStr<'i>,
3393    ) -> Result<PseudoElement, SelectorParseError<'i>> {
3394      match_ignore_ascii_case! { &name,
3395          "before" => return Ok(PseudoElement::Before),
3396          "after" => return Ok(PseudoElement::After),
3397          "details-content" | "target-text" | "search-text" | "picker-icon" |
3398          "checkmark" | "grammar-error" | "spelling-error" => {
3399            return Ok(PseudoElement::Named(name.to_ascii_lowercase()));
3400          },
3401          _ => {}
3402      }
3403      Err(location.new_custom_error(SelectorParseErrorKind::UnsupportedPseudoElement(name)))
3404    }
3405
3406    fn parse_functional_pseudo_element<'t>(
3407      &self,
3408      name: CowRcStr<'i>,
3409      arguments: &mut CssParser<'i, 't>,
3410    ) -> Result<PseudoElement, SelectorParseError<'i>> {
3411      let argument = match_ignore_ascii_case! { &name,
3412        "highlight" => arguments.expect_ident()?.to_string(),
3413        "picker" => {
3414          arguments.expect_ident_matching("select")?;
3415          "select".to_owned()
3416        },
3417        _ => return Err(arguments.new_custom_error(SelectorParseErrorKind::UnsupportedPseudoElement(name))),
3418      };
3419      Ok(PseudoElement::Functional(name.to_ascii_lowercase(), argument))
3420    }
3421
3422    fn default_namespace(&self) -> Option<DummyAtom> {
3423      self.default_ns.clone()
3424    }
3425
3426    fn namespace_for_prefix(&self, prefix: &DummyAtom) -> Option<DummyAtom> {
3427      self.ns_prefixes.get(prefix).cloned()
3428    }
3429  }
3430
3431  fn parse<'i>(input: &'i str) -> Result<SelectorList<'i, DummySelectorImpl>, SelectorParseError<'i>> {
3432    parse_ns(input, &DummyParser::default())
3433  }
3434
3435  // fn parse_expected<'i, 'a>(
3436  //   input: &'i str,
3437  //   expected: Option<&'a str>,
3438  // ) -> Result<SelectorList<'i, DummySelectorImpl>, SelectorParseError<'i>> {
3439  //   parse_ns_expected(input, &DummyParser::default(), expected)
3440  // }
3441
3442  fn parse_ns<'i>(
3443    input: &'i str,
3444    parser: &DummyParser,
3445  ) -> Result<SelectorList<'i, DummySelectorImpl>, SelectorParseError<'i>> {
3446    parse_ns_expected(input, parser, None)
3447  }
3448
3449  fn parse_ns_expected<'i>(
3450    input: &'i str,
3451    parser: &DummyParser,
3452    expected: Option<&str>,
3453  ) -> Result<SelectorList<'i, DummySelectorImpl>, SelectorParseError<'i>> {
3454    let mut parser_input = ParserInput::new(input);
3455    let result = SelectorList::parse(
3456      parser,
3457      &mut CssParser::new(&mut parser_input),
3458      ParseErrorRecovery::DiscardList,
3459      NestingRequirement::None,
3460    );
3461    if let Ok(ref selectors) = result {
3462      assert_eq!(selectors.0.len(), 1);
3463      // We can't assume that the serialized parsed selector will equal
3464      // the input; for example, if there is no default namespace, '*|foo'
3465      // should serialize to 'foo'.
3466      assert_eq!(
3467        selectors.0[0].to_css_string(),
3468        match expected {
3469          Some(x) => x,
3470          None => input,
3471        }
3472      );
3473    }
3474    result
3475  }
3476
3477  fn specificity(a: u32, b: u32, c: u32) -> u32 {
3478    a << 20 | b << 10 | c
3479  }
3480
3481  #[test]
3482  fn test_empty() {
3483    let mut input = ParserInput::new(":empty");
3484    let list = SelectorList::parse(
3485      &DummyParser::default(),
3486      &mut CssParser::new(&mut input),
3487      ParseErrorRecovery::DiscardList,
3488      NestingRequirement::None,
3489    );
3490    assert!(list.is_ok());
3491  }
3492
3493  const MATHML: &str = "http://www.w3.org/1998/Math/MathML";
3494  const SVG: &str = "http://www.w3.org/2000/svg";
3495
3496  #[test]
3497  fn test_parsing() {
3498    assert!(parse("").is_err());
3499    assert!(parse(":lang(4)").is_err());
3500    assert!(parse(":lang(en US)").is_err());
3501    assert_eq!(
3502      parse("EeÉ"),
3503      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3504        vec![Component::LocalName(LocalName {
3505          name: DummyAtom::from("EeÉ"),
3506          lower_name: DummyAtom::from("eeÉ"),
3507        })],
3508        specificity(0, 0, 1),
3509        Default::default(),
3510      )]))
3511    );
3512    assert_eq!(
3513      parse("|e"),
3514      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3515        vec![
3516          Component::ExplicitNoNamespace,
3517          Component::LocalName(LocalName {
3518            name: DummyAtom::from("e"),
3519            lower_name: DummyAtom::from("e"),
3520          }),
3521        ],
3522        specificity(0, 0, 1),
3523        Default::default(),
3524      )]))
3525    );
3526    // When the default namespace is not set, *| should be elided.
3527    // https://github.com/servo/servo/pull/17537
3528    // assert_eq!(
3529    //   parse_expected("*|e", Some("e")),
3530    //   Ok(SelectorList::from_vec(vec![Selector::from_vec(
3531    //     vec![Component::LocalName(LocalName {
3532    //       name: DummyAtom::from("e"),
3533    //       lower_name: DummyAtom::from("e"),
3534    //     })],
3535    //     specificity(0, 0, 1),
3536    //     Default::default(),
3537    //   )]))
3538    // );
3539    // When the default namespace is set, *| should _not_ be elided (as foo
3540    // is no longer equivalent to *|foo--the former is only for foo in the
3541    // default namespace).
3542    // https://github.com/servo/servo/issues/16020
3543    // assert_eq!(
3544    //   parse_ns(
3545    //     "*|e",
3546    //     &DummyParser::default_with_namespace(DummyAtom::from("https://mozilla.org"))
3547    //   ),
3548    //   Ok(SelectorList::from_vec(vec![Selector::from_vec(
3549    //     vec![
3550    //       Component::ExplicitAnyNamespace,
3551    //       Component::LocalName(LocalName {
3552    //         name: DummyAtom::from("e"),
3553    //         lower_name: DummyAtom::from("e"),
3554    //       }),
3555    //     ],
3556    //     specificity(0, 0, 1),
3557    //     Default::default(),
3558    //   )]))
3559    // );
3560    assert_eq!(
3561      parse("*"),
3562      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3563        vec![Component::ExplicitUniversalType],
3564        specificity(0, 0, 0),
3565        Default::default(),
3566      )]))
3567    );
3568    assert_eq!(
3569      parse("|*"),
3570      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3571        vec![Component::ExplicitNoNamespace, Component::ExplicitUniversalType,],
3572        specificity(0, 0, 0),
3573        Default::default(),
3574      )]))
3575    );
3576    // assert_eq!(
3577    //   parse_expected("*|*", Some("*")),
3578    //   Ok(SelectorList::from_vec(vec![Selector::from_vec(
3579    //     vec![Component::ExplicitUniversalType],
3580    //     specificity(0, 0, 0),
3581    //     Default::default(),
3582    //   )]))
3583    // );
3584    assert_eq!(
3585      parse_ns(
3586        "*|*",
3587        &DummyParser::default_with_namespace(DummyAtom::from("https://mozilla.org"))
3588      ),
3589      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3590        vec![Component::ExplicitAnyNamespace, Component::ExplicitUniversalType,],
3591        specificity(0, 0, 0),
3592        Default::default(),
3593      )]))
3594    );
3595    assert_eq!(
3596      parse(".foo:lang(en-US)"),
3597      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3598        vec![
3599          Component::Class(DummyAtom::from("foo")),
3600          Component::NonTSPseudoClass(PseudoClass::Lang("en-US".to_owned())),
3601        ],
3602        specificity(0, 2, 0),
3603        Default::default(),
3604      )]))
3605    );
3606    assert_eq!(
3607      parse("#bar"),
3608      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3609        vec![Component::ID(DummyAtom::from("bar"))],
3610        specificity(1, 0, 0),
3611        Default::default(),
3612      )]))
3613    );
3614    assert_eq!(
3615      parse("e.foo#bar"),
3616      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3617        vec![
3618          Component::LocalName(LocalName {
3619            name: DummyAtom::from("e"),
3620            lower_name: DummyAtom::from("e"),
3621          }),
3622          Component::Class(DummyAtom::from("foo")),
3623          Component::ID(DummyAtom::from("bar")),
3624        ],
3625        specificity(1, 1, 1),
3626        Default::default(),
3627      )]))
3628    );
3629    assert_eq!(
3630      parse("e.foo #bar"),
3631      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3632        vec![
3633          Component::LocalName(LocalName {
3634            name: DummyAtom::from("e"),
3635            lower_name: DummyAtom::from("e"),
3636          }),
3637          Component::Class(DummyAtom::from("foo")),
3638          Component::Combinator(Combinator::Descendant),
3639          Component::ID(DummyAtom::from("bar")),
3640        ],
3641        specificity(1, 1, 1),
3642        Default::default(),
3643      )]))
3644    );
3645    // Default namespace does not apply to attribute selectors
3646    // https://github.com/mozilla/servo/pull/1652
3647    let mut parser = DummyParser::default();
3648    assert_eq!(
3649      parse_ns("[Foo]", &parser),
3650      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3651        vec![Component::AttributeInNoNamespaceExists {
3652          local_name: DummyAtom::from("Foo"),
3653          local_name_lower: DummyAtom::from("foo"),
3654        }],
3655        specificity(0, 1, 0),
3656        Default::default(),
3657      )]))
3658    );
3659    assert!(parse_ns("svg|circle", &parser).is_err());
3660    parser.ns_prefixes.insert(DummyAtom("svg".into()), DummyAtom(SVG.into()));
3661    assert_eq!(
3662      parse_ns("svg|circle", &parser),
3663      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3664        vec![
3665          Component::Namespace(DummyAtom("svg".into()), SVG.into()),
3666          Component::LocalName(LocalName {
3667            name: DummyAtom::from("circle"),
3668            lower_name: DummyAtom::from("circle"),
3669          }),
3670        ],
3671        specificity(0, 0, 1),
3672        Default::default(),
3673      )]))
3674    );
3675    assert_eq!(
3676      parse_ns("svg|*", &parser),
3677      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3678        vec![
3679          Component::Namespace(DummyAtom("svg".into()), SVG.into()),
3680          Component::ExplicitUniversalType,
3681        ],
3682        specificity(0, 0, 0),
3683        Default::default(),
3684      )]))
3685    );
3686    // Default namespace does not apply to attribute selectors
3687    // https://github.com/mozilla/servo/pull/1652
3688    // but it does apply to implicit type selectors
3689    // https://github.com/servo/rust-selectors/pull/82
3690    parser.default_ns = Some(MATHML.into());
3691    assert_eq!(
3692      parse_ns("[Foo]", &parser),
3693      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3694        vec![
3695          Component::DefaultNamespace(MATHML.into()),
3696          Component::AttributeInNoNamespaceExists {
3697            local_name: DummyAtom::from("Foo"),
3698            local_name_lower: DummyAtom::from("foo"),
3699          },
3700        ],
3701        specificity(0, 1, 0),
3702        Default::default(),
3703      )]))
3704    );
3705    // Default namespace does apply to type selectors
3706    assert_eq!(
3707      parse_ns("e", &parser),
3708      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3709        vec![
3710          Component::DefaultNamespace(MATHML.into()),
3711          Component::LocalName(LocalName {
3712            name: DummyAtom::from("e"),
3713            lower_name: DummyAtom::from("e"),
3714          }),
3715        ],
3716        specificity(0, 0, 1),
3717        Default::default(),
3718      )]))
3719    );
3720    assert_eq!(
3721      parse_ns("*", &parser),
3722      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3723        vec![
3724          Component::DefaultNamespace(MATHML.into()),
3725          Component::ExplicitUniversalType,
3726        ],
3727        specificity(0, 0, 0),
3728        Default::default(),
3729      )]))
3730    );
3731    assert_eq!(
3732      parse_ns("*|*", &parser),
3733      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3734        vec![Component::ExplicitAnyNamespace, Component::ExplicitUniversalType,],
3735        specificity(0, 0, 0),
3736        Default::default(),
3737      )]))
3738    );
3739    // Default namespace applies to universal and type selectors inside :not and :matches,
3740    // but not otherwise.
3741    assert_eq!(
3742      parse_ns(":not(.cl)", &parser),
3743      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3744        vec![
3745          Component::DefaultNamespace(MATHML.into()),
3746          Component::Negation(
3747            vec![Selector::from_vec(
3748              vec![Component::Class(DummyAtom::from("cl"))],
3749              specificity(0, 1, 0),
3750              Default::default(),
3751            )]
3752            .into_boxed_slice()
3753          ),
3754        ],
3755        specificity(0, 1, 0),
3756        Default::default(),
3757      )]))
3758    );
3759    assert_eq!(
3760      parse_ns(":not(*)", &parser),
3761      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3762        vec![
3763          Component::DefaultNamespace(MATHML.into()),
3764          Component::Negation(
3765            vec![Selector::from_vec(
3766              vec![
3767                Component::DefaultNamespace(MATHML.into()),
3768                Component::ExplicitUniversalType,
3769              ],
3770              specificity(0, 0, 0),
3771              Default::default(),
3772            )]
3773            .into_boxed_slice(),
3774          ),
3775        ],
3776        specificity(0, 0, 0),
3777        Default::default(),
3778      )]))
3779    );
3780    assert_eq!(
3781      parse_ns(":not(e)", &parser),
3782      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3783        vec![
3784          Component::DefaultNamespace(MATHML.into()),
3785          Component::Negation(
3786            vec![Selector::from_vec(
3787              vec![
3788                Component::DefaultNamespace(MATHML.into()),
3789                Component::LocalName(LocalName {
3790                  name: DummyAtom::from("e"),
3791                  lower_name: DummyAtom::from("e"),
3792                }),
3793              ],
3794              specificity(0, 0, 1),
3795              Default::default(),
3796            ),]
3797            .into_boxed_slice()
3798          ),
3799        ],
3800        specificity(0, 0, 1),
3801        Default::default(),
3802      )]))
3803    );
3804    assert_eq!(
3805      parse("[attr|=\"foo\"]"),
3806      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3807        vec![Component::AttributeInNoNamespace {
3808          local_name: DummyAtom::from("attr"),
3809          operator: AttrSelectorOperator::DashMatch,
3810          value: DummyAttrValue::from("foo"),
3811          never_matches: false,
3812          case_sensitivity: ParsedCaseSensitivity::CaseSensitive,
3813        }],
3814        specificity(0, 1, 0),
3815        Default::default(),
3816      )]))
3817    );
3818    // https://github.com/mozilla/servo/issues/1723
3819    assert_eq!(
3820      parse("::before"),
3821      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3822        vec![
3823          Component::Combinator(Combinator::PseudoElement),
3824          Component::PseudoElement(PseudoElement::Before),
3825        ],
3826        specificity(0, 0, 1),
3827        SelectorFlags::HAS_PSEUDO,
3828      )]))
3829    );
3830    assert_eq!(
3831      parse("::before:hover"),
3832      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3833        vec![
3834          Component::Combinator(Combinator::PseudoElement),
3835          Component::PseudoElement(PseudoElement::Before),
3836          Component::NonTSPseudoClass(PseudoClass::Hover),
3837        ],
3838        specificity(0, 1, 1),
3839        SelectorFlags::HAS_PSEUDO,
3840      )]))
3841    );
3842    assert_eq!(
3843      parse("::before:hover:hover"),
3844      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3845        vec![
3846          Component::Combinator(Combinator::PseudoElement),
3847          Component::PseudoElement(PseudoElement::Before),
3848          Component::NonTSPseudoClass(PseudoClass::Hover),
3849          Component::NonTSPseudoClass(PseudoClass::Hover),
3850        ],
3851        specificity(0, 2, 1),
3852        SelectorFlags::HAS_PSEUDO,
3853      )]))
3854    );
3855    assert!(parse("::before:hover:lang(foo)").is_err());
3856    assert!(parse("::before:hover .foo").is_err());
3857    assert!(parse("::before .foo").is_err());
3858    assert!(parse("::before ~ bar").is_err());
3859    assert!(parse("::before:active").is_ok());
3860
3861    // https://github.com/servo/servo/issues/15335
3862    assert!(parse(":: before").is_err());
3863    assert_eq!(
3864      parse("div ::after"),
3865      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3866        vec![
3867          Component::LocalName(LocalName {
3868            name: DummyAtom::from("div"),
3869            lower_name: DummyAtom::from("div"),
3870          }),
3871          Component::Combinator(Combinator::Descendant),
3872          Component::Combinator(Combinator::PseudoElement),
3873          Component::PseudoElement(PseudoElement::After),
3874        ],
3875        specificity(0, 0, 2),
3876        SelectorFlags::HAS_PSEUDO,
3877      )]))
3878    );
3879    assert_eq!(
3880      parse("#d1 > .ok"),
3881      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3882        vec![
3883          Component::ID(DummyAtom::from("d1")),
3884          Component::Combinator(Combinator::Child),
3885          Component::Class(DummyAtom::from("ok")),
3886        ],
3887        (1 << 20) + (1 << 10),
3888        Default::default(),
3889      )]))
3890    );
3891    parser.default_ns = None;
3892    assert!(parse(":not(#provel.old)").is_ok());
3893    assert!(parse(":not(#provel > old)").is_ok());
3894    assert!(parse("table[rules]:not([rules=\"none\"]):not([rules=\"\"])").is_ok());
3895    // https://github.com/servo/servo/issues/16017
3896    assert_eq!(
3897      parse_ns(":not(*)", &parser),
3898      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3899        vec![Component::Negation(
3900          vec![Selector::from_vec(
3901            vec![Component::ExplicitUniversalType],
3902            specificity(0, 0, 0),
3903            Default::default(),
3904          )]
3905          .into_boxed_slice()
3906        )],
3907        specificity(0, 0, 0),
3908        Default::default(),
3909      )]))
3910    );
3911    assert_eq!(
3912      parse_ns(":not(|*)", &parser),
3913      Ok(SelectorList::from_vec(vec![Selector::from_vec(
3914        vec![Component::Negation(
3915          vec![Selector::from_vec(
3916            vec![Component::ExplicitNoNamespace, Component::ExplicitUniversalType,],
3917            specificity(0, 0, 0),
3918            Default::default(),
3919          )]
3920          .into_boxed_slice(),
3921        )],
3922        specificity(0, 0, 0),
3923        Default::default(),
3924      )]))
3925    );
3926    // *| should be elided if there is no default namespace.
3927    // https://github.com/servo/servo/pull/17537
3928    // assert_eq!(
3929    //   parse_ns_expected(":not(*|*)", &parser, Some(":not(*)")),
3930    //   Ok(SelectorList::from_vec(vec![Selector::from_vec(
3931    //     vec![Component::Negation(
3932    //       vec![Selector::from_vec(
3933    //         vec![Component::ExplicitUniversalType],
3934    //         specificity(0, 0, 0),
3935    //         Default::default()
3936    //       )]
3937    //       .into_boxed_slice()
3938    //     )],
3939    //     specificity(0, 0, 0),
3940    //     Default::default(),
3941    //   )]))
3942    // );
3943
3944    assert!(parse("::slotted()").is_err());
3945    assert!(parse("::slotted(div)").is_ok());
3946    assert!(parse("::slotted(div).foo").is_err());
3947    assert!(parse("::slotted(div + bar)").is_err());
3948    assert!(parse("::slotted(div) + foo").is_err());
3949
3950    assert!(parse("::part()").is_err());
3951    assert!(parse("::part(42)").is_err());
3952    assert!(parse("::part(foo bar)").is_ok());
3953    assert!(parse("::part(foo):hover").is_ok());
3954    assert!(parse("::part(foo) + bar").is_err());
3955
3956    assert!(parse("div ::slotted(div)").is_ok());
3957    assert!(parse("div + slot::slotted(div)").is_ok());
3958    assert!(parse("div + slot::slotted(div.foo)").is_ok());
3959    assert!(parse("slot::slotted(div,foo)::first-line").is_err());
3960    assert!(parse("::slotted(div)::before").is_ok());
3961    assert!(parse("slot::slotted(div,foo)").is_err());
3962
3963    assert!(parse("foo:where()").is_err());
3964    assert!(parse("foo:where(div, foo, .bar baz)").is_ok());
3965    assert!(parse("foo:where(::before)").is_err());
3966
3967    assert!(parse("foo::details-content").is_ok());
3968    assert!(parse("foo::target-text").is_ok());
3969    assert!(parse("foo::search-text").is_ok());
3970    assert!(parse(":current::search-text").is_ok());
3971
3972    assert!(parse("::highlight").is_err());
3973    assert!(parse("::highlight()").is_err());
3974    assert!(parse("::highlight(custom-highlight-name)").is_ok());
3975
3976    assert!(parse("select::picker").is_err());
3977    assert!(parse("::picker()").is_err());
3978    assert!(parse("::picker(select)").is_ok());
3979    assert!(parse("select::picker-icon").is_ok());
3980    assert!(parse("option::checkmark").is_ok());
3981
3982    assert!(parse("::grammar-error").is_ok());
3983    assert!(parse("::spelling-error").is_ok());
3984    assert!(parse("::part(mypart)::grammar-error").is_ok());
3985    assert!(parse("::part(mypart)::spelling-error").is_ok());
3986  }
3987
3988  #[test]
3989  fn test_pseudo_iter() {
3990    let selector = &parse("q::before").unwrap().0[0];
3991    assert!(!selector.is_universal());
3992    let mut iter = selector.iter();
3993    assert_eq!(iter.next(), Some(&Component::PseudoElement(PseudoElement::Before)));
3994    assert_eq!(iter.next(), None);
3995    let combinator = iter.next_sequence();
3996    assert_eq!(combinator, Some(Combinator::PseudoElement));
3997    assert!(matches!(iter.next(), Some(&Component::LocalName(..))));
3998    assert_eq!(iter.next(), None);
3999    assert_eq!(iter.next_sequence(), None);
4000  }
4001
4002  #[test]
4003  fn test_universal() {
4004    let selector = &parse_ns(
4005      "*|*::before",
4006      &DummyParser::default_with_namespace(DummyAtom::from("https://mozilla.org")),
4007    )
4008    .unwrap()
4009    .0[0];
4010    assert!(selector.is_universal());
4011  }
4012
4013  #[test]
4014  fn test_empty_pseudo_iter() {
4015    let selector = &parse("::before").unwrap().0[0];
4016    assert!(selector.is_universal());
4017    let mut iter = selector.iter();
4018    assert_eq!(iter.next(), Some(&Component::PseudoElement(PseudoElement::Before)));
4019    assert_eq!(iter.next(), None);
4020    assert_eq!(iter.next_sequence(), Some(Combinator::PseudoElement));
4021    assert_eq!(iter.next(), None);
4022    assert_eq!(iter.next_sequence(), None);
4023  }
4024
4025  struct TestVisitor {
4026    seen: Vec<String>,
4027  }
4028
4029  impl<'i> SelectorVisitor<'i> for TestVisitor {
4030    type Impl = DummySelectorImpl;
4031
4032    fn visit_simple_selector(&mut self, s: &Component<DummySelectorImpl>) -> bool {
4033      let mut dest = String::new();
4034      s.to_css(&mut dest).unwrap();
4035      self.seen.push(dest);
4036      true
4037    }
4038  }
4039
4040  #[test]
4041  fn visitor() {
4042    let mut test_visitor = TestVisitor { seen: vec![] };
4043    parse(":not(:hover) ~ label").unwrap().0[0].visit(&mut test_visitor);
4044    assert!(test_visitor.seen.contains(&":hover".into()));
4045
4046    let mut test_visitor = TestVisitor { seen: vec![] };
4047    parse("::before:hover").unwrap().0[0].visit(&mut test_visitor);
4048    assert!(test_visitor.seen.contains(&":hover".into()));
4049  }
4050}