1use crate::compat::Feature;
4use crate::error::{ParserError, PrinterError, SelectorError};
5use crate::parser::ParserFlags;
6use crate::printer::Printer;
7use crate::properties::custom::TokenList;
8use crate::rules::{detach_style_context, 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 use rspack_lightningcss_static_self::IntoOwned;
51 fn _assert<'any, T: IntoOwned<'any>>() {}
52
53 _assert::<SelectorList>();
54}
55
56use private::Selectors;
57
58pub type SelectorList<'i> = rspack_lightningcss_selectors::SelectorList<'i, Selectors>;
60pub type Selector<'i> = rspack_lightningcss_selectors::parser::Selector<'i, Selectors>;
62pub type Component<'i> = rspack_lightningcss_selectors::parser::Component<'i, Selectors>;
64
65pub(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 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
87pub 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 "hover" => Hover,
130 "active" => Active,
131 "focus" => Focus,
132 "focus-visible" => FocusVisible,
133 "focus-within" => FocusWithin,
134
135 "current" => Current,
137 "past" => Past,
138 "future" => Future,
139
140 "playing" => Playing,
142 "paused" => Paused,
143 "seeking" => Seeking,
144 "buffering" => Buffering,
145 "stalled" => Stalled,
146 "muted" => Muted,
147 "volume-locked" => VolumeLocked,
148
149 "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 "open" => Open,
157 "closed" => Closed,
158 "modal" => Modal,
159 "picture-in-picture" => PictureInPicture,
160
161 "popover-open" => PopoverOpen,
163
164 "defined" => Defined,
166
167 "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 "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 "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 "autofill" => Autofill(VendorPrefix::None),
208 "-webkit-autofill" => Autofill(VendorPrefix::WebKit),
209 "-o-autofill" => Autofill(VendorPrefix::O),
210
211 "active-view-transition" => ActiveViewTransition,
213
214 "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 "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 #[derive(Eq, Hash)]
418 pub enum Direction {
419 Ltr,
421 Rtl,
423 }
424}
425
426#[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 Lang {
439 #[cfg_attr(feature = "serde", serde(borrow))]
441 languages: Vec<CowArcStr<'i>>,
442 },
443 Dir {
445 direction: Direction,
447 },
448
449 Hover,
452 Active,
454 Focus,
456 FocusVisible,
458 FocusWithin,
460
461 Current,
464 Past,
466 Future,
468
469 Playing,
472 Paused,
474 Seeking,
476 Buffering,
478 Stalled,
480 Muted,
482 VolumeLocked,
484
485 #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
487 Fullscreen(VendorPrefix),
488
489 Open,
492 Closed,
494 Modal,
496 PictureInPicture,
498
499 PopoverOpen,
502
503 Defined,
505
506 #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
509 AnyLink(VendorPrefix),
510 Link,
512 LocalLink,
514 Target,
516
517 TargetCurrent,
519 TargetBefore,
521 TargetAfter,
523 TargetWithin,
525 Visited,
527
528 Enabled,
531 Disabled,
533 #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
535 ReadOnly(VendorPrefix),
536 #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
538 ReadWrite(VendorPrefix),
539 #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
541 PlaceholderShown(VendorPrefix),
542 Default,
544 Checked,
546 Indeterminate,
548 Blank,
550 Valid,
552 Invalid,
554 InRange,
556 OutOfRange,
558 Required,
560 Optional,
562 UserValid,
564 UserInvalid,
566
567 #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
569 Autofill(VendorPrefix),
570
571 ActiveViewTransition,
573 ActiveViewTransitionType {
575 #[cfg_attr(feature = "serde", serde(rename = "type"))]
577 kind: SmallVec<[CustomIdent<'i>; 1]>,
578 },
579
580 State {
582 state: CustomIdent<'i>,
584 },
585
586 Local {
589 selector: Box<Selector<'i>>,
591 },
592 Global {
594 selector: Box<Selector<'i>>,
596 },
597
598 #[cfg_attr(
601 feature = "serde",
602 serde(rename = "webkit-scrollbar", with = "ValueWrapper::<WebKitScrollbarPseudoClass>")
603 )]
604 WebKitScrollbar(WebKitScrollbarPseudoClass),
605 Custom {
607 name: CowArcStr<'i>,
609 },
610 CustomFunction {
612 name: CowArcStr<'i>,
614 arguments: TokenList<'i>,
616 },
617}
618
619#[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,
631 Vertical,
633 Decrement,
635 Increment,
637 Start,
639 End,
641 DoubleButton,
643 SingleButton,
645 NoButton,
647 CornerPresent,
649 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 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 let vp = if !dest.state().vendor_prefix.is_empty() {
741 (dest.state().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 let class = dest
754 .options()
755 .pseudo_classes
756 .as_ref()
757 .and_then(|pseudo_classes| pseudo_classes.$key)
758 .map(|class| unsafe { std::mem::transmute::<&str, &'static str>(class) });
759
760 if let Some(class) = class {
761 dest.write_char('.')?;
762 dest.write_ident(class, true)
763 } else {
764 dest.write_str($s)?;
765 Ok(())
766 }
767 }};
768 }
769
770 match pseudo_class {
771 Hover => pseudo!(hover, ":hover"),
773 Active => pseudo!(active, ":active"),
774 Focus => pseudo!(focus, ":focus"),
775 FocusVisible => pseudo!(focus_visible, ":focus-visible"),
776 FocusWithin => pseudo!(focus_within, ":focus-within"),
777
778 Current => {
780 dest.write_str(":current")?;
781 Ok(())
782 }
783 Past => {
784 dest.write_str(":past")?;
785 Ok(())
786 }
787 Future => {
788 dest.write_str(":future")?;
789 Ok(())
790 }
791
792 Playing => {
794 dest.write_str(":playing")?;
795 Ok(())
796 }
797 Paused => {
798 dest.write_str(":paused")?;
799 Ok(())
800 }
801 Seeking => {
802 dest.write_str(":seeking")?;
803 Ok(())
804 }
805 Buffering => {
806 dest.write_str(":buffering")?;
807 Ok(())
808 }
809 Stalled => {
810 dest.write_str(":stalled")?;
811 Ok(())
812 }
813 Muted => {
814 dest.write_str(":muted")?;
815 Ok(())
816 }
817 VolumeLocked => {
818 dest.write_str(":volume-locked")?;
819 Ok(())
820 }
821
822 Fullscreen(prefix) => {
824 dest.write_char(':')?;
825 let vp = if !dest.state().vendor_prefix.is_empty() {
826 (dest.state().vendor_prefix & *prefix).or_none()
827 } else {
828 *prefix
829 };
830 vp.to_css(dest)?;
831 if vp == VendorPrefix::WebKit || vp == VendorPrefix::Moz {
832 dest.write_str("full-screen")?;
833 Ok(())
834 } else {
835 dest.write_str("fullscreen")?;
836 Ok(())
837 }
838 }
839
840 Open => {
842 dest.write_str(":open")?;
843 Ok(())
844 }
845 Closed => {
846 dest.write_str(":closed")?;
847 Ok(())
848 }
849 Modal => {
850 dest.write_str(":modal")?;
851 Ok(())
852 }
853 PictureInPicture => {
854 dest.write_str(":picture-in-picture")?;
855 Ok(())
856 }
857
858 PopoverOpen => {
860 dest.write_str(":popover-open")?;
861 Ok(())
862 }
863
864 Defined => {
866 dest.write_str(":defined")?;
867 Ok(())
868 }
869
870 AnyLink(prefix) => write_prefixed!(prefix, "any-link"),
872 Link => {
873 dest.write_str(":link")?;
874 Ok(())
875 }
876 LocalLink => {
877 dest.write_str(":local-link")?;
878 Ok(())
879 }
880 Target => {
881 dest.write_str(":target")?;
882 Ok(())
883 }
884 TargetWithin => {
885 dest.write_str(":target-within")?;
886 Ok(())
887 }
888
889 TargetCurrent => {
891 dest.write_str(":target-current")?;
892 Ok(())
893 }
894 TargetBefore => {
895 dest.write_str(":target-before")?;
896 Ok(())
897 }
898 TargetAfter => {
899 dest.write_str(":target-after")?;
900 Ok(())
901 }
902
903 Visited => {
904 dest.write_str(":visited")?;
905 Ok(())
906 }
907
908 Enabled => {
910 dest.write_str(":enabled")?;
911 Ok(())
912 }
913 Disabled => {
914 dest.write_str(":disabled")?;
915 Ok(())
916 }
917 ReadOnly(prefix) => write_prefixed!(prefix, "read-only"),
918 ReadWrite(prefix) => write_prefixed!(prefix, "read-write"),
919 PlaceholderShown(prefix) => write_prefixed!(prefix, "placeholder-shown"),
920 Default => {
921 dest.write_str(":default")?;
922 Ok(())
923 }
924 Checked => {
925 dest.write_str(":checked")?;
926 Ok(())
927 }
928 Indeterminate => {
929 dest.write_str(":indeterminate")?;
930 Ok(())
931 }
932 Blank => {
933 dest.write_str(":blank")?;
934 Ok(())
935 }
936 Valid => {
937 dest.write_str(":valid")?;
938 Ok(())
939 }
940 Invalid => {
941 dest.write_str(":invalid")?;
942 Ok(())
943 }
944 InRange => {
945 dest.write_str(":in-range")?;
946 Ok(())
947 }
948 OutOfRange => {
949 dest.write_str(":out-of-range")?;
950 Ok(())
951 }
952 Required => {
953 dest.write_str(":required")?;
954 Ok(())
955 }
956 Optional => {
957 dest.write_str(":optional")?;
958 Ok(())
959 }
960 UserValid => {
961 dest.write_str(":user-valid")?;
962 Ok(())
963 }
964 UserInvalid => {
965 dest.write_str(":user-invalid")?;
966 Ok(())
967 }
968
969 Autofill(prefix) => write_prefixed!(prefix, "autofill"),
971
972 ActiveViewTransition => {
973 dest.write_str(":active-view-transition")?;
974 Ok(())
975 }
976 ActiveViewTransitionType { kind } => {
977 dest.write_str(":active-view-transition-type(")?;
978 kind.to_css(dest)?;
979 dest.write_char(')')?;
980 Ok(())
981 }
982
983 Local { selector } => serialize_selector(selector, dest, context, false),
984 Global { selector } => dest.without_css_module(|dest| serialize_selector(selector, dest, context, false)),
985
986 WebKitScrollbar(s) => {
988 use WebKitScrollbarPseudoClass::*;
989 dest.write_str(match s {
990 Horizontal => ":horizontal",
991 Vertical => ":vertical",
992 Decrement => ":decrement",
993 Increment => ":increment",
994 Start => ":start",
995 End => ":end",
996 DoubleButton => ":double-button",
997 SingleButton => ":single-button",
998 NoButton => ":no-button",
999 CornerPresent => ":corner-present",
1000 WindowInactive => ":window-inactive",
1001 })?;
1002 Ok(())
1003 }
1004
1005 Lang { languages: _ } | Dir { direction: _ } | State { .. } => unreachable!(),
1006 Custom { name } => {
1007 dest.write_char(':')?;
1008 dest.write_str(&name)?;
1009 return Ok(());
1010 }
1011 CustomFunction { name, arguments: args } => {
1012 dest.write_char(':')?;
1013 dest.write_str(name)?;
1014 dest.write_char('(')?;
1015 args.to_css_raw(dest)?;
1016 dest.write_char(')')?;
1017 Ok(())
1018 }
1019 }
1020}
1021
1022impl<'i> PseudoClass<'i> {
1023 pub(crate) fn is_equivalent(&self, other: &PseudoClass<'i>) -> bool {
1024 use PseudoClass::*;
1025 match (self, other) {
1026 (Fullscreen(_), Fullscreen(_))
1027 | (AnyLink(_), AnyLink(_))
1028 | (ReadOnly(_), ReadOnly(_))
1029 | (ReadWrite(_), ReadWrite(_))
1030 | (PlaceholderShown(_), PlaceholderShown(_))
1031 | (Autofill(_), Autofill(_)) => true,
1032 (a, b) => a == b,
1033 }
1034 }
1035
1036 pub(crate) fn get_prefix(&self) -> VendorPrefix {
1037 use PseudoClass::*;
1038 match self {
1039 Fullscreen(p) | AnyLink(p) | ReadOnly(p) | ReadWrite(p) | PlaceholderShown(p) | Autofill(p) => *p,
1040 _ => VendorPrefix::empty(),
1041 }
1042 }
1043
1044 pub(crate) fn get_necessary_prefixes(&mut self, targets: Targets) -> VendorPrefix {
1045 use crate::prefixes::Feature;
1046 use PseudoClass::*;
1047 let (p, feature) = match self {
1048 Fullscreen(p) => (p, Feature::PseudoClassFullscreen),
1049 AnyLink(p) => (p, Feature::PseudoClassAnyLink),
1050 ReadOnly(p) => (p, Feature::PseudoClassReadOnly),
1051 ReadWrite(p) => (p, Feature::PseudoClassReadWrite),
1052 PlaceholderShown(p) => (p, Feature::PseudoClassPlaceholderShown),
1053 Autofill(p) => (p, Feature::PseudoClassAutofill),
1054 _ => return VendorPrefix::empty(),
1055 };
1056
1057 *p = targets.prefixes(*p, feature);
1058 *p
1059 }
1060}
1061
1062#[derive(PartialEq, Eq, Hash, Clone, Debug)]
1064#[cfg_attr(
1065 feature = "serde",
1066 derive(serde::Serialize, serde::Deserialize),
1067 serde(tag = "kind", rename_all = "kebab-case")
1068)]
1069#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1070#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1071pub enum PseudoElement<'i> {
1072 After,
1074 Before,
1076 FirstLine,
1078 FirstLetter,
1080 DetailsContent,
1082 TargetText,
1084 SearchText,
1086 #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
1088 Selection(VendorPrefix),
1089 #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
1091 Placeholder(VendorPrefix),
1092 HighlightFunction {
1094 name: CustomIdent<'i>,
1096 },
1097 Marker,
1099 #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
1101 Backdrop(VendorPrefix),
1102 #[cfg_attr(feature = "serde", serde(with = "PrefixWrapper"))]
1104 FileSelectorButton(VendorPrefix),
1105 #[cfg_attr(
1107 feature = "serde",
1108 serde(rename = "webkit-scrollbar", with = "ValueWrapper::<WebKitScrollbarPseudoElement>")
1109 )]
1110 WebKitScrollbar(WebKitScrollbarPseudoElement),
1111 Cue,
1113 CueRegion,
1115 CueFunction {
1117 selector: Box<Selector<'i>>,
1119 },
1120 CueRegionFunction {
1122 selector: Box<Selector<'i>>,
1124 },
1125 ViewTransition,
1127 #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
1129 ViewTransitionGroup {
1130 part: ViewTransitionPartSelector<'i>,
1132 },
1133 #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
1135 ViewTransitionImagePair {
1136 part: ViewTransitionPartSelector<'i>,
1138 },
1139 #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
1141 ViewTransitionOld {
1142 part: ViewTransitionPartSelector<'i>,
1144 },
1145 #[cfg_attr(feature = "serde", serde(rename_all = "camelCase"))]
1147 ViewTransitionNew {
1148 part: ViewTransitionPartSelector<'i>,
1150 },
1151 PickerFunction {
1153 identifier: Ident<'i>,
1155 },
1156 PickerIcon,
1158 Checkmark,
1160 GrammarError,
1162 SpellingError,
1164 Custom {
1166 #[cfg_attr(feature = "serde", serde(borrow))]
1168 name: CowArcStr<'i>,
1169 },
1170 CustomFunction {
1172 name: CowArcStr<'i>,
1174 arguments: TokenList<'i>,
1176 },
1177}
1178
1179#[derive(PartialEq, Eq, Clone, Debug, Hash)]
1181#[cfg_attr(
1182 feature = "serde",
1183 derive(serde::Serialize, serde::Deserialize),
1184 serde(rename_all = "kebab-case")
1185)]
1186#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1187#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1188pub enum WebKitScrollbarPseudoElement {
1189 Scrollbar,
1191 Button,
1193 Track,
1195 TrackPiece,
1197 Thumb,
1199 Corner,
1201 Resizer,
1203}
1204
1205#[derive(PartialEq, Eq, Clone, Debug, Hash)]
1207#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1208#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1209pub enum ViewTransitionPartName<'i> {
1210 #[cfg_attr(feature = "serde", serde(rename = "*"))]
1212 All,
1213 #[cfg_attr(feature = "serde", serde(borrow, untagged))]
1215 Name(CustomIdent<'i>),
1216}
1217
1218#[cfg(feature = "jsonschema")]
1219#[cfg_attr(docsrs, doc(cfg(feature = "jsonschema")))]
1220impl<'a> schemars::JsonSchema for ViewTransitionPartName<'a> {
1221 fn is_referenceable() -> bool {
1222 true
1223 }
1224
1225 fn json_schema(gen: &mut schemars::gen::SchemaGenerator) -> schemars::schema::Schema {
1226 str::json_schema(gen)
1227 }
1228
1229 fn schema_name() -> String {
1230 "ViewTransitionPartName".into()
1231 }
1232}
1233
1234impl<'i> Parse<'i> for ViewTransitionPartName<'i> {
1235 fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1236 if input.try_parse(|input| input.expect_delim('*')).is_ok() {
1237 return Ok(ViewTransitionPartName::All);
1238 }
1239
1240 Ok(ViewTransitionPartName::Name(CustomIdent::parse(input)?))
1241 }
1242}
1243
1244impl<'i> ToCss for ViewTransitionPartName<'i> {
1245 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1246 match self {
1247 ViewTransitionPartName::All => {
1248 dest.write_char('*')?;
1249 Ok(())
1250 }
1251 ViewTransitionPartName::Name(name) => name.to_css(dest),
1252 }
1253 }
1254}
1255
1256#[derive(PartialEq, Eq, Clone, Debug, Hash)]
1258#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1259#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1260#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1261pub struct ViewTransitionPartSelector<'i> {
1262 #[cfg_attr(feature = "serde", serde(borrow))]
1264 name: Option<ViewTransitionPartName<'i>>,
1265 classes: Vec<CustomIdent<'i>>,
1267}
1268
1269impl<'i> Parse<'i> for ViewTransitionPartSelector<'i> {
1270 fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1271 input.skip_whitespace();
1272 let name = input.try_parse(ViewTransitionPartName::parse).ok();
1273 let mut classes = Vec::new();
1274 while let Ok(token) = input.next_including_whitespace() {
1275 if matches!(token, Token::Delim('.')) {
1276 match input.next_including_whitespace() {
1277 Ok(Token::Ident(id)) => classes.push(CustomIdent(id.into())),
1278 _ => return Err(input.new_custom_error(ParserError::SelectorError(SelectorError::InvalidState))),
1279 }
1280 } else {
1281 break;
1282 }
1283 }
1284
1285 if !input.is_exhausted() || (name.is_none() && classes.is_empty()) {
1286 return Err(input.new_custom_error(ParserError::SelectorError(SelectorError::InvalidState)));
1287 }
1288
1289 Ok(ViewTransitionPartSelector { name, classes })
1290 }
1291}
1292
1293impl<'i> ToCss for ViewTransitionPartSelector<'i> {
1294 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1295 if let Some(name) = &self.name {
1296 name.to_css(dest)?;
1297 }
1298 for class in &self.classes {
1299 dest.write_char('.')?;
1300 class.to_css(dest)?;
1301 }
1302 Ok(())
1303 }
1304}
1305
1306impl<'i> cssparser::ToCss for PseudoElement<'i> {
1307 fn to_css<W>(&self, dest: &mut W) -> std::fmt::Result
1308 where
1309 W: fmt::Write,
1310 {
1311 let mut s = String::new();
1312 let mut printer = Printer::new(&mut s, PrinterOptions::default());
1313 serialize_pseudo_element(self, &mut printer, None).map_err(|_| std::fmt::Error)?;
1314 write!(dest, "{}", s)
1315 }
1316}
1317
1318fn serialize_pseudo_element<'a, 'i, PrinterT: crate::printer::PrinterTrait>(
1319 pseudo_element: &PseudoElement,
1320 dest: &mut PrinterT,
1321 context: Option<&StyleContext>,
1322) -> Result<(), PrinterError> {
1323 use PseudoElement::*;
1324
1325 macro_rules! write_prefix {
1326 ($prefix: ident) => {{
1327 dest.write_str("::")?;
1328 let vp = if !dest.state().vendor_prefix.is_empty() {
1330 (dest.state().vendor_prefix & *$prefix).or_none()
1331 } else {
1332 *$prefix
1333 };
1334 vp.to_css(dest)?;
1335 vp
1336 }};
1337 }
1338
1339 macro_rules! write_prefixed {
1340 ($prefix: ident, $val: expr) => {{
1341 write_prefix!($prefix);
1342 dest.write_str($val)?;
1343 Ok(())
1344 }};
1345 }
1346
1347 match pseudo_element {
1348 After => {
1352 dest.write_str(":after")?;
1353 Ok(())
1354 }
1355 Before => {
1356 dest.write_str(":before")?;
1357 Ok(())
1358 }
1359 FirstLine => {
1360 dest.write_str(":first-line")?;
1361 Ok(())
1362 }
1363 FirstLetter => {
1364 dest.write_str(":first-letter")?;
1365 Ok(())
1366 }
1367 DetailsContent => {
1368 dest.write_str("::details-content")?;
1369 Ok(())
1370 }
1371 TargetText => {
1372 dest.write_str("::target-text")?;
1373 Ok(())
1374 }
1375 SearchText => {
1376 dest.write_str("::search-text")?;
1377 Ok(())
1378 }
1379 HighlightFunction { name } => {
1380 dest.write_str("::highlight(")?;
1381 name.to_css(dest)?;
1382 dest.write_char(')')?;
1383 Ok(())
1384 }
1385 Marker => {
1386 dest.write_str("::marker")?;
1387 Ok(())
1388 }
1389 Selection(prefix) => write_prefixed!(prefix, "selection"),
1390 Cue => {
1391 dest.write_str("::cue")?;
1392 Ok(())
1393 }
1394 CueRegion => {
1395 dest.write_str("::cue-region")?;
1396 Ok(())
1397 }
1398 CueFunction { selector } => {
1399 dest.write_str("::cue(")?;
1400 serialize_selector(selector, dest, context, false)?;
1401 dest.write_char(')')?;
1402 Ok(())
1403 }
1404 CueRegionFunction { selector } => {
1405 dest.write_str("::cue-region(")?;
1406 serialize_selector(selector, dest, context, false)?;
1407 dest.write_char(')')?;
1408 Ok(())
1409 }
1410 Placeholder(prefix) => {
1411 let vp = write_prefix!(prefix);
1412 if vp == VendorPrefix::WebKit || vp == VendorPrefix::Ms {
1413 dest.write_str("input-placeholder")?;
1414 Ok(())
1415 } else {
1416 dest.write_str("placeholder")?;
1417 Ok(())
1418 }
1419 }
1420 Backdrop(prefix) => write_prefixed!(prefix, "backdrop"),
1421 FileSelectorButton(prefix) => {
1422 let vp = write_prefix!(prefix);
1423 if vp == VendorPrefix::WebKit {
1424 dest.write_str("file-upload-button")?;
1425 Ok(())
1426 } else if vp == VendorPrefix::Ms {
1427 dest.write_str("browse")?;
1428 Ok(())
1429 } else {
1430 dest.write_str("file-selector-button")?;
1431 Ok(())
1432 }
1433 }
1434 WebKitScrollbar(s) => {
1435 use WebKitScrollbarPseudoElement::*;
1436 dest.write_str(match s {
1437 Scrollbar => "::-webkit-scrollbar",
1438 Button => "::-webkit-scrollbar-button",
1439 Track => "::-webkit-scrollbar-track",
1440 TrackPiece => "::-webkit-scrollbar-track-piece",
1441 Thumb => "::-webkit-scrollbar-thumb",
1442 Corner => "::-webkit-scrollbar-corner",
1443 Resizer => "::-webkit-resizer",
1444 })?;
1445 Ok(())
1446 }
1447 ViewTransition => {
1448 dest.write_str("::view-transition")?;
1449 Ok(())
1450 }
1451 ViewTransitionGroup { part } => {
1452 dest.write_str("::view-transition-group(")?;
1453 part.to_css(dest)?;
1454 dest.write_char(')')?;
1455 Ok(())
1456 }
1457 ViewTransitionImagePair { part } => {
1458 dest.write_str("::view-transition-image-pair(")?;
1459 part.to_css(dest)?;
1460 dest.write_char(')')?;
1461 Ok(())
1462 }
1463 ViewTransitionOld { part } => {
1464 dest.write_str("::view-transition-old(")?;
1465 part.to_css(dest)?;
1466 dest.write_char(')')?;
1467 Ok(())
1468 }
1469 ViewTransitionNew { part } => {
1470 dest.write_str("::view-transition-new(")?;
1471 part.to_css(dest)?;
1472 dest.write_char(')')?;
1473 Ok(())
1474 }
1475 PickerFunction { identifier } => {
1476 dest.write_str("::picker(")?;
1477 identifier.to_css(dest)?;
1478 dest.write_char(')')?;
1479 Ok(())
1480 }
1481 PickerIcon => {
1482 dest.write_str("::picker-icon")?;
1483 Ok(())
1484 }
1485 Checkmark => {
1486 dest.write_str("::checkmark")?;
1487 Ok(())
1488 }
1489 GrammarError => {
1490 dest.write_str("::grammar-error")?;
1491 Ok(())
1492 }
1493 SpellingError => {
1494 dest.write_str("::spelling-error")?;
1495 Ok(())
1496 }
1497 Custom { name: val } => {
1498 dest.write_str("::")?;
1499 dest.write_str(val)?;
1500 return Ok(());
1501 }
1502 CustomFunction { name, arguments: args } => {
1503 dest.write_str("::")?;
1504 dest.write_str(name)?;
1505 dest.write_char('(')?;
1506 args.to_css_raw(dest)?;
1507 dest.write_char(')')?;
1508 Ok(())
1509 }
1510 }
1511}
1512
1513impl<'i> rspack_lightningcss_selectors::parser::PseudoElement<'i> for PseudoElement<'i> {
1514 type Impl = Selectors;
1515
1516 fn accepts_state_pseudo_classes(&self) -> bool {
1517 true
1519 }
1520
1521 fn valid_after_slotted(&self) -> bool {
1522 matches!(
1526 *self,
1527 PseudoElement::Before
1528 | PseudoElement::After
1529 | PseudoElement::Marker
1530 | PseudoElement::Placeholder(_)
1531 | PseudoElement::FileSelectorButton(_)
1532 )
1533 }
1534
1535 fn is_webkit_scrollbar(&self) -> bool {
1536 matches!(*self, PseudoElement::WebKitScrollbar(..))
1537 }
1538
1539 fn is_view_transition(&self) -> bool {
1540 matches!(
1541 *self,
1542 PseudoElement::ViewTransitionGroup { .. }
1543 | PseudoElement::ViewTransitionImagePair { .. }
1544 | PseudoElement::ViewTransitionNew { .. }
1545 | PseudoElement::ViewTransitionOld { .. }
1546 )
1547 }
1548
1549 fn is_unknown(&self) -> bool {
1550 matches!(
1551 *self,
1552 PseudoElement::Custom { .. } | PseudoElement::CustomFunction { .. },
1553 )
1554 }
1555}
1556
1557impl<'i> PseudoElement<'i> {
1558 pub(crate) fn is_equivalent(&self, other: &PseudoElement<'i>) -> bool {
1559 use PseudoElement::*;
1560 match (self, other) {
1561 (Selection(_), Selection(_))
1562 | (Placeholder(_), Placeholder(_))
1563 | (Backdrop(_), Backdrop(_))
1564 | (FileSelectorButton(_), FileSelectorButton(_)) => true,
1565 (a, b) => a == b,
1566 }
1567 }
1568
1569 pub(crate) fn get_prefix(&self) -> VendorPrefix {
1570 use PseudoElement::*;
1571 match self {
1572 Selection(p) | Placeholder(p) | Backdrop(p) | FileSelectorButton(p) => *p,
1573 _ => VendorPrefix::empty(),
1574 }
1575 }
1576
1577 pub(crate) fn get_necessary_prefixes(&mut self, targets: Targets) -> VendorPrefix {
1578 use crate::prefixes::Feature;
1579 use PseudoElement::*;
1580 let (p, feature) = match self {
1581 Selection(p) => (p, Feature::PseudoElementSelection),
1582 Placeholder(p) => (p, Feature::PseudoElementPlaceholder),
1583 Backdrop(p) => (p, Feature::PseudoElementBackdrop),
1584 FileSelectorButton(p) => (p, Feature::PseudoElementFileSelectorButton),
1585 _ => return VendorPrefix::empty(),
1586 };
1587
1588 *p = targets.prefixes(*p, feature);
1589 *p
1590 }
1591}
1592
1593impl<'a, 'i> ToCss for SelectorList<'i> {
1594 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1595 let context = detach_style_context(dest.state().context);
1596 serialize_selector_list(self.0.iter(), dest, context, false)
1597 }
1598}
1599
1600impl ToCss for Combinator {
1601 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1602 match *self {
1603 Combinator::Child => dest.delim('>', true),
1604 Combinator::Descendant => {
1605 dest.write_str(" ")?;
1606 Ok(())
1607 }
1608 Combinator::NextSibling => dest.delim('+', true),
1609 Combinator::LaterSibling => dest.delim('~', true),
1610 Combinator::Deep => {
1611 dest.write_str(" /deep/ ")?;
1612 Ok(())
1613 }
1614 Combinator::DeepDescendant => {
1615 dest.whitespace()?;
1616 dest.write_str(">>>")?;
1617 dest.whitespace()
1618 }
1619 Combinator::PseudoElement | Combinator::Part | Combinator::SlotAssignment => Ok(()),
1620 }
1621 }
1622}
1623
1624impl<'a, 'i> ToCss for Selector<'i> {
1626 fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1627 let context = detach_style_context(dest.state().context);
1628 serialize_selector(self, dest, context, false)
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 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.state().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 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 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 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 (Some(Combinator::PseudoElement), _) | (Some(Combinator::SlotAssignment), _) => (),
1707 (_, &Component::ExplicitUniversalType) => {
1708 let mut iter = compound.iter();
1711 let swap_nesting = has_leading_nesting && should_compile_nesting;
1712 if swap_nesting {
1713 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 perform_step_2 = false;
1727 }
1728 _ => (),
1729 }
1730 }
1731
1732 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 let nesting = iter.next().unwrap();
1747 let local = iter.next().unwrap();
1748 serialize_component(local, dest, context)?;
1749
1750 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 iter.next();
1760 serialize_nesting(dest, context, true)?;
1761 }
1762
1763 for simple in iter {
1764 if let Component::ExplicitUniversalType = *simple {
1765 if can_elide_namespace {
1770 continue;
1771 }
1772 }
1773 serialize_component(simple, dest, context)?;
1774 }
1775 }
1776
1777 match next_combinator {
1783 Some(c) => c.to_css(dest)?,
1784 None => combinators_exhausted = true,
1785 };
1786
1787 }
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 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 should_unwrap_is(selectors) {
1849 serialize_selector(selectors.first().unwrap(), dest, context, false)?;
1850 return Ok(());
1851 }
1852
1853 let vp = dest.state().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.state().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 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 should_compile!(dest.state().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 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 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 Component::Is(selectors) => {
2111 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 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 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
2254pub(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
2286pub(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 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 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
2326pub(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 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 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 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 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
2439pub(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
2476pub(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}