Skip to main content

rspack_lightningcss/
selector.rs

1//! CSS selectors.
2
3use crate::compat::Feature;
4use crate::error::{ParserError, PrinterError, SelectorError};
5use crate::parser::ParserFlags;
6use crate::printer::{ContextAccess, Printer};
7use crate::properties::custom::TokenList;
8use crate::rules::StyleContext;
9use crate::stylesheet::{ParserOptions, PrinterOptions};
10use crate::targets::{should_compile, Targets};
11use crate::traits::{Parse, ParseWithOptions, ToCss};
12use crate::values::ident::{CustomIdent, Ident};
13use crate::values::string::CSSString;
14use crate::vendor_prefix::VendorPrefix;
15#[cfg(feature = "visitor")]
16use crate::visitor::{Visit, VisitTypes, Visitor};
17use crate::{macros::enum_property, values::string::CowArcStr};
18use cssparser::*;
19use rspack_lightningcss_selectors::parser::{NthType, SelectorParseErrorKind};
20use rspack_lightningcss_selectors::{
21  attr::{AttrSelectorOperator, ParsedAttrSelectorOperation, ParsedCaseSensitivity},
22  parser::SelectorImpl,
23};
24use smallvec::SmallVec;
25use std::collections::HashSet;
26use std::fmt;
27
28#[cfg(feature = "serde")]
29use crate::serialization::*;
30
31mod private {
32  #[derive(Debug, Clone, PartialEq, Eq, Hash)]
33  #[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
34  pub struct Selectors;
35
36  #[cfg(feature = "into_owned")]
37  impl<'any> ::rspack_lightningcss_static_self::IntoOwned<'any> for Selectors {
38    type Owned = Self;
39
40    fn into_owned(self) -> Self::Owned {
41      self
42    }
43  }
44}
45
46#[cfg(feature = "into_owned")]
47fn _assert_into_owned() {
48  // Ensure that we provide into_owned
49
50  use rspack_lightningcss_static_self::IntoOwned;
51  fn _assert<'any, T: IntoOwned<'any>>() {}
52
53  _assert::<SelectorList>();
54}
55
56use private::Selectors;
57
58/// A list of selectors.
59pub type SelectorList<'i> = rspack_lightningcss_selectors::SelectorList<'i, Selectors>;
60/// A CSS selector, including a list of components.
61pub type Selector<'i> = rspack_lightningcss_selectors::parser::Selector<'i, Selectors>;
62/// An individual component within a selector.
63pub type Component<'i> = rspack_lightningcss_selectors::parser::Component<'i, Selectors>;
64
65/// Whether a selector contains nesting, including inside a functional pseudo class.
66pub(crate) fn has_nesting(selector: &Selector) -> bool {
67  struct WithoutNesting;
68  impl<'i> rspack_lightningcss_selectors::visitor::SelectorVisitor<'i> for WithoutNesting {
69    type Impl = Selectors;
70
71    fn visit_simple_selector(&mut self, component: &Component<'i>) -> bool {
72      match component {
73        Component::Nesting => false,
74        // SelectorVisitor does not descend into these arguments by default.
75        Component::Has(selectors) | Component::Any(_, selectors) => selectors.iter().all(|s| s.visit(self)),
76        Component::PseudoElement(
77          PseudoElement::CueFunction { selector } | PseudoElement::CueRegionFunction { selector },
78        ) => Selector::visit(selector, self),
79        _ => true,
80      }
81    }
82  }
83
84  !selector.visit(&mut WithoutNesting)
85}
86
87/// A combinator.
88pub use rspack_lightningcss_selectors::parser::Combinator;
89
90impl<'i> SelectorImpl<'i> for Selectors {
91  type AttrValue = CSSString<'i>;
92  type Identifier = Ident<'i>;
93  type LocalName = Ident<'i>;
94  type NamespacePrefix = Ident<'i>;
95  type NamespaceUrl = CowArcStr<'i>;
96  type BorrowedNamespaceUrl = CowArcStr<'i>;
97  type BorrowedLocalName = Ident<'i>;
98
99  type NonTSPseudoClass = PseudoClass<'i>;
100  type PseudoElement = PseudoElement<'i>;
101  type VendorPrefix = VendorPrefix;
102
103  type ExtraMatchingData = ();
104
105  fn to_css<W: fmt::Write>(selectors: &SelectorList<'i>, dest: &mut W) -> std::fmt::Result {
106    let mut printer = Printer::new(dest, PrinterOptions::default());
107    serialize_selector_list(selectors.0.iter(), &mut printer, None, false).map_err(|_| std::fmt::Error)
108  }
109}
110
111pub(crate) struct SelectorParser<'a, 'i> {
112  pub is_nesting_allowed: bool,
113  pub options: &'a ParserOptions<'i>,
114}
115
116impl<'a, 'i> rspack_lightningcss_selectors::parser::Parser<'i> for SelectorParser<'a, 'i> {
117  type Impl = Selectors;
118  type Error = ParserError<'i>;
119
120  fn parse_non_ts_pseudo_class(
121    &self,
122    loc: SourceLocation,
123    name: CowRcStr<'i>,
124  ) -> Result<PseudoClass<'i>, ParseError<'i, Self::Error>> {
125    use PseudoClass::*;
126    let scroll_navigation_controls = self.options.flags.contains(ParserFlags::SCROLL_NAVIGATION_CONTROLS);
127    let pseudo_class = match_ignore_ascii_case! { &name,
128      // https://drafts.csswg.org/selectors-4/#useraction-pseudos
129      "hover" => Hover,
130      "active" => Active,
131      "focus" => Focus,
132      "focus-visible" => FocusVisible,
133      "focus-within" => FocusWithin,
134
135      // https://drafts.csswg.org/selectors-4/#time-pseudos
136      "current" => Current,
137      "past" => Past,
138      "future" => Future,
139
140      // https://drafts.csswg.org/selectors-4/#resource-pseudos
141      "playing" => Playing,
142      "paused" => Paused,
143      "seeking" => Seeking,
144      "buffering" => Buffering,
145      "stalled" => Stalled,
146      "muted" => Muted,
147      "volume-locked" => VolumeLocked,
148
149      // https://fullscreen.spec.whatwg.org/#:fullscreen-pseudo-class
150      "fullscreen" => Fullscreen(VendorPrefix::None),
151      "-webkit-full-screen" => Fullscreen(VendorPrefix::WebKit),
152      "-moz-full-screen" => Fullscreen(VendorPrefix::Moz),
153      "-ms-fullscreen" => Fullscreen(VendorPrefix::Ms),
154
155      // https://drafts.csswg.org/selectors/#display-state-pseudos
156      "open" => Open,
157      "closed" => Closed,
158      "modal" => Modal,
159      "picture-in-picture" => PictureInPicture,
160
161      // https://html.spec.whatwg.org/multipage/semantics-other.html#selector-popover-open
162      "popover-open" => PopoverOpen,
163
164      // https://drafts.csswg.org/selectors-4/#the-defined-pseudo
165      "defined" => Defined,
166
167      // https://drafts.csswg.org/selectors-4/#location
168      "any-link" => AnyLink(VendorPrefix::None),
169      "-webkit-any-link" => AnyLink(VendorPrefix::WebKit),
170      "-moz-any-link" => AnyLink(VendorPrefix::Moz),
171      "link" => Link,
172      "local-link" => LocalLink,
173      "target" => Target,
174      "target-within" => TargetWithin,
175
176      // https://drafts.csswg.org/css-overflow-5/#active-before-after-scroll-markers
177      "target-current" if scroll_navigation_controls => TargetCurrent,
178      "target-before" if scroll_navigation_controls => TargetBefore,
179      "target-after" if scroll_navigation_controls => TargetAfter,
180
181      "visited" => Visited,
182
183      // https://drafts.csswg.org/selectors-4/#input-pseudos
184      "enabled" => Enabled,
185      "disabled" => Disabled,
186      "read-only" => ReadOnly(VendorPrefix::None),
187      "-moz-read-only" => ReadOnly(VendorPrefix::Moz),
188      "read-write" => ReadWrite(VendorPrefix::None),
189      "-moz-read-write" => ReadWrite(VendorPrefix::Moz),
190      "placeholder-shown" => PlaceholderShown(VendorPrefix::None),
191      "-moz-placeholder" => PlaceholderShown(VendorPrefix::Moz),
192      "-ms-input-placeholder" => PlaceholderShown(VendorPrefix::Ms),
193      "default" => Default,
194      "checked" => Checked,
195      "indeterminate" => Indeterminate,
196      "blank" => Blank,
197      "valid" => Valid,
198      "invalid" => Invalid,
199      "in-range" => InRange,
200      "out-of-range" => OutOfRange,
201      "required" => Required,
202      "optional" => Optional,
203      "user-valid" => UserValid,
204      "user-invalid" => UserInvalid,
205
206      // https://html.spec.whatwg.org/multipage/semantics-other.html#selector-autofill
207      "autofill" => Autofill(VendorPrefix::None),
208      "-webkit-autofill" => Autofill(VendorPrefix::WebKit),
209      "-o-autofill" => Autofill(VendorPrefix::O),
210
211      // https://drafts.csswg.org/css-view-transitions-2/#pseudo-classes-for-selective-vt
212      "active-view-transition" => ActiveViewTransition,
213
214      // https://webkit.org/blog/363/styling-scrollbars/
215      "horizontal" => WebKitScrollbar(WebKitScrollbarPseudoClass::Horizontal),
216      "vertical" => WebKitScrollbar(WebKitScrollbarPseudoClass::Vertical),
217      "decrement" => WebKitScrollbar(WebKitScrollbarPseudoClass::Decrement),
218      "increment" => WebKitScrollbar(WebKitScrollbarPseudoClass::Increment),
219      "start" => WebKitScrollbar(WebKitScrollbarPseudoClass::Start),
220      "end" => WebKitScrollbar(WebKitScrollbarPseudoClass::End),
221      "double-button" => WebKitScrollbar(WebKitScrollbarPseudoClass::DoubleButton),
222      "single-button" => WebKitScrollbar(WebKitScrollbarPseudoClass::SingleButton),
223      "no-button" => WebKitScrollbar(WebKitScrollbarPseudoClass::NoButton),
224      "corner-present" => WebKitScrollbar(WebKitScrollbarPseudoClass::CornerPresent),
225      "window-inactive" => WebKitScrollbar(WebKitScrollbarPseudoClass::WindowInactive),
226
227      "local" | "global" if self.options.css_modules.is_some() => {
228        return Err(loc.new_custom_error(SelectorParseErrorKind::AmbiguousCssModuleClass(name.clone())))
229      },
230
231      _ => {
232        if !name.starts_with('-') {
233          self.options.warn(loc.new_custom_error(SelectorParseErrorKind::UnsupportedPseudoClass(name.clone())));
234        }
235        Custom { name: name.into() }
236      }
237    };
238
239    Ok(pseudo_class)
240  }
241
242  fn parse_non_ts_functional_pseudo_class<'t>(
243    &self,
244    name: CowRcStr<'i>,
245    parser: &mut cssparser::Parser<'i, 't>,
246  ) -> Result<PseudoClass<'i>, ParseError<'i, Self::Error>> {
247    use PseudoClass::*;
248    let pseudo_class = match_ignore_ascii_case! { &name,
249      "lang" => {
250        let languages = parser.parse_comma_separated(|parser| {
251          parser.expect_ident_or_string()
252            .map(|s| s.into())
253            .map_err(|e| e.into())
254        })?;
255        Lang { languages }
256      },
257      "dir" => Dir { direction: Direction::parse(parser)? },
258      // https://drafts.csswg.org/css-view-transitions-2/#the-active-view-transition-type-pseudo
259      "active-view-transition-type" => {
260        let kind = Parse::parse(parser)?;
261        ActiveViewTransitionType { kind }
262      },
263      "state" => {
264        let state = CustomIdent::parse(parser)?;
265        State { state }
266      },
267      "local" if self.options.css_modules.is_some() => Local { selector: Box::new(Selector::parse(self, parser)?) },
268      "global" if self.options.css_modules.is_some() => Global { selector: Box::new(Selector::parse(self, parser)?) },
269      _ => {
270        if !name.starts_with('-') {
271          self.options.warn(parser.new_custom_error(SelectorParseErrorKind::UnsupportedPseudoClass(name.clone())));
272        }
273        let mut args = Vec::new();
274        TokenList::parse_raw(parser, &mut args, &self.options, 0)?;
275        CustomFunction {
276          name: name.into(),
277          arguments: TokenList(args)
278        }
279      },
280    };
281
282    Ok(pseudo_class)
283  }
284
285  fn parse_any_prefix<'t>(&self, name: &str) -> Option<VendorPrefix> {
286    match_ignore_ascii_case! { &name,
287      "-webkit-any" => Some(VendorPrefix::WebKit),
288      "-moz-any" => Some(VendorPrefix::Moz),
289      _ => None
290    }
291  }
292
293  fn parse_pseudo_element(
294    &self,
295    loc: SourceLocation,
296    name: CowRcStr<'i>,
297  ) -> Result<PseudoElement<'i>, ParseError<'i, Self::Error>> {
298    use PseudoElement::*;
299    let pseudo_element = match_ignore_ascii_case! { &name,
300      "before" => Before,
301      "after" => After,
302      "first-line" => FirstLine,
303      "first-letter" => FirstLetter,
304      "details-content" => DetailsContent,
305      "target-text" => TargetText,
306      "search-text" => SearchText,
307      "cue" => Cue,
308      "cue-region" => CueRegion,
309      "selection" => Selection(VendorPrefix::None),
310      "-moz-selection" => Selection(VendorPrefix::Moz),
311      "placeholder" => Placeholder(VendorPrefix::None),
312      "-webkit-input-placeholder" => Placeholder(VendorPrefix::WebKit),
313      "-moz-placeholder" => Placeholder(VendorPrefix::Moz),
314      "-ms-input-placeholder" => Placeholder(VendorPrefix::Moz),
315      "marker" => Marker,
316      "backdrop" => Backdrop(VendorPrefix::None),
317      "-webkit-backdrop" => Backdrop(VendorPrefix::WebKit),
318      "file-selector-button" => FileSelectorButton(VendorPrefix::None),
319      "-webkit-file-upload-button" => FileSelectorButton(VendorPrefix::WebKit),
320      "-ms-browse" => FileSelectorButton(VendorPrefix::Ms),
321
322      "-webkit-scrollbar" => WebKitScrollbar(WebKitScrollbarPseudoElement::Scrollbar),
323      "-webkit-scrollbar-button" => WebKitScrollbar(WebKitScrollbarPseudoElement::Button),
324      "-webkit-scrollbar-track" => WebKitScrollbar(WebKitScrollbarPseudoElement::Track),
325      "-webkit-scrollbar-track-piece" => WebKitScrollbar(WebKitScrollbarPseudoElement::TrackPiece),
326      "-webkit-scrollbar-thumb" => WebKitScrollbar(WebKitScrollbarPseudoElement::Thumb),
327      "-webkit-scrollbar-corner" => WebKitScrollbar(WebKitScrollbarPseudoElement::Corner),
328      "-webkit-resizer" => WebKitScrollbar(WebKitScrollbarPseudoElement::Resizer),
329
330      "picker-icon" => PickerIcon,
331      "checkmark" => Checkmark,
332
333      "view-transition" => ViewTransition,
334
335      "grammar-error" => GrammarError,
336      "spelling-error" => SpellingError,
337
338      _ => {
339        if !name.starts_with('-') {
340          self.options.warn(loc.new_custom_error(SelectorParseErrorKind::UnsupportedPseudoElement(name.clone())));
341        }
342        Custom { name: name.into() }
343      }
344    };
345
346    Ok(pseudo_element)
347  }
348
349  fn parse_functional_pseudo_element<'t>(
350    &self,
351    name: CowRcStr<'i>,
352    arguments: &mut Parser<'i, 't>,
353  ) -> Result<<Self::Impl as SelectorImpl<'i>>::PseudoElement, ParseError<'i, Self::Error>> {
354    use PseudoElement::*;
355    let pseudo_element = match_ignore_ascii_case! { &name,
356      "cue" => CueFunction { selector: Box::new(Selector::parse(self, arguments)?) },
357      "cue-region" => CueRegionFunction { selector: Box::new(Selector::parse(self, arguments)?) },
358      "highlight" => HighlightFunction { name: CustomIdent::parse(arguments)? },
359      "picker" => PickerFunction { identifier: Ident::parse(arguments)? },
360      "view-transition-group" => ViewTransitionGroup { part: ViewTransitionPartSelector::parse(arguments)? },
361      "view-transition-image-pair" => ViewTransitionImagePair { part: ViewTransitionPartSelector::parse(arguments)? },
362      "view-transition-old" => ViewTransitionOld { part: ViewTransitionPartSelector::parse(arguments)? },
363      "view-transition-new" => ViewTransitionNew { part: ViewTransitionPartSelector::parse(arguments)? },
364      _ => {
365        if !name.starts_with('-') {
366          self.options.warn(arguments.new_custom_error(SelectorParseErrorKind::UnsupportedPseudoElement(name.clone())));
367        }
368        let mut args = Vec::new();
369        TokenList::parse_raw(arguments, &mut args, &self.options, 0)?;
370        CustomFunction { name: name.into(), arguments: TokenList(args) }
371      }
372    };
373
374    Ok(pseudo_element)
375  }
376
377  #[inline]
378  fn parse_slotted(&self) -> bool {
379    true
380  }
381
382  #[inline]
383  fn parse_host(&self) -> bool {
384    true
385  }
386
387  #[inline]
388  fn parse_is_and_where(&self) -> bool {
389    true
390  }
391
392  #[inline]
393  fn parse_part(&self) -> bool {
394    true
395  }
396
397  fn default_namespace(&self) -> Option<CowArcStr<'i>> {
398    None
399  }
400
401  fn namespace_for_prefix(&self, prefix: &Ident<'i>) -> Option<CowArcStr<'i>> {
402    Some(prefix.0.clone())
403  }
404
405  #[inline]
406  fn is_nesting_allowed(&self) -> bool {
407    self.is_nesting_allowed
408  }
409
410  fn deep_combinator_enabled(&self) -> bool {
411    self.options.flags.contains(ParserFlags::DEEP_SELECTOR_COMBINATOR)
412  }
413}
414
415enum_property! {
416  /// The [:dir()](https://drafts.csswg.org/selectors-4/#the-dir-pseudo) pseudo class.
417  #[derive(Eq, Hash)]
418  pub enum Direction {
419    /// Left to right
420    Ltr,
421    /// Right to left
422    Rtl,
423  }
424}
425
426/// A pseudo class.
427#[derive(Clone, PartialEq, Eq, Hash)]
428#[cfg_attr(
429  feature = "serde",
430  derive(serde::Serialize, serde::Deserialize),
431  serde(tag = "kind", rename_all = "kebab-case")
432)]
433#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
434#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
435pub enum PseudoClass<'i> {
436  // https://drafts.csswg.org/selectors-4/#linguistic-pseudos
437  /// The [:lang()](https://drafts.csswg.org/selectors-4/#the-lang-pseudo) pseudo class.
438  Lang {
439    /// A list of language codes.
440    #[cfg_attr(feature = "serde", serde(borrow))]
441    languages: Vec<CowArcStr<'i>>,
442  },
443  /// The [:dir()](https://drafts.csswg.org/selectors-4/#the-dir-pseudo) pseudo class.
444  Dir {
445    /// A direction.
446    direction: Direction,
447  },
448
449  // https://drafts.csswg.org/selectors-4/#useraction-pseudos
450  /// The [:hover](https://drafts.csswg.org/selectors-4/#the-hover-pseudo) pseudo class.
451  Hover,
452  /// The [:active](https://drafts.csswg.org/selectors-4/#the-active-pseudo) pseudo class.
453  Active,
454  /// The [:focus](https://drafts.csswg.org/selectors-4/#the-focus-pseudo) pseudo class.
455  Focus,
456  /// The [:focus-visible](https://drafts.csswg.org/selectors-4/#the-focus-visible-pseudo) pseudo class.
457  FocusVisible,
458  /// The [:focus-within](https://drafts.csswg.org/selectors-4/#the-focus-within-pseudo) pseudo class.
459  FocusWithin,
460
461  // https://drafts.csswg.org/selectors-4/#time-pseudos
462  /// The [:current](https://drafts.csswg.org/selectors-4/#the-current-pseudo) pseudo class.
463  Current,
464  /// The [:past](https://drafts.csswg.org/selectors-4/#the-past-pseudo) pseudo class.
465  Past,
466  /// The [:future](https://drafts.csswg.org/selectors-4/#the-future-pseudo) pseudo class.
467  Future,
468
469  // https://drafts.csswg.org/selectors-4/#resource-pseudos
470  /// The [:playing](https://drafts.csswg.org/selectors-4/#selectordef-playing) pseudo class.
471  Playing,
472  /// The [:paused](https://drafts.csswg.org/selectors-4/#selectordef-paused) pseudo class.
473  Paused,
474  /// The [:seeking](https://drafts.csswg.org/selectors-4/#selectordef-seeking) pseudo class.
475  Seeking,
476  /// The [:buffering](https://drafts.csswg.org/selectors-4/#selectordef-buffering) pseudo class.
477  Buffering,
478  /// The [:stalled](https://drafts.csswg.org/selectors-4/#selectordef-stalled) pseudo class.
479  Stalled,
480  /// The [:muted](https://drafts.csswg.org/selectors-4/#selectordef-muted) pseudo class.
481  Muted,
482  /// The [:volume-locked](https://drafts.csswg.org/selectors-4/#selectordef-volume-locked) pseudo class.
483  VolumeLocked,
484
485  /// The [:fullscreen](https://fullscreen.spec.whatwg.org/#:fullscreen-pseudo-class) pseudo class.
486  #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
487  Fullscreen(VendorPrefix),
488
489  // https://drafts.csswg.org/selectors/#display-state-pseudos
490  /// The [:open](https://drafts.csswg.org/selectors/#selectordef-open) pseudo class.
491  Open,
492  /// The [:closed](https://drafts.csswg.org/selectors/#selectordef-closed) pseudo class.
493  Closed,
494  /// The [:modal](https://drafts.csswg.org/selectors/#modal-state) pseudo class.
495  Modal,
496  /// The [:picture-in-picture](https://drafts.csswg.org/selectors/#pip-state) pseudo class.
497  PictureInPicture,
498
499  // https://html.spec.whatwg.org/multipage/semantics-other.html#selector-popover-open
500  /// The [:popover-open](https://html.spec.whatwg.org/multipage/semantics-other.html#selector-popover-open) pseudo class.
501  PopoverOpen,
502
503  /// The [:defined](https://drafts.csswg.org/selectors-4/#the-defined-pseudo) pseudo class.
504  Defined,
505
506  // https://drafts.csswg.org/selectors-4/#location
507  /// The [:any-link](https://drafts.csswg.org/selectors-4/#the-any-link-pseudo) pseudo class.
508  #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
509  AnyLink(VendorPrefix),
510  /// The [:link](https://drafts.csswg.org/selectors-4/#link-pseudo) pseudo class.
511  Link,
512  /// The [:local-link](https://drafts.csswg.org/selectors-4/#the-local-link-pseudo) pseudo class.
513  LocalLink,
514  /// The [:target](https://drafts.csswg.org/selectors-4/#the-target-pseudo) pseudo class.
515  Target,
516
517  /// The [:target-current](https://drafts.csswg.org/css-overflow-5/#selectordef-target-current) pseudo class.
518  TargetCurrent,
519  /// The [:target-before](https://drafts.csswg.org/css-overflow-5/#selectordef-target-before) pseudo class.
520  TargetBefore,
521  /// The [:target-after](https://drafts.csswg.org/css-overflow-5/#selectordef-target-after) pseudo class.
522  TargetAfter,
523  /// The [:target-within](https://drafts.csswg.org/selectors-4/#the-target-within-pseudo) pseudo class.
524  TargetWithin,
525  /// The [:visited](https://drafts.csswg.org/selectors-4/#visited-pseudo) pseudo class.
526  Visited,
527
528  // https://drafts.csswg.org/selectors-4/#input-pseudos
529  /// The [:enabled](https://drafts.csswg.org/selectors-4/#enabled-pseudo) pseudo class.
530  Enabled,
531  /// The [:disabled](https://drafts.csswg.org/selectors-4/#disabled-pseudo) pseudo class.
532  Disabled,
533  /// The [:read-only](https://drafts.csswg.org/selectors-4/#read-only-pseudo) pseudo class.
534  #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
535  ReadOnly(VendorPrefix),
536  /// The [:read-write](https://drafts.csswg.org/selectors-4/#read-write-pseudo) pseudo class.
537  #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
538  ReadWrite(VendorPrefix),
539  /// The [:placeholder-shown](https://drafts.csswg.org/selectors-4/#placeholder) pseudo class.
540  #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
541  PlaceholderShown(VendorPrefix),
542  /// The [:default](https://drafts.csswg.org/selectors-4/#the-default-pseudo) pseudo class.
543  Default,
544  /// The [:checked](https://drafts.csswg.org/selectors-4/#checked) pseudo class.
545  Checked,
546  /// The [:indeterminate](https://drafts.csswg.org/selectors-4/#indeterminate) pseudo class.
547  Indeterminate,
548  /// The [:blank](https://drafts.csswg.org/selectors-4/#blank) pseudo class.
549  Blank,
550  /// The [:valid](https://drafts.csswg.org/selectors-4/#valid-pseudo) pseudo class.
551  Valid,
552  /// The [:invalid](https://drafts.csswg.org/selectors-4/#invalid-pseudo) pseudo class.
553  Invalid,
554  /// The [:in-range](https://drafts.csswg.org/selectors-4/#in-range-pseudo) pseudo class.
555  InRange,
556  /// The [:out-of-range](https://drafts.csswg.org/selectors-4/#out-of-range-pseudo) pseudo class.
557  OutOfRange,
558  /// The [:required](https://drafts.csswg.org/selectors-4/#required-pseudo) pseudo class.
559  Required,
560  /// The [:optional](https://drafts.csswg.org/selectors-4/#optional-pseudo) pseudo class.
561  Optional,
562  /// The [:user-valid](https://drafts.csswg.org/selectors-4/#user-valid-pseudo) pseudo class.
563  UserValid,
564  /// The [:used-invalid](https://drafts.csswg.org/selectors-4/#user-invalid-pseudo) pseudo class.
565  UserInvalid,
566
567  /// The [:autofill](https://html.spec.whatwg.org/multipage/semantics-other.html#selector-autofill) pseudo class.
568  #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
569  Autofill(VendorPrefix),
570
571  /// The [:active-view-transition](https://drafts.csswg.org/css-view-transitions-2/#the-active-view-transition-pseudo) pseudo class.
572  ActiveViewTransition,
573  /// The [:active-view-transition-type()](https://drafts.csswg.org/css-view-transitions-2/#the-active-view-transition-type-pseudo) pseudo class.
574  ActiveViewTransitionType {
575    /// A view transition type.
576    #[cfg_attr(feature = "serde", serde(rename = "type"))]
577    kind: SmallVec<[CustomIdent<'i>; 1]>,
578  },
579
580  /// The [:state()](https://developer.mozilla.org/en-US/docs/Web/CSS/:state) pseudo class for custom element states.
581  State {
582    /// The custom state identifier.
583    state: CustomIdent<'i>,
584  },
585
586  // CSS modules
587  /// The CSS modules :local() pseudo class.
588  Local {
589    /// A local selector.
590    selector: Box<Selector<'i>>,
591  },
592  /// The CSS modules :global() pseudo class.
593  Global {
594    /// A global selector.
595    selector: Box<Selector<'i>>,
596  },
597
598  /// A [webkit scrollbar](https://webkit.org/blog/363/styling-scrollbars/) pseudo class.
599  // https://webkit.org/blog/363/styling-scrollbars/
600  #[cfg_attr(
601    feature = "serde",
602    serde(rename = "webkit-scrollbar", with = "ValueWrapper::<WebKitScrollbarPseudoClass>")
603  )]
604  WebKitScrollbar(WebKitScrollbarPseudoClass),
605  /// An unknown pseudo class.
606  Custom {
607    /// The pseudo class name.
608    name: CowArcStr<'i>,
609  },
610  /// An unknown functional pseudo class.
611  CustomFunction {
612    /// The pseudo class name.
613    name: CowArcStr<'i>,
614    /// The arguments of the pseudo class function.
615    arguments: TokenList<'i>,
616  },
617}
618
619/// A [webkit scrollbar](https://webkit.org/blog/363/styling-scrollbars/) pseudo class.
620#[derive(Clone, Eq, PartialEq, Hash)]
621#[cfg_attr(
622  feature = "serde",
623  derive(serde::Serialize, serde::Deserialize),
624  serde(rename_all = "kebab-case")
625)]
626#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
627#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
628pub enum WebKitScrollbarPseudoClass {
629  /// :horizontal
630  Horizontal,
631  /// :vertical
632  Vertical,
633  /// :decrement
634  Decrement,
635  /// :increment
636  Increment,
637  /// :start
638  Start,
639  /// :end
640  End,
641  /// :double-button
642  DoubleButton,
643  /// :single-button
644  SingleButton,
645  /// :no-button
646  NoButton,
647  /// :corner-present
648  CornerPresent,
649  /// :window-inactive
650  WindowInactive,
651}
652
653impl<'i> rspack_lightningcss_selectors::parser::NonTSPseudoClass<'i> for PseudoClass<'i> {
654  type Impl = Selectors;
655
656  fn is_active_or_hover(&self) -> bool {
657    matches!(*self, PseudoClass::Active | PseudoClass::Hover)
658  }
659
660  fn is_user_action_state(&self) -> bool {
661    matches!(
662      *self,
663      PseudoClass::Active
664        | PseudoClass::Hover
665        | PseudoClass::Focus
666        | PseudoClass::FocusWithin
667        | PseudoClass::FocusVisible
668    )
669  }
670
671  fn is_valid_before_webkit_scrollbar(&self) -> bool {
672    !matches!(*self, PseudoClass::WebKitScrollbar(..))
673  }
674
675  fn is_valid_after_webkit_scrollbar(&self) -> bool {
676    // https://github.com/WebKit/WebKit/blob/02fbf9b7aa435edb96cbf563a8d4dcf1aa73b4b3/Source/WebCore/css/parser/CSSSelectorParser.cpp#L285
677    matches!(
678      *self,
679      PseudoClass::WebKitScrollbar(..)
680        | PseudoClass::Enabled
681        | PseudoClass::Disabled
682        | PseudoClass::Hover
683        | PseudoClass::Active
684    )
685  }
686}
687
688impl<'i> cssparser::ToCss for PseudoClass<'i> {
689  fn to_css<W>(&self, dest: &mut W) -> std::fmt::Result
690  where
691    W: fmt::Write,
692  {
693    let mut s = String::new();
694    let mut printer = Printer::new(&mut s, PrinterOptions::default());
695    serialize_pseudo_class(self, &mut printer, None).map_err(|_| std::fmt::Error)?;
696    write!(dest, "{}", s)
697  }
698}
699
700fn serialize_pseudo_class<'a, 'i, PrinterT: crate::printer::PrinterTrait>(
701  pseudo_class: &PseudoClass<'i>,
702  dest: &mut PrinterT,
703  context: Option<&StyleContext>,
704) -> Result<(), PrinterError> {
705  use PseudoClass::*;
706  match pseudo_class {
707    Lang { languages: lang } => {
708      dest.write_str(":lang(")?;
709      let mut first = true;
710      for lang in lang {
711        if first {
712          first = false;
713        } else {
714          dest.delim(',', false)?;
715        }
716        serialize_identifier(lang, dest)?;
717      }
718      dest.write_str(")")?;
719      return Ok(());
720    }
721    Dir { direction: dir } => {
722      dest.write_str(":dir(")?;
723      dir.to_css(dest)?;
724      dest.write_str(")")?;
725      return Ok(());
726    }
727    State { state } => {
728      dest.write_str(":state(")?;
729      state.to_css(dest)?;
730      dest.write_str(")")?;
731      return Ok(());
732    }
733    _ => {}
734  }
735
736  macro_rules! write_prefixed {
737    ($prefix: ident, $val: expr) => {{
738      dest.write_char(':')?;
739      // If the printer has a vendor prefix override, use that.
740      let vp = if !dest.vendor_prefix().is_empty() {
741        (dest.vendor_prefix() & *$prefix).or_none()
742      } else {
743        *$prefix
744      };
745      vp.to_css(dest)?;
746      dest.write_str($val)?;
747      Ok(())
748    }};
749  }
750
751  macro_rules! pseudo {
752    ($key: ident, $s: literal) => {{
753      dest.with_pseudo_class(
754        |pseudo_classes| pseudo_classes.$key,
755        |dest, class| {
756          if let Some(class) = class {
757            dest.write_char('.')?;
758            dest.write_ident(class, true)
759          } else {
760            dest.write_str($s)?;
761            Ok(())
762          }
763        },
764      )
765    }};
766  }
767
768  match pseudo_class {
769    // https://drafts.csswg.org/selectors-4/#useraction-pseudos
770    Hover => pseudo!(hover, ":hover"),
771    Active => pseudo!(active, ":active"),
772    Focus => pseudo!(focus, ":focus"),
773    FocusVisible => pseudo!(focus_visible, ":focus-visible"),
774    FocusWithin => pseudo!(focus_within, ":focus-within"),
775
776    // https://drafts.csswg.org/selectors-4/#time-pseudos
777    Current => {
778      dest.write_str(":current")?;
779      Ok(())
780    }
781    Past => {
782      dest.write_str(":past")?;
783      Ok(())
784    }
785    Future => {
786      dest.write_str(":future")?;
787      Ok(())
788    }
789
790    // https://drafts.csswg.org/selectors-4/#resource-pseudos
791    Playing => {
792      dest.write_str(":playing")?;
793      Ok(())
794    }
795    Paused => {
796      dest.write_str(":paused")?;
797      Ok(())
798    }
799    Seeking => {
800      dest.write_str(":seeking")?;
801      Ok(())
802    }
803    Buffering => {
804      dest.write_str(":buffering")?;
805      Ok(())
806    }
807    Stalled => {
808      dest.write_str(":stalled")?;
809      Ok(())
810    }
811    Muted => {
812      dest.write_str(":muted")?;
813      Ok(())
814    }
815    VolumeLocked => {
816      dest.write_str(":volume-locked")?;
817      Ok(())
818    }
819
820    // https://fullscreen.spec.whatwg.org/#:fullscreen-pseudo-class
821    Fullscreen(prefix) => {
822      dest.write_char(':')?;
823      let vp = if !dest.vendor_prefix().is_empty() {
824        (dest.vendor_prefix() & *prefix).or_none()
825      } else {
826        *prefix
827      };
828      vp.to_css(dest)?;
829      if vp == VendorPrefix::WebKit || vp == VendorPrefix::Moz {
830        dest.write_str("full-screen")?;
831        Ok(())
832      } else {
833        dest.write_str("fullscreen")?;
834        Ok(())
835      }
836    }
837
838    // https://drafts.csswg.org/selectors/#display-state-pseudos
839    Open => {
840      dest.write_str(":open")?;
841      Ok(())
842    }
843    Closed => {
844      dest.write_str(":closed")?;
845      Ok(())
846    }
847    Modal => {
848      dest.write_str(":modal")?;
849      Ok(())
850    }
851    PictureInPicture => {
852      dest.write_str(":picture-in-picture")?;
853      Ok(())
854    }
855
856    // https://html.spec.whatwg.org/multipage/semantics-other.html#selector-popover-open
857    PopoverOpen => {
858      dest.write_str(":popover-open")?;
859      Ok(())
860    }
861
862    // https://drafts.csswg.org/selectors-4/#the-defined-pseudo
863    Defined => {
864      dest.write_str(":defined")?;
865      Ok(())
866    }
867
868    // https://drafts.csswg.org/selectors-4/#location
869    AnyLink(prefix) => write_prefixed!(prefix, "any-link"),
870    Link => {
871      dest.write_str(":link")?;
872      Ok(())
873    }
874    LocalLink => {
875      dest.write_str(":local-link")?;
876      Ok(())
877    }
878    Target => {
879      dest.write_str(":target")?;
880      Ok(())
881    }
882    TargetWithin => {
883      dest.write_str(":target-within")?;
884      Ok(())
885    }
886
887    // https://drafts.csswg.org/css-overflow-5/#active-before-after-scroll-markers
888    TargetCurrent => {
889      dest.write_str(":target-current")?;
890      Ok(())
891    }
892    TargetBefore => {
893      dest.write_str(":target-before")?;
894      Ok(())
895    }
896    TargetAfter => {
897      dest.write_str(":target-after")?;
898      Ok(())
899    }
900
901    Visited => {
902      dest.write_str(":visited")?;
903      Ok(())
904    }
905
906    // https://drafts.csswg.org/selectors-4/#input-pseudos
907    Enabled => {
908      dest.write_str(":enabled")?;
909      Ok(())
910    }
911    Disabled => {
912      dest.write_str(":disabled")?;
913      Ok(())
914    }
915    ReadOnly(prefix) => write_prefixed!(prefix, "read-only"),
916    ReadWrite(prefix) => write_prefixed!(prefix, "read-write"),
917    PlaceholderShown(prefix) => write_prefixed!(prefix, "placeholder-shown"),
918    Default => {
919      dest.write_str(":default")?;
920      Ok(())
921    }
922    Checked => {
923      dest.write_str(":checked")?;
924      Ok(())
925    }
926    Indeterminate => {
927      dest.write_str(":indeterminate")?;
928      Ok(())
929    }
930    Blank => {
931      dest.write_str(":blank")?;
932      Ok(())
933    }
934    Valid => {
935      dest.write_str(":valid")?;
936      Ok(())
937    }
938    Invalid => {
939      dest.write_str(":invalid")?;
940      Ok(())
941    }
942    InRange => {
943      dest.write_str(":in-range")?;
944      Ok(())
945    }
946    OutOfRange => {
947      dest.write_str(":out-of-range")?;
948      Ok(())
949    }
950    Required => {
951      dest.write_str(":required")?;
952      Ok(())
953    }
954    Optional => {
955      dest.write_str(":optional")?;
956      Ok(())
957    }
958    UserValid => {
959      dest.write_str(":user-valid")?;
960      Ok(())
961    }
962    UserInvalid => {
963      dest.write_str(":user-invalid")?;
964      Ok(())
965    }
966
967    // https://html.spec.whatwg.org/multipage/semantics-other.html#selector-autofill
968    Autofill(prefix) => write_prefixed!(prefix, "autofill"),
969
970    ActiveViewTransition => {
971      dest.write_str(":active-view-transition")?;
972      Ok(())
973    }
974    ActiveViewTransitionType { kind } => {
975      dest.write_str(":active-view-transition-type(")?;
976      kind.to_css(dest)?;
977      dest.write_char(')')?;
978      Ok(())
979    }
980
981    Local { selector } => serialize_selector(selector, dest, context, false),
982    Global { selector } => dest.without_css_module(|dest| serialize_selector(selector, dest, context, false)),
983
984    // https://webkit.org/blog/363/styling-scrollbars/
985    WebKitScrollbar(s) => {
986      use WebKitScrollbarPseudoClass::*;
987      dest.write_str(match s {
988        Horizontal => ":horizontal",
989        Vertical => ":vertical",
990        Decrement => ":decrement",
991        Increment => ":increment",
992        Start => ":start",
993        End => ":end",
994        DoubleButton => ":double-button",
995        SingleButton => ":single-button",
996        NoButton => ":no-button",
997        CornerPresent => ":corner-present",
998        WindowInactive => ":window-inactive",
999      })?;
1000      Ok(())
1001    }
1002
1003    Lang { languages: _ } | Dir { direction: _ } | State { .. } => unreachable!(),
1004    Custom { name } => {
1005      dest.write_char(':')?;
1006      dest.write_str(&name)?;
1007      return Ok(());
1008    }
1009    CustomFunction { name, arguments: args } => {
1010      dest.write_char(':')?;
1011      dest.write_str(name)?;
1012      dest.write_char('(')?;
1013      args.to_css_raw(dest)?;
1014      dest.write_char(')')?;
1015      Ok(())
1016    }
1017  }
1018}
1019
1020impl<'i> PseudoClass<'i> {
1021  pub(crate) fn is_equivalent(&self, other: &PseudoClass<'i>) -> bool {
1022    use PseudoClass::*;
1023    match (self, other) {
1024      (Fullscreen(_), Fullscreen(_))
1025      | (AnyLink(_), AnyLink(_))
1026      | (ReadOnly(_), ReadOnly(_))
1027      | (ReadWrite(_), ReadWrite(_))
1028      | (PlaceholderShown(_), PlaceholderShown(_))
1029      | (Autofill(_), Autofill(_)) => true,
1030      (a, b) => a == b,
1031    }
1032  }
1033
1034  pub(crate) fn get_prefix(&self) -> VendorPrefix {
1035    use PseudoClass::*;
1036    match self {
1037      Fullscreen(p) | AnyLink(p) | ReadOnly(p) | ReadWrite(p) | PlaceholderShown(p) | Autofill(p) => *p,
1038      _ => VendorPrefix::empty(),
1039    }
1040  }
1041
1042  pub(crate) fn get_necessary_prefixes(&mut self, targets: Targets) -> VendorPrefix {
1043    use crate::prefixes::Feature;
1044    use PseudoClass::*;
1045    let (p, feature) = match self {
1046      Fullscreen(p) => (p, Feature::PseudoClassFullscreen),
1047      AnyLink(p) => (p, Feature::PseudoClassAnyLink),
1048      ReadOnly(p) => (p, Feature::PseudoClassReadOnly),
1049      ReadWrite(p) => (p, Feature::PseudoClassReadWrite),
1050      PlaceholderShown(p) => (p, Feature::PseudoClassPlaceholderShown),
1051      Autofill(p) => (p, Feature::PseudoClassAutofill),
1052      _ => return VendorPrefix::empty(),
1053    };
1054
1055    *p = targets.prefixes(*p, feature);
1056    *p
1057  }
1058}
1059
1060/// A pseudo element.
1061#[derive(PartialEq, Eq, Hash, Clone, Debug)]
1062#[cfg_attr(
1063  feature = "serde",
1064  derive(serde::Serialize, serde::Deserialize),
1065  serde(tag = "kind", rename_all = "kebab-case")
1066)]
1067#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1068#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1069pub enum PseudoElement<'i> {
1070  /// The [::after](https://drafts.csswg.org/css-pseudo-4/#selectordef-after) pseudo element.
1071  After,
1072  /// The [::before](https://drafts.csswg.org/css-pseudo-4/#selectordef-before) pseudo element.
1073  Before,
1074  /// The [::first-line](https://drafts.csswg.org/css-pseudo-4/#first-line-pseudo) pseudo element.
1075  FirstLine,
1076  /// The [::first-letter](https://drafts.csswg.org/css-pseudo-4/#first-letter-pseudo) pseudo element.
1077  FirstLetter,
1078  /// The [::details-content](https://drafts.csswg.org/css-pseudo-4/#details-content-pseudo)
1079  DetailsContent,
1080  /// The [::target-text](https://drafts.csswg.org/css-pseudo-4/#selectordef-target-text)
1081  TargetText,
1082  /// The [::search-text](https://drafts.csswg.org/css-pseudo-4/#selectordef-search-text) pseudo element.
1083  SearchText,
1084  /// The [::selection](https://drafts.csswg.org/css-pseudo-4/#selectordef-selection) pseudo element.
1085  #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
1086  Selection(VendorPrefix),
1087  /// The [::placeholder](https://drafts.csswg.org/css-pseudo-4/#placeholder-pseudo) pseudo element.
1088  #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
1089  Placeholder(VendorPrefix),
1090  /// The [::highlight()](https://drafts.csswg.org/css-highlight-api/#custom-highlight-pseudo) functional pseudo element.
1091  HighlightFunction {
1092    /// A custom highlight name.
1093    name: CustomIdent<'i>,
1094  },
1095  ///  The [::marker](https://drafts.csswg.org/css-pseudo-4/#marker-pseudo) pseudo element.
1096  Marker,
1097  /// The [::backdrop](https://fullscreen.spec.whatwg.org/#::backdrop-pseudo-element) pseudo element.
1098  #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
1099  Backdrop(VendorPrefix),
1100  /// The [::file-selector-button](https://drafts.csswg.org/css-pseudo-4/#file-selector-button-pseudo) pseudo element.
1101  #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
1102  FileSelectorButton(VendorPrefix),
1103  /// A [webkit scrollbar](https://webkit.org/blog/363/styling-scrollbars/) pseudo element.
1104  #[cfg_attr(
1105    feature = "serde",
1106    serde(rename = "webkit-scrollbar", with = "ValueWrapper::<WebKitScrollbarPseudoElement>")
1107  )]
1108  WebKitScrollbar(WebKitScrollbarPseudoElement),
1109  /// The [::cue](https://w3c.github.io/webvtt/#the-cue-pseudo-element) pseudo element.
1110  Cue,
1111  /// The [::cue-region](https://w3c.github.io/webvtt/#the-cue-region-pseudo-element) pseudo element.
1112  CueRegion,
1113  /// The [::cue()](https://w3c.github.io/webvtt/#cue-selector) functional pseudo element.
1114  CueFunction {
1115    /// The selector argument.
1116    selector: Box<Selector<'i>>,
1117  },
1118  /// The [::cue-region()](https://w3c.github.io/webvtt/#cue-region-selector) functional pseudo element.
1119  CueRegionFunction {
1120    /// The selector argument.
1121    selector: Box<Selector<'i>>,
1122  },
1123  /// The [::view-transition](https://w3c.github.io/csswg-drafts/css-view-transitions-1/#view-transition) pseudo element.
1124  ViewTransition,
1125  /// The [::view-transition-group()](https://w3c.github.io/csswg-drafts/css-view-transitions-1/#view-transition-group-pt-name-selector) functional pseudo element.
1126  #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
1127  ViewTransitionGroup {
1128    /// A part name selector.
1129    part: ViewTransitionPartSelector<'i>,
1130  },
1131  /// The [::view-transition-image-pair()](https://w3c.github.io/csswg-drafts/css-view-transitions-1/#view-transition-image-pair-pt-name-selector) functional pseudo element.
1132  #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
1133  ViewTransitionImagePair {
1134    /// A part name selector.
1135    part: ViewTransitionPartSelector<'i>,
1136  },
1137  /// The [::view-transition-old()](https://w3c.github.io/csswg-drafts/css-view-transitions-1/#view-transition-old-pt-name-selector) functional pseudo element.
1138  #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
1139  ViewTransitionOld {
1140    /// A part name selector.
1141    part: ViewTransitionPartSelector<'i>,
1142  },
1143  /// The [::view-transition-new()](https://w3c.github.io/csswg-drafts/css-view-transitions-1/#view-transition-new-pt-name-selector) functional pseudo element.
1144  #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
1145  ViewTransitionNew {
1146    /// A part name selector.
1147    part: ViewTransitionPartSelector<'i>,
1148  },
1149  /// The [::picker()](https://drafts.csswg.org/css-forms-1/#the-picker-pseudo-element) functional pseudo element.
1150  PickerFunction {
1151    /// A form control identifier.
1152    identifier: Ident<'i>,
1153  },
1154  /// The [::picker-icon](https://drafts.csswg.org/css-forms-1/#picker-opener-icon-the-picker-icon-pseudo-element) pseudo element.
1155  PickerIcon,
1156  /// The [::checkmark](https://drafts.csswg.org/css-forms-1/#styling-checkmarks-the-checkmark-pseudo-element) pseudo element.
1157  Checkmark,
1158  /// The [::grammar-error](https://drafts.csswg.org/css-pseudo/#selectordef-grammar-error) pseudo element.
1159  GrammarError,
1160  /// The [::spelling-error](https://drafts.csswg.org/css-pseudo/#selectordef-spelling-error) pseudo element.
1161  SpellingError,
1162  /// An unknown pseudo element.
1163  Custom {
1164    /// The name of the pseudo element.
1165    #[cfg_attr(feature = "serde", serde(borrow))]
1166    name: CowArcStr<'i>,
1167  },
1168  /// An unknown functional pseudo element.
1169  CustomFunction {
1170    ///The name of the pseudo element.
1171    name: CowArcStr<'i>,
1172    /// The arguments of the pseudo element function.
1173    arguments: TokenList<'i>,
1174  },
1175}
1176
1177/// A [webkit scrollbar](https://webkit.org/blog/363/styling-scrollbars/) pseudo element.
1178#[derive(PartialEq, Eq, Clone, Debug, Hash)]
1179#[cfg_attr(
1180  feature = "serde",
1181  derive(serde::Serialize, serde::Deserialize),
1182  serde(rename_all = "kebab-case")
1183)]
1184#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1185#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1186pub enum WebKitScrollbarPseudoElement {
1187  /// ::-webkit-scrollbar
1188  Scrollbar,
1189  /// ::-webkit-scrollbar-button
1190  Button,
1191  /// ::-webkit-scrollbar-track
1192  Track,
1193  /// ::-webkit-scrollbar-track-piece
1194  TrackPiece,
1195  /// ::-webkit-scrollbar-thumb
1196  Thumb,
1197  /// ::-webkit-scrollbar-corner
1198  Corner,
1199  /// ::-webkit-resizer
1200  Resizer,
1201}
1202
1203/// A [view transition part name](https://w3c.github.io/csswg-drafts/css-view-transitions-1/#typedef-pt-name-selector).
1204#[derive(PartialEq, Eq, Clone, Debug, Hash)]
1205#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1206#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1207pub enum ViewTransitionPartName<'i> {
1208  /// *
1209  #[cfg_attr(feature = "serde", serde(rename = "*"))]
1210  All,
1211  /// <custom-ident>
1212  #[cfg_attr(feature = "serde", serde(borrow, untagged))]
1213  Name(CustomIdent<'i>),
1214}
1215
1216#[cfg(feature = "jsonschema")]
1217#[cfg_attr(docsrs, doc(cfg(feature = "jsonschema")))]
1218impl<'a> schemars::JsonSchema for ViewTransitionPartName<'a> {
1219  fn is_referenceable() -> bool {
1220    true
1221  }
1222
1223  fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
1224    str::json_schema(gen)
1225  }
1226
1227  fn schema_name() -> String {
1228    "ViewTransitionPartName".into()
1229  }
1230}
1231
1232impl<'i> Parse<'i> for ViewTransitionPartName<'i> {
1233  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1234    if input.try_parse(|input| input.expect_delim('*')).is_ok() {
1235      return Ok(ViewTransitionPartName::All);
1236    }
1237
1238    Ok(ViewTransitionPartName::Name(CustomIdent::parse(input)?))
1239  }
1240}
1241
1242impl<'i> ToCss for ViewTransitionPartName<'i> {
1243  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1244    match self {
1245      ViewTransitionPartName::All => {
1246        dest.write_char('*')?;
1247        Ok(())
1248      }
1249      ViewTransitionPartName::Name(name) => name.to_css(dest),
1250    }
1251  }
1252}
1253
1254/// A [view transition part selector](https://w3c.github.io/csswg-drafts/css-view-transitions-1/#typedef-pt-name-selector).
1255#[derive(PartialEq, Eq, Clone, Debug, Hash)]
1256#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1257#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1258#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1259pub struct ViewTransitionPartSelector<'i> {
1260  /// The view transition part name.
1261  #[cfg_attr(feature = "serde", serde(borrow))]
1262  name: Option<ViewTransitionPartName<'i>>,
1263  /// A list of view transition classes.
1264  classes: Vec<CustomIdent<'i>>,
1265}
1266
1267impl<'i> Parse<'i> for ViewTransitionPartSelector<'i> {
1268  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1269    input.skip_whitespace();
1270    let name = input.try_parse(ViewTransitionPartName::parse).ok();
1271    let mut classes = Vec::new();
1272    while let Ok(token) = input.next_including_whitespace() {
1273      if matches!(token, Token::Delim('.')) {
1274        match input.next_including_whitespace() {
1275          Ok(Token::Ident(id)) => classes.push(CustomIdent(id.into())),
1276          _ => return Err(input.new_custom_error(ParserError::SelectorError(SelectorError::InvalidState))),
1277        }
1278      } else {
1279        break;
1280      }
1281    }
1282
1283    if !input.is_exhausted() || (name.is_none() && classes.is_empty()) {
1284      return Err(input.new_custom_error(ParserError::SelectorError(SelectorError::InvalidState)));
1285    }
1286
1287    Ok(ViewTransitionPartSelector { name, classes })
1288  }
1289}
1290
1291impl<'i> ToCss for ViewTransitionPartSelector<'i> {
1292  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1293    if let Some(name) = &self.name {
1294      name.to_css(dest)?;
1295    }
1296    for class in &self.classes {
1297      dest.write_char('.')?;
1298      class.to_css(dest)?;
1299    }
1300    Ok(())
1301  }
1302}
1303
1304impl<'i> cssparser::ToCss for PseudoElement<'i> {
1305  fn to_css<W>(&self, dest: &mut W) -> std::fmt::Result
1306  where
1307    W: fmt::Write,
1308  {
1309    let mut s = String::new();
1310    let mut printer = Printer::new(&mut s, PrinterOptions::default());
1311    serialize_pseudo_element(self, &mut printer, None).map_err(|_| std::fmt::Error)?;
1312    write!(dest, "{}", s)
1313  }
1314}
1315
1316fn serialize_pseudo_element<'a, 'i, PrinterT: crate::printer::PrinterTrait>(
1317  pseudo_element: &PseudoElement,
1318  dest: &mut PrinterT,
1319  context: Option<&StyleContext>,
1320) -> Result<(), PrinterError> {
1321  use PseudoElement::*;
1322
1323  macro_rules! write_prefix {
1324    ($prefix: ident) => {{
1325      dest.write_str("::")?;
1326      // If the printer has a vendor prefix override, use that.
1327      let vp = if !dest.vendor_prefix().is_empty() {
1328        (dest.vendor_prefix() & *$prefix).or_none()
1329      } else {
1330        *$prefix
1331      };
1332      vp.to_css(dest)?;
1333      vp
1334    }};
1335  }
1336
1337  macro_rules! write_prefixed {
1338    ($prefix: ident, $val: expr) => {{
1339      write_prefix!($prefix);
1340      dest.write_str($val)?;
1341      Ok(())
1342    }};
1343  }
1344
1345  match pseudo_element {
1346    // CSS2 pseudo elements support a single colon syntax in addition
1347    // to the more correct double colon for other pseudo elements.
1348    // We use that here because it's supported everywhere and is shorter.
1349    After => {
1350      dest.write_str(":after")?;
1351      Ok(())
1352    }
1353    Before => {
1354      dest.write_str(":before")?;
1355      Ok(())
1356    }
1357    FirstLine => {
1358      dest.write_str(":first-line")?;
1359      Ok(())
1360    }
1361    FirstLetter => {
1362      dest.write_str(":first-letter")?;
1363      Ok(())
1364    }
1365    DetailsContent => {
1366      dest.write_str("::details-content")?;
1367      Ok(())
1368    }
1369    TargetText => {
1370      dest.write_str("::target-text")?;
1371      Ok(())
1372    }
1373    SearchText => {
1374      dest.write_str("::search-text")?;
1375      Ok(())
1376    }
1377    HighlightFunction { name } => {
1378      dest.write_str("::highlight(")?;
1379      name.to_css(dest)?;
1380      dest.write_char(')')?;
1381      Ok(())
1382    }
1383    Marker => {
1384      dest.write_str("::marker")?;
1385      Ok(())
1386    }
1387    Selection(prefix) => write_prefixed!(prefix, "selection"),
1388    Cue => {
1389      dest.write_str("::cue")?;
1390      Ok(())
1391    }
1392    CueRegion => {
1393      dest.write_str("::cue-region")?;
1394      Ok(())
1395    }
1396    CueFunction { selector } => {
1397      dest.write_str("::cue(")?;
1398      serialize_selector(selector, dest, context, false)?;
1399      dest.write_char(')')?;
1400      Ok(())
1401    }
1402    CueRegionFunction { selector } => {
1403      dest.write_str("::cue-region(")?;
1404      serialize_selector(selector, dest, context, false)?;
1405      dest.write_char(')')?;
1406      Ok(())
1407    }
1408    Placeholder(prefix) => {
1409      let vp = write_prefix!(prefix);
1410      if vp == VendorPrefix::WebKit || vp == VendorPrefix::Ms {
1411        dest.write_str("input-placeholder")?;
1412        Ok(())
1413      } else {
1414        dest.write_str("placeholder")?;
1415        Ok(())
1416      }
1417    }
1418    Backdrop(prefix) => write_prefixed!(prefix, "backdrop"),
1419    FileSelectorButton(prefix) => {
1420      let vp = write_prefix!(prefix);
1421      if vp == VendorPrefix::WebKit {
1422        dest.write_str("file-upload-button")?;
1423        Ok(())
1424      } else if vp == VendorPrefix::Ms {
1425        dest.write_str("browse")?;
1426        Ok(())
1427      } else {
1428        dest.write_str("file-selector-button")?;
1429        Ok(())
1430      }
1431    }
1432    WebKitScrollbar(s) => {
1433      use WebKitScrollbarPseudoElement::*;
1434      dest.write_str(match s {
1435        Scrollbar => "::-webkit-scrollbar",
1436        Button => "::-webkit-scrollbar-button",
1437        Track => "::-webkit-scrollbar-track",
1438        TrackPiece => "::-webkit-scrollbar-track-piece",
1439        Thumb => "::-webkit-scrollbar-thumb",
1440        Corner => "::-webkit-scrollbar-corner",
1441        Resizer => "::-webkit-resizer",
1442      })?;
1443      Ok(())
1444    }
1445    ViewTransition => {
1446      dest.write_str("::view-transition")?;
1447      Ok(())
1448    }
1449    ViewTransitionGroup { part } => {
1450      dest.write_str("::view-transition-group(")?;
1451      part.to_css(dest)?;
1452      dest.write_char(')')?;
1453      Ok(())
1454    }
1455    ViewTransitionImagePair { part } => {
1456      dest.write_str("::view-transition-image-pair(")?;
1457      part.to_css(dest)?;
1458      dest.write_char(')')?;
1459      Ok(())
1460    }
1461    ViewTransitionOld { part } => {
1462      dest.write_str("::view-transition-old(")?;
1463      part.to_css(dest)?;
1464      dest.write_char(')')?;
1465      Ok(())
1466    }
1467    ViewTransitionNew { part } => {
1468      dest.write_str("::view-transition-new(")?;
1469      part.to_css(dest)?;
1470      dest.write_char(')')?;
1471      Ok(())
1472    }
1473    PickerFunction { identifier } => {
1474      dest.write_str("::picker(")?;
1475      identifier.to_css(dest)?;
1476      dest.write_char(')')?;
1477      Ok(())
1478    }
1479    PickerIcon => {
1480      dest.write_str("::picker-icon")?;
1481      Ok(())
1482    }
1483    Checkmark => {
1484      dest.write_str("::checkmark")?;
1485      Ok(())
1486    }
1487    GrammarError => {
1488      dest.write_str("::grammar-error")?;
1489      Ok(())
1490    }
1491    SpellingError => {
1492      dest.write_str("::spelling-error")?;
1493      Ok(())
1494    }
1495    Custom { name: val } => {
1496      dest.write_str("::")?;
1497      dest.write_str(val)?;
1498      return Ok(());
1499    }
1500    CustomFunction { name, arguments: args } => {
1501      dest.write_str("::")?;
1502      dest.write_str(name)?;
1503      dest.write_char('(')?;
1504      args.to_css_raw(dest)?;
1505      dest.write_char(')')?;
1506      Ok(())
1507    }
1508  }
1509}
1510
1511impl<'i> rspack_lightningcss_selectors::parser::PseudoElement<'i> for PseudoElement<'i> {
1512  type Impl = Selectors;
1513
1514  fn accepts_state_pseudo_classes(&self) -> bool {
1515    // Be lenient.
1516    true
1517  }
1518
1519  fn valid_after_slotted(&self) -> bool {
1520    // ::slotted() should support all tree-abiding pseudo-elements, see
1521    // https://drafts.csswg.org/css-scoping/#slotted-pseudo
1522    // https://drafts.csswg.org/css-pseudo-4/#treelike
1523    matches!(
1524      *self,
1525      PseudoElement::Before
1526        | PseudoElement::After
1527        | PseudoElement::Marker
1528        | PseudoElement::Placeholder(_)
1529        | PseudoElement::FileSelectorButton(_)
1530    )
1531  }
1532
1533  fn is_webkit_scrollbar(&self) -> bool {
1534    matches!(*self, PseudoElement::WebKitScrollbar(..))
1535  }
1536
1537  fn is_view_transition(&self) -> bool {
1538    matches!(
1539      *self,
1540      PseudoElement::ViewTransitionGroup { .. }
1541        | PseudoElement::ViewTransitionImagePair { .. }
1542        | PseudoElement::ViewTransitionNew { .. }
1543        | PseudoElement::ViewTransitionOld { .. }
1544    )
1545  }
1546
1547  fn is_unknown(&self) -> bool {
1548    matches!(
1549      *self,
1550      PseudoElement::Custom { .. } | PseudoElement::CustomFunction { .. },
1551    )
1552  }
1553}
1554
1555impl<'i> PseudoElement<'i> {
1556  pub(crate) fn is_equivalent(&self, other: &PseudoElement<'i>) -> bool {
1557    use PseudoElement::*;
1558    match (self, other) {
1559      (Selection(_), Selection(_))
1560      | (Placeholder(_), Placeholder(_))
1561      | (Backdrop(_), Backdrop(_))
1562      | (FileSelectorButton(_), FileSelectorButton(_)) => true,
1563      (a, b) => a == b,
1564    }
1565  }
1566
1567  pub(crate) fn get_prefix(&self) -> VendorPrefix {
1568    use PseudoElement::*;
1569    match self {
1570      Selection(p) | Placeholder(p) | Backdrop(p) | FileSelectorButton(p) => *p,
1571      _ => VendorPrefix::empty(),
1572    }
1573  }
1574
1575  pub(crate) fn get_necessary_prefixes(&mut self, targets: Targets) -> VendorPrefix {
1576    use crate::prefixes::Feature;
1577    use PseudoElement::*;
1578    let (p, feature) = match self {
1579      Selection(p) => (p, Feature::PseudoElementSelection),
1580      Placeholder(p) => (p, Feature::PseudoElementPlaceholder),
1581      Backdrop(p) => (p, Feature::PseudoElementBackdrop),
1582      FileSelectorButton(p) => (p, Feature::PseudoElementFileSelectorButton),
1583      _ => return VendorPrefix::empty(),
1584    };
1585
1586    *p = targets.prefixes(*p, feature);
1587    *p
1588  }
1589}
1590
1591impl<'a, 'i> ToCss for SelectorList<'i> {
1592  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1593    dest.with_current_context(ContextAccess, |dest, context| {
1594      serialize_selector_list(self.0.iter(), dest, context, false)
1595    })
1596  }
1597}
1598
1599impl ToCss for Combinator {
1600  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1601    match *self {
1602      Combinator::Child => dest.delim('>', true),
1603      Combinator::Descendant => {
1604        dest.write_str(" ")?;
1605        Ok(())
1606      }
1607      Combinator::NextSibling => dest.delim('+', true),
1608      Combinator::LaterSibling => dest.delim('~', true),
1609      Combinator::Deep => {
1610        dest.write_str(" /deep/ ")?;
1611        Ok(())
1612      }
1613      Combinator::DeepDescendant => {
1614        dest.whitespace()?;
1615        dest.write_str(">>>")?;
1616        dest.whitespace()
1617      }
1618      Combinator::PseudoElement | Combinator::Part | Combinator::SlotAssignment => Ok(()),
1619    }
1620  }
1621}
1622
1623// Copied from the selectors crate and modified to override to_css implementation.
1624impl<'a, 'i> ToCss for Selector<'i> {
1625  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1626    dest.with_current_context(ContextAccess, |dest, context| {
1627      serialize_selector(self, dest, context, false)
1628    })
1629  }
1630}
1631
1632fn serialize_selector<'a, 'i, PrinterT: crate::printer::PrinterTrait>(
1633  selector: &Selector<'i>,
1634  dest: &mut PrinterT,
1635  context: Option<&StyleContext>,
1636  mut is_relative: bool,
1637) -> Result<(), PrinterError> {
1638  use rspack_lightningcss_selectors::parser::*;
1639  // Compound selectors invert the order of their contents, so we need to
1640  // undo that during serialization.
1641  //
1642  // This two-iterator strategy involves walking over the selector twice.
1643  // We could do something more clever, but selector serialization probably
1644  // isn't hot enough to justify it, and the stringification likely
1645  // dominates anyway.
1646  //
1647  // NB: A parse-order iterator is a Rev<>, which doesn't expose as_slice(),
1648  // which we need for |split|. So we split by combinators on a match-order
1649  // sequence and then reverse.
1650
1651  let mut combinators = selector.iter_raw_match_order().rev().filter_map(|x| x.as_combinator());
1652  let compound_selectors = selector.iter_raw_match_order().as_slice().split(|x| x.is_combinator()).rev();
1653  let should_compile_nesting = should_compile!(dest.targets().current, Nesting);
1654
1655  let mut first = true;
1656  let mut combinators_exhausted = false;
1657  for mut compound in compound_selectors {
1658    debug_assert!(!combinators_exhausted);
1659
1660    // Skip implicit :scope in relative selectors (e.g. :has(:scope > foo) -> :has(> foo))
1661    if is_relative && matches!(compound.get(0), Some(Component::Scope)) {
1662      if let Some(combinator) = combinators.next() {
1663        combinator.to_css(dest)?;
1664      }
1665      compound = &compound[1..];
1666      is_relative = false;
1667    }
1668
1669    // https://drafts.csswg.org/cssom/#serializing-selectors
1670    if compound.is_empty() {
1671      continue;
1672    }
1673
1674    let has_leading_nesting = first && matches!(compound[0], Component::Nesting);
1675    let first_index = if has_leading_nesting { 1 } else { 0 };
1676    first = false;
1677
1678    // 1. If there is only one simple selector in the compound selectors
1679    //    which is a universal selector, append the result of
1680    //    serializing the universal selector to s.
1681    //
1682    // Check if `!compound.empty()` first--this can happen if we have
1683    // something like `... > ::before`, because we store `>` and `::`
1684    // both as combinators internally.
1685    //
1686    // If we are in this case, after we have serialized the universal
1687    // selector, we skip Step 2 and continue with the algorithm.
1688    let (can_elide_namespace, first_non_namespace) = match compound.get(first_index) {
1689      Some(Component::ExplicitAnyNamespace)
1690      | Some(Component::ExplicitNoNamespace)
1691      | Some(Component::Namespace(..)) => (false, first_index + 1),
1692      Some(Component::DefaultNamespace(..)) => (true, first_index + 1),
1693      _ => (true, first_index),
1694    };
1695    let mut perform_step_2 = true;
1696    let next_combinator = combinators.next();
1697    if first_non_namespace == compound.len() - 1 {
1698      match (next_combinator, &compound[first_non_namespace]) {
1699        // We have to be careful here, because if there is a
1700        // pseudo element "combinator" there isn't really just
1701        // the one simple selector. Technically this compound
1702        // selector contains the pseudo element selector as well
1703        // -- Combinator::PseudoElement, just like
1704        // Combinator::SlotAssignment, don't exist in the
1705        // spec.
1706        (Some(Combinator::PseudoElement), _) | (Some(Combinator::SlotAssignment), _) => (),
1707        (_, &Component::ExplicitUniversalType) => {
1708          // Iterate over everything so we serialize the namespace
1709          // too.
1710          let mut iter = compound.iter();
1711          let swap_nesting = has_leading_nesting && should_compile_nesting;
1712          if swap_nesting {
1713            // Swap nesting and type selector (e.g. &div -> div&).
1714            iter.next();
1715          }
1716
1717          for simple in iter {
1718            serialize_component(simple, dest, context)?;
1719          }
1720
1721          if swap_nesting {
1722            serialize_nesting(dest, context, false)?;
1723          }
1724
1725          // Skip step 2, which is an "otherwise".
1726          perform_step_2 = false;
1727        }
1728        _ => (),
1729      }
1730    }
1731
1732    // 2. Otherwise, for each simple selector in the compound selectors
1733    //    that is not a universal selector of which the namespace prefix
1734    //    maps to a namespace that is not the default namespace
1735    //    serialize the simple selector and append the result to s.
1736    //
1737    // See https://github.com/w3c/csswg-drafts/issues/1606, which is
1738    // proposing to change this to match up with the behavior asserted
1739    // in cssom/serialize-namespaced-type-selectors.html, which the
1740    // following code tries to match.
1741    if perform_step_2 {
1742      let mut iter = compound.iter();
1743      if has_leading_nesting && should_compile_nesting && is_type_selector(compound.get(first_non_namespace)) {
1744        // Swap nesting and type selector (e.g. &div -> div&).
1745        // This ensures that the compiled selector is valid. e.g. (div.foo is valid, .foodiv is not).
1746        let nesting = iter.next().unwrap();
1747        let local = iter.next().unwrap();
1748        serialize_component(local, dest, context)?;
1749
1750        // Also check the next item in case of namespaces.
1751        if first_non_namespace > first_index {
1752          let local = iter.next().unwrap();
1753          serialize_component(local, dest, context)?;
1754        }
1755
1756        serialize_component(nesting, dest, context)?;
1757      } else if has_leading_nesting && should_compile_nesting {
1758        // Nesting selector may serialize differently if it is leading, due to type selectors.
1759        iter.next();
1760        serialize_nesting(dest, context, true)?;
1761      }
1762
1763      for simple in iter {
1764        if let Component::ExplicitUniversalType = *simple {
1765          // Can't have a namespace followed by a pseudo-element
1766          // selector followed by a universal selector in the same
1767          // compound selector, so we don't have to worry about the
1768          // real namespace being in a different `compound`.
1769          if can_elide_namespace {
1770            continue;
1771          }
1772        }
1773        serialize_component(simple, dest, context)?;
1774      }
1775    }
1776
1777    // 3. If this is not the last part of the chain of the selector
1778    //    append a single SPACE (U+0020), followed by the combinator
1779    //    ">", "+", "~", ">>", "||", as appropriate, followed by another
1780    //    single SPACE (U+0020) if the combinator was not whitespace, to
1781    //    s.
1782    match next_combinator {
1783      Some(c) => c.to_css(dest)?,
1784      None => combinators_exhausted = true,
1785    };
1786
1787    // 4. If this is the last part of the chain of the selector and
1788    //    there is a pseudo-element, append "::" followed by the name of
1789    //    the pseudo-element, to s.
1790    //
1791    // (we handle this above)
1792  }
1793
1794  Ok(())
1795}
1796
1797fn serialize_component<'a, 'i, PrinterT: crate::printer::PrinterTrait>(
1798  component: &Component,
1799  dest: &mut PrinterT,
1800  context: Option<&StyleContext>,
1801) -> Result<(), PrinterError> {
1802  match component {
1803    Component::Combinator(ref c) => c.to_css(dest),
1804    Component::AttributeInNoNamespace {
1805      ref local_name,
1806      operator,
1807      ref value,
1808      case_sensitivity,
1809      ..
1810    } => {
1811      dest.write_char('[')?;
1812      cssparser::ToCss::to_css(local_name, dest)?;
1813      cssparser::ToCss::to_css(operator, dest)?;
1814
1815      if dest.options().minify {
1816        // Serialize as both an identifier and a string and choose the shorter one.
1817        let mut id = String::new();
1818        serialize_identifier(&value, &mut id)?;
1819
1820        let s = value.to_css_string(Default::default())?;
1821
1822        if id.len() > 0 && id.len() < s.len() {
1823          dest.write_str(&id)?;
1824        } else {
1825          dest.write_str(&s)?;
1826        }
1827      } else {
1828        value.to_css(dest)?;
1829      }
1830
1831      match case_sensitivity {
1832        rspack_lightningcss_selectors::attr::ParsedCaseSensitivity::CaseSensitive
1833        | rspack_lightningcss_selectors::attr::ParsedCaseSensitivity::AsciiCaseInsensitiveIfInHtmlElementInHtmlDocument => {}
1834        rspack_lightningcss_selectors::attr::ParsedCaseSensitivity::AsciiCaseInsensitive => dest.write_str(" i")?,
1835        rspack_lightningcss_selectors::attr::ParsedCaseSensitivity::ExplicitCaseSensitive => dest.write_str(" s")?,
1836      }
1837      dest.write_char(']')?;
1838      Ok(())
1839    }
1840    Component::Is(ref list)
1841    | Component::Where(ref list)
1842    | Component::Negation(ref list)
1843    | Component::Any(_, ref list) => {
1844      match *component {
1845        Component::Where(..) => dest.write_str(":where(")?,
1846        Component::Is(ref selectors) => {
1847          // If there's only one simple selector, serialize it directly.
1848          if should_unwrap_is(selectors) {
1849            serialize_selector(selectors.first().unwrap(), dest, context, false)?;
1850            return Ok(());
1851          }
1852
1853          let vp = dest.vendor_prefix();
1854          if vp.intersects(VendorPrefix::WebKit | VendorPrefix::Moz) {
1855            dest.write_char(':')?;
1856            vp.to_css(dest)?;
1857            dest.write_str("any(")?;
1858          } else {
1859            dest.write_str(":is(")?;
1860          }
1861        }
1862        Component::Negation(_) => {
1863          dest.write_str(":not(")?;
1864        }
1865        Component::Any(prefix, ..) => {
1866          let vp = dest.vendor_prefix().or(prefix);
1867          if vp.intersects(VendorPrefix::WebKit | VendorPrefix::Moz) {
1868            dest.write_char(':')?;
1869            vp.to_css(dest)?;
1870            dest.write_str("any(")?;
1871          } else {
1872            dest.write_str(":is(")?;
1873          }
1874        }
1875        _ => unreachable!(),
1876      }
1877      serialize_selector_list(list.iter(), dest, context, false)?;
1878      dest.write_str(")")?;
1879      Ok(())
1880    }
1881    Component::Has(ref list) => {
1882      dest.write_str(":has(")?;
1883      serialize_selector_list(list.iter(), dest, context, true)?;
1884      dest.write_str(")")?;
1885      Ok(())
1886    }
1887    Component::NonTSPseudoClass(pseudo) => serialize_pseudo_class(pseudo, dest, context),
1888    Component::PseudoElement(pseudo) => serialize_pseudo_element(pseudo, dest, context),
1889    Component::Nesting => serialize_nesting(dest, context, false),
1890    Component::Class(ref class) => {
1891      dest.write_char('.')?;
1892      dest.write_ident(&class.0, true)
1893    }
1894    Component::ID(ref id) => {
1895      dest.write_char('#')?;
1896      dest.write_ident(&id.0, true)
1897    }
1898    Component::Host(selector) => {
1899      dest.write_str(":host")?;
1900      if let Some(ref selector) = *selector {
1901        dest.write_char('(')?;
1902        selector.to_css(dest)?;
1903        dest.write_char(')')?;
1904      }
1905      Ok(())
1906    }
1907    Component::Slotted(ref selector) => {
1908      dest.write_str("::slotted(")?;
1909      selector.to_css(dest)?;
1910      dest.write_char(')')?;
1911      Ok(())
1912    }
1913    Component::NthOf(ref nth_of_data) => {
1914      let nth_data = nth_of_data.nth_data();
1915      nth_data.write_start(dest, true)?;
1916      nth_data.write_affine(dest)?;
1917      dest.write_str(" of ")?;
1918      serialize_selector_list(nth_of_data.selectors().iter(), dest, context, true)?;
1919      dest.write_char(')')?;
1920      Ok(())
1921    }
1922    _ => {
1923      cssparser::ToCss::to_css(component, dest)?;
1924      Ok(())
1925    }
1926  }
1927}
1928
1929fn should_unwrap_is<'i>(selectors: &Box<[Selector<'i>]>) -> bool {
1930  if selectors.len() == 1 {
1931    let first = selectors.first().unwrap();
1932    if !has_type_selector(first) && is_simple(first) {
1933      return true;
1934    }
1935  }
1936
1937  false
1938}
1939
1940fn serialize_nesting<PrinterT: crate::printer::PrinterTrait>(
1941  dest: &mut PrinterT,
1942  context: Option<&StyleContext>,
1943  first: bool,
1944) -> Result<(), PrinterError> {
1945  if let Some(ctx) = context {
1946    // If there's only one simple selector, just serialize it directly.
1947    // Otherwise, use an :is() pseudo class.
1948    // Type selectors are only allowed at the start of a compound selector,
1949    // so use :is() if that is not the case.
1950    if ctx.selectors.0.len() == 1
1951      && (first || (!has_type_selector(&ctx.selectors.0[0]) && is_simple(&ctx.selectors.0[0])))
1952    {
1953      serialize_selector(ctx.selectors.0.first().unwrap(), dest, ctx.parent, false)
1954    } else {
1955      dest.write_str(":is(")?;
1956      serialize_selector_list(ctx.selectors.0.iter(), dest, ctx.parent, false)?;
1957      dest.write_char(')')?;
1958      Ok(())
1959    }
1960  } else {
1961    // If there is no context, we are at the root if nesting is supported. This is equivalent to :scope.
1962    // Otherwise, if nesting is supported, serialize the nesting selector directly.
1963    if should_compile!(dest.targets().current, Nesting) {
1964      dest.write_str(":scope")?;
1965      Ok(())
1966    } else {
1967      dest.write_char('&')?;
1968      Ok(())
1969    }
1970  }
1971}
1972
1973#[inline]
1974fn has_type_selector(selector: &Selector) -> bool {
1975  // For input:checked the component vector is
1976  // [input, :checked] so we have to check it using matching order.
1977  //
1978  // This both happens for input:checked and is(input:checked)
1979  let mut iter = selector.iter_raw_match_order();
1980  let first = iter.next();
1981
1982  if is_namespace(first) {
1983    is_type_selector(iter.next())
1984  } else {
1985    is_type_selector(first)
1986  }
1987}
1988
1989#[inline]
1990fn is_simple(selector: &Selector) -> bool {
1991  !selector.iter_raw_match_order().any(|component| component.is_combinator())
1992}
1993
1994#[inline]
1995fn is_type_selector(component: Option<&Component>) -> bool {
1996  matches!(
1997    component,
1998    Some(Component::LocalName(_)) | Some(Component::ExplicitUniversalType)
1999  )
2000}
2001
2002#[inline]
2003fn is_namespace(component: Option<&Component>) -> bool {
2004  matches!(
2005    component,
2006    Some(Component::ExplicitAnyNamespace)
2007      | Some(Component::ExplicitNoNamespace)
2008      | Some(Component::Namespace(..))
2009      | Some(Component::DefaultNamespace(_))
2010  )
2011}
2012
2013fn serialize_selector_list<'a, 'i: 'a, I, PrinterT: crate::printer::PrinterTrait>(
2014  iter: I,
2015  dest: &mut PrinterT,
2016  context: Option<&StyleContext>,
2017  is_relative: bool,
2018) -> Result<(), PrinterError>
2019where
2020  I: Iterator<Item = &'a Selector<'i>>,
2021{
2022  let mut first = true;
2023  for selector in iter {
2024    if !first {
2025      dest.delim(',', false)?;
2026    }
2027    first = false;
2028    serialize_selector(selector, dest, context, is_relative)?;
2029  }
2030  Ok(())
2031}
2032
2033pub(crate) fn is_compatible(selectors: &[Selector], targets: Targets) -> bool {
2034  for selector in selectors {
2035    let iter = selector.iter_raw_match_order();
2036    for component in iter {
2037      let feature = match component {
2038        Component::ID(_) | Component::Class(_) | Component::LocalName(_) => continue,
2039
2040        Component::ExplicitAnyNamespace
2041        | Component::ExplicitNoNamespace
2042        | Component::DefaultNamespace(_)
2043        | Component::Namespace(_, _) => Feature::Namespaces,
2044
2045        Component::ExplicitUniversalType => Feature::Selectors2,
2046
2047        Component::AttributeInNoNamespaceExists { .. } => Feature::Selectors2,
2048        Component::AttributeInNoNamespace {
2049          operator,
2050          case_sensitivity,
2051          ..
2052        } => {
2053          if *case_sensitivity != ParsedCaseSensitivity::CaseSensitive {
2054            Feature::CaseInsensitive
2055          } else {
2056            match operator {
2057              AttrSelectorOperator::Equal | AttrSelectorOperator::Includes | AttrSelectorOperator::DashMatch => {
2058                Feature::Selectors2
2059              }
2060              AttrSelectorOperator::Prefix | AttrSelectorOperator::Substring | AttrSelectorOperator::Suffix => {
2061                Feature::Selectors3
2062              }
2063            }
2064          }
2065        }
2066        Component::AttributeOther(attr) => match attr.operation {
2067          ParsedAttrSelectorOperation::Exists => Feature::Selectors2,
2068          ParsedAttrSelectorOperation::WithValue {
2069            operator,
2070            case_sensitivity,
2071            ..
2072          } => {
2073            if case_sensitivity != ParsedCaseSensitivity::CaseSensitive {
2074              Feature::CaseInsensitive
2075            } else {
2076              match operator {
2077                AttrSelectorOperator::Equal | AttrSelectorOperator::Includes | AttrSelectorOperator::DashMatch => {
2078                  Feature::Selectors2
2079                }
2080                AttrSelectorOperator::Prefix | AttrSelectorOperator::Substring | AttrSelectorOperator::Suffix => {
2081                  Feature::Selectors3
2082                }
2083              }
2084            }
2085          }
2086        },
2087
2088        Component::Empty | Component::Root => Feature::Selectors3,
2089        Component::Negation(selectors) => {
2090          // :not() selector list is not forgiving.
2091          if !targets.is_compatible(Feature::Selectors3) || !is_compatible(&*selectors, targets) {
2092            return false;
2093          }
2094          continue;
2095        }
2096
2097        Component::Nth(data) => match data.ty {
2098          NthType::Child if data.a == 0 && data.b == 1 => Feature::Selectors2,
2099          NthType::Col | NthType::LastCol => return false,
2100          _ => Feature::Selectors3,
2101        },
2102        Component::NthOf(n) => {
2103          if !targets.is_compatible(Feature::NthChildOf) || !is_compatible(n.selectors(), targets) {
2104            return false;
2105          }
2106          continue;
2107        }
2108
2109        // These support forgiving selector lists, so no need to check nested selectors.
2110        Component::Is(selectors) => {
2111          // ... except if we are going to unwrap them.
2112          if should_unwrap_is(selectors) && is_compatible(selectors, targets) {
2113            continue;
2114          }
2115
2116          Feature::IsSelector
2117        }
2118        Component::Where(_) | Component::Nesting => Feature::IsSelector,
2119        Component::Any(..) => return false,
2120        Component::Has(selectors) => {
2121          if !targets.is_compatible(Feature::HasSelector) || !is_compatible(&*selectors, targets) {
2122            return false;
2123          }
2124          continue;
2125        }
2126
2127        Component::Host(Some(selector)) | Component::Slotted(selector) => {
2128          // These arguments are not forgiving: an unsupported selector inside
2129          // the function invalidates the entire outer selector list as well.
2130          if !is_compatible(std::slice::from_ref(selector), targets) {
2131            return false;
2132          }
2133          Feature::Shadowdomv1
2134        }
2135        Component::Scope | Component::Host(None) => Feature::Shadowdomv1,
2136
2137        Component::Part(_) => Feature::PartPseudo,
2138
2139        Component::NonTSPseudoClass(pseudo) => {
2140          match pseudo {
2141            PseudoClass::Link
2142            | PseudoClass::Visited
2143            | PseudoClass::Active
2144            | PseudoClass::Hover
2145            | PseudoClass::Focus
2146            | PseudoClass::Lang { languages: _ } => Feature::Selectors2,
2147
2148            PseudoClass::Checked | PseudoClass::Disabled | PseudoClass::Enabled | PseudoClass::Target => {
2149              Feature::Selectors3
2150            }
2151
2152            PseudoClass::AnyLink(prefix) if *prefix == VendorPrefix::None => Feature::AnyLink,
2153            PseudoClass::Indeterminate => Feature::IndeterminatePseudo,
2154
2155            PseudoClass::Fullscreen(prefix) if *prefix == VendorPrefix::None => Feature::Fullscreen,
2156
2157            PseudoClass::FocusVisible => Feature::FocusVisible,
2158            PseudoClass::FocusWithin => Feature::FocusWithin,
2159            PseudoClass::Default => Feature::DefaultPseudo,
2160            PseudoClass::Dir { direction: _ } => Feature::DirSelector,
2161            PseudoClass::Optional => Feature::OptionalPseudo,
2162            PseudoClass::PlaceholderShown(prefix) if *prefix == VendorPrefix::None => Feature::PlaceholderShown,
2163
2164            PseudoClass::TargetCurrent => Feature::TargetCurrent,
2165            PseudoClass::TargetBefore | PseudoClass::TargetAfter => Feature::TargetBeforeAfter,
2166
2167            PseudoClass::ReadOnly(prefix) | PseudoClass::ReadWrite(prefix) if *prefix == VendorPrefix::None => {
2168              Feature::ReadOnlyWrite
2169            }
2170
2171            PseudoClass::Valid | PseudoClass::Invalid | PseudoClass::Required => Feature::FormValidation,
2172
2173            PseudoClass::InRange | PseudoClass::OutOfRange => Feature::InOutOfRange,
2174
2175            PseudoClass::Autofill(prefix) if *prefix == VendorPrefix::None => Feature::Autofill,
2176
2177            PseudoClass::State { .. } => Feature::StatePseudoClass,
2178
2179            // Experimental, no browser support.
2180            PseudoClass::Current
2181            | PseudoClass::Past
2182            | PseudoClass::Future
2183            | PseudoClass::Playing
2184            | PseudoClass::Paused
2185            | PseudoClass::Seeking
2186            | PseudoClass::Stalled
2187            | PseudoClass::Buffering
2188            | PseudoClass::Muted
2189            | PseudoClass::VolumeLocked
2190            | PseudoClass::TargetWithin
2191            | PseudoClass::LocalLink
2192            | PseudoClass::Blank
2193            | PseudoClass::UserInvalid
2194            | PseudoClass::UserValid
2195            | PseudoClass::Defined
2196            | PseudoClass::ActiveViewTransition
2197            | PseudoClass::ActiveViewTransitionType { .. } => return false,
2198
2199            PseudoClass::Custom { .. } | _ => return false,
2200          }
2201        }
2202
2203        Component::PseudoElement(pseudo) => match pseudo {
2204          PseudoElement::After | PseudoElement::Before => Feature::Gencontent,
2205          PseudoElement::FirstLine => Feature::FirstLine,
2206          PseudoElement::FirstLetter => Feature::FirstLetter,
2207          PseudoElement::DetailsContent => Feature::DetailsContent,
2208          PseudoElement::TargetText => Feature::TargetText,
2209          PseudoElement::SearchText => Feature::SearchText,
2210          PseudoElement::Selection(prefix) if *prefix == VendorPrefix::None => Feature::Selection,
2211          PseudoElement::Placeholder(prefix) if *prefix == VendorPrefix::None => Feature::Placeholder,
2212          PseudoElement::HighlightFunction { name: _ } => Feature::Highlight,
2213          PseudoElement::Marker => Feature::MarkerPseudo,
2214          PseudoElement::Backdrop(prefix) if *prefix == VendorPrefix::None => Feature::Dialog,
2215          PseudoElement::Cue => Feature::Cue,
2216          PseudoElement::CueFunction { selector } => {
2217            if selector.has_combinator()
2218              || selector.has_pseudo_element()
2219              || !is_compatible(std::slice::from_ref(selector), targets)
2220            {
2221              return false;
2222            }
2223            Feature::CueFunction
2224          }
2225          PseudoElement::ViewTransition
2226          | PseudoElement::ViewTransitionNew { .. }
2227          | PseudoElement::ViewTransitionOld { .. }
2228          | PseudoElement::ViewTransitionGroup { .. }
2229          | PseudoElement::ViewTransitionImagePair { .. } => Feature::ViewTransition,
2230          PseudoElement::PickerFunction { identifier: _ } => Feature::Picker,
2231          PseudoElement::PickerIcon => Feature::PickerIcon,
2232          PseudoElement::Checkmark => Feature::Checkmark,
2233          PseudoElement::GrammarError => Feature::GrammarError,
2234          PseudoElement::SpellingError => Feature::SpellingError,
2235          PseudoElement::Custom { name: _ } | _ => return false,
2236        },
2237
2238        Component::Combinator(combinator) => match combinator {
2239          Combinator::Child | Combinator::NextSibling => Feature::Selectors2,
2240          Combinator::LaterSibling => Feature::Selectors3,
2241          _ => continue,
2242        },
2243      };
2244
2245      if !targets.is_compatible(feature) {
2246        return false;
2247      }
2248    }
2249  }
2250
2251  true
2252}
2253
2254/// Returns whether two selector lists are equivalent, i.e. the same minus any vendor prefix differences.
2255pub(crate) fn is_equivalent<'i>(selectors: &[Selector<'i>], other: &[Selector<'i>]) -> bool {
2256  if selectors.len() != other.len() {
2257    return false;
2258  }
2259
2260  for (i, a) in selectors.iter().enumerate() {
2261    let b = &other[i];
2262    if a.len() != b.len() {
2263      return false;
2264    }
2265
2266    for (a, b) in a.iter_raw_match_order().zip(b.iter_raw_match_order()) {
2267      let is_equivalent = match (a, b) {
2268        (Component::NonTSPseudoClass(a_ps), Component::NonTSPseudoClass(b_ps)) => a_ps.is_equivalent(b_ps),
2269        (Component::PseudoElement(a_pe), Component::PseudoElement(b_pe)) => a_pe.is_equivalent(b_pe),
2270        (Component::Any(_, a), Component::Is(b))
2271        | (Component::Is(a), Component::Any(_, b))
2272        | (Component::Any(_, a), Component::Any(_, b))
2273        | (Component::Is(a), Component::Is(b)) => is_equivalent(&*a, &*b),
2274        (a, b) => a == b,
2275      };
2276
2277      if !is_equivalent {
2278        return false;
2279      }
2280    }
2281  }
2282
2283  true
2284}
2285
2286/// Returns the vendor prefix (if any) used in the given selector list.
2287/// If multiple vendor prefixes are seen, this is invalid, and an empty result is returned.
2288pub(crate) fn get_prefix(selectors: &SelectorList) -> VendorPrefix {
2289  let mut prefix = VendorPrefix::empty();
2290  for selector in &selectors.0 {
2291    for component in selector.iter_raw_match_order() {
2292      let p = match component {
2293        // Return none rather than empty for these so that we call downlevel_selectors.
2294        Component::NonTSPseudoClass(PseudoClass::Lang { .. })
2295        | Component::NonTSPseudoClass(PseudoClass::Dir { .. })
2296        | Component::Is(..)
2297        | Component::Where(..)
2298        | Component::Has(..)
2299        | Component::Negation(..) => VendorPrefix::None,
2300        Component::Any(prefix, _) => *prefix,
2301        Component::NonTSPseudoClass(pc) => pc.get_prefix(),
2302        Component::PseudoElement(pe) => pe.get_prefix(),
2303        _ => VendorPrefix::empty(),
2304      };
2305
2306      if !p.is_empty() {
2307        // Allow none to be mixed with a prefix.
2308        let prefix_without_none = prefix - VendorPrefix::None;
2309        if prefix_without_none.is_empty() || prefix_without_none == p {
2310          prefix |= p;
2311        } else {
2312          return VendorPrefix::empty();
2313        }
2314      }
2315    }
2316  }
2317
2318  prefix
2319}
2320
2321const RTL_LANGS: &[&str] = &[
2322  "ae", "ar", "arc", "bcc", "bqi", "ckb", "dv", "fa", "glk", "he", "ku", "mzn", "nqo", "pnb", "ps", "sd", "ug",
2323  "ur", "yi",
2324];
2325
2326/// Downlevels the given selectors to be compatible with the given browser targets.
2327/// Returns the necessary vendor prefixes.
2328pub(crate) fn downlevel_selectors(selectors: &mut [Selector], targets: Targets) -> VendorPrefix {
2329  let mut necessary_prefixes = VendorPrefix::empty();
2330  for selector in selectors {
2331    for component in selector.iter_mut_raw_match_order() {
2332      necessary_prefixes |= downlevel_component(component, targets);
2333    }
2334  }
2335
2336  necessary_prefixes
2337}
2338
2339fn downlevel_component<'i>(component: &mut Component<'i>, targets: Targets) -> VendorPrefix {
2340  match component {
2341    Component::NonTSPseudoClass(pc) => {
2342      match pc {
2343        PseudoClass::Dir { direction: dir } => {
2344          if should_compile!(targets, DirSelector) {
2345            *component = downlevel_dir(*dir, targets);
2346            downlevel_component(component, targets)
2347          } else {
2348            VendorPrefix::empty()
2349          }
2350        }
2351        PseudoClass::Lang { languages: langs } => {
2352          // :lang() with multiple languages is not supported everywhere.
2353          // compile this to :is(:lang(a), :lang(b)) etc.
2354          if langs.len() > 1 && should_compile!(targets, LangSelectorList) {
2355            *component = Component::Is(lang_list_to_selectors(&langs));
2356            downlevel_component(component, targets)
2357          } else {
2358            VendorPrefix::empty()
2359          }
2360        }
2361        _ => pc.get_necessary_prefixes(targets),
2362      }
2363    }
2364    Component::PseudoElement(pe) => pe.get_necessary_prefixes(targets),
2365    Component::Is(selectors) => {
2366      let mut necessary_prefixes = downlevel_selectors(&mut **selectors, targets);
2367
2368      // Convert :is to :-webkit-any/:-moz-any if needed.
2369      // All selectors must be simple, no combinators are supported.
2370      if should_compile!(targets, IsSelector)
2371        && !should_unwrap_is(selectors)
2372        && selectors.iter().all(|selector| !selector.has_combinator())
2373      {
2374        necessary_prefixes |= targets.prefixes(VendorPrefix::None, crate::prefixes::Feature::AnyPseudo)
2375      } else {
2376        necessary_prefixes |= VendorPrefix::None
2377      }
2378
2379      necessary_prefixes
2380    }
2381    Component::Negation(selectors) => {
2382      let mut necessary_prefixes = downlevel_selectors(&mut **selectors, targets);
2383
2384      // Downlevel :not(.a, .b) -> :not(:is(.a, .b)) if not list is unsupported.
2385      // We need to use :is() / :-webkit-any() rather than :not(.a):not(.b) to ensure the specificity is equivalent.
2386      // https://drafts.csswg.org/selectors/#specificity-rules
2387      if selectors.len() > 1 && should_compile!(targets, NotSelectorList) {
2388        *component =
2389          Component::Negation(vec![Selector::from(Component::Is(selectors.clone()))].into_boxed_slice());
2390
2391        if should_compile!(targets, IsSelector) {
2392          necessary_prefixes |= targets.prefixes(VendorPrefix::None, crate::prefixes::Feature::AnyPseudo)
2393        } else {
2394          necessary_prefixes |= VendorPrefix::None
2395        }
2396      }
2397
2398      necessary_prefixes
2399    }
2400    Component::Where(selectors) | Component::Any(_, selectors) | Component::Has(selectors) => {
2401      downlevel_selectors(&mut **selectors, targets)
2402    }
2403    _ => VendorPrefix::empty(),
2404  }
2405}
2406
2407fn lang_list_to_selectors<'i>(langs: &Vec<CowArcStr<'i>>) -> Box<[Selector<'i>]> {
2408  langs
2409    .iter()
2410    .map(|lang| {
2411      Selector::from(Component::NonTSPseudoClass(PseudoClass::Lang {
2412        languages: vec![lang.clone()],
2413      }))
2414    })
2415    .collect::<Vec<Selector>>()
2416    .into_boxed_slice()
2417}
2418
2419fn downlevel_dir<'i>(dir: Direction, targets: Targets) -> Component<'i> {
2420  // Convert :dir to :lang. If supported, use a list of languages in a single :lang,
2421  // otherwise, use :is/:not, which may be further downleveled to e.g. :-webkit-any.
2422  let langs = RTL_LANGS.iter().map(|lang| (*lang).into()).collect();
2423  if !should_compile!(targets, LangSelectorList) {
2424    let c = Component::NonTSPseudoClass(PseudoClass::Lang { languages: langs });
2425    if dir == Direction::Ltr {
2426      Component::Negation(vec![Selector::from(c)].into_boxed_slice())
2427    } else {
2428      c
2429    }
2430  } else {
2431    if dir == Direction::Ltr {
2432      Component::Negation(lang_list_to_selectors(&langs))
2433    } else {
2434      Component::Is(lang_list_to_selectors(&langs))
2435    }
2436  }
2437}
2438
2439/// Determines whether a selector list contains only unused selectors.
2440/// A selector is considered unused if it contains a class or id component that exists in the set of unused symbols.
2441pub(crate) fn is_unused(
2442  selectors: &mut std::slice::Iter<Selector>,
2443  unused_symbols: &HashSet<String>,
2444  parent_is_unused: bool,
2445) -> bool {
2446  if unused_symbols.is_empty() {
2447    return false;
2448  }
2449
2450  selectors.all(|selector| {
2451    for component in selector.iter_raw_match_order() {
2452      match component {
2453        Component::Class(name) | Component::ID(name) => {
2454          if unused_symbols.contains(&name.0.to_string()) {
2455            return true;
2456          }
2457        }
2458        Component::Is(is) | Component::Where(is) | Component::Any(_, is) => {
2459          if is_unused(&mut is.iter(), unused_symbols, parent_is_unused) {
2460            return true;
2461          }
2462        }
2463        Component::Nesting => {
2464          if parent_is_unused {
2465            return true;
2466          }
2467        }
2468        _ => {}
2469      }
2470    }
2471
2472    false
2473  })
2474}
2475
2476/// Returns whether the selector has any class or id components.
2477pub(crate) fn is_pure_css_modules_selector(selector: &Selector) -> bool {
2478  use rspack_lightningcss_selectors::parser::Component;
2479  selector.iter_raw_match_order().any(|c| match c {
2480    Component::Class(_) | Component::ID(_) => true,
2481    Component::Is(s) | Component::Where(s) | Component::Has(s) | Component::Any(_, s) | Component::Negation(s) => {
2482      s.iter().any(is_pure_css_modules_selector)
2483    }
2484    Component::NthOf(nth) => nth.selectors().iter().any(is_pure_css_modules_selector),
2485    Component::Slotted(s) => is_pure_css_modules_selector(&s),
2486    Component::Host(s) => s.as_ref().map(is_pure_css_modules_selector).unwrap_or(false),
2487    Component::NonTSPseudoClass(pc) => match pc {
2488      PseudoClass::Local { selector } => is_pure_css_modules_selector(&*selector),
2489      _ => false,
2490    },
2491    _ => false,
2492  })
2493}
2494
2495#[cfg(feature = "visitor")]
2496#[cfg_attr(docsrs, doc(cfg(feature = "visitor")))]
2497impl<'i, T: Visit<'i, T, V>, V: ?Sized + Visitor<'i, T>> Visit<'i, T, V> for SelectorList<'i> {
2498  const CHILD_TYPES: VisitTypes = VisitTypes::SELECTORS;
2499
2500  fn visit(&mut self, visitor: &mut V) -> Result<(), V::Error> {
2501    if visitor.visit_types().contains(VisitTypes::SELECTORS) {
2502      visitor.visit_selector_list(self)
2503    } else {
2504      self.visit_children(visitor)
2505    }
2506  }
2507
2508  fn visit_children(&mut self, visitor: &mut V) -> Result<(), V::Error> {
2509    self.0.iter_mut().try_for_each(|selector| Visit::visit(selector, visitor))
2510  }
2511}
2512
2513#[cfg(feature = "visitor")]
2514#[cfg_attr(docsrs, doc(cfg(feature = "visitor")))]
2515impl<'i, T: Visit<'i, T, V>, V: ?Sized + Visitor<'i, T>> Visit<'i, T, V> for Selector<'i> {
2516  const CHILD_TYPES: VisitTypes = VisitTypes::SELECTORS;
2517
2518  fn visit(&mut self, visitor: &mut V) -> Result<(), V::Error> {
2519    visitor.visit_selector(self)
2520  }
2521
2522  fn visit_children(&mut self, _visitor: &mut V) -> Result<(), V::Error> {
2523    Ok(())
2524  }
2525}
2526
2527impl<'i> ParseWithOptions<'i> for Selector<'i> {
2528  fn parse_with_options<'t>(
2529    input: &mut Parser<'i, 't>,
2530    options: &ParserOptions<'i>,
2531  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
2532    Selector::parse(
2533      &SelectorParser {
2534        is_nesting_allowed: true,
2535        options: &options,
2536      },
2537      input,
2538    )
2539  }
2540}
2541
2542impl<'i> ParseWithOptions<'i> for SelectorList<'i> {
2543  fn parse_with_options<'t>(
2544    input: &mut Parser<'i, 't>,
2545    options: &ParserOptions<'i>,
2546  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
2547    SelectorList::parse(
2548      &SelectorParser {
2549        is_nesting_allowed: true,
2550        options: &options,
2551      },
2552      input,
2553      rspack_lightningcss_selectors::parser::ParseErrorRecovery::DiscardList,
2554      rspack_lightningcss_selectors::parser::NestingRequirement::None,
2555    )
2556  }
2557}