Skip to main content

rspack_lightningcss/rules/
mod.rs

1//! CSS rules.
2//!
3//! The [CssRule](CssRule) enum includes all supported rules, and can be used to parse
4//! and serialize rules from CSS. Lists of rules (i.e. within a stylesheet, or inside
5//! another rule such as `@media`) are represented by [CssRuleList](CssRuleList).
6//!
7//! Each rule includes a source location, which indicates the line and column within
8//! the source file where it was parsed. This is used when generating source maps.
9//!
10//! # Example
11//!
12//! This example shows how you could parse a single CSS rule, and serialize it to a string.
13//!
14//! ```
15//! use rspack_lightningcss::{
16//!   rules::CssRule,
17//!   traits::ToCss,
18//!   stylesheet::{ParserOptions, PrinterOptions}
19//! };
20//!
21//! let rule = CssRule::parse_string(
22//!   ".foo { color: red; }",
23//!   ParserOptions::default()
24//! ).unwrap();
25//!
26//! assert_eq!(
27//!   rule.to_css_string(PrinterOptions::default()).unwrap(),
28//!   ".foo {\n  color: red;\n}"
29//! );
30//! ```
31//!
32//! If you have a [cssparser::Parser](cssparser::Parser) already, you can also use the `parse` and `to_css`
33//! methods instead, rather than parsing from a string.
34//!
35//! See [StyleSheet](super::stylesheet::StyleSheet) to parse an entire file of multiple rules.
36
37#![deny(missing_docs)]
38
39pub mod container;
40pub mod counter_style;
41pub mod custom_media;
42pub mod document;
43pub mod font_face;
44pub mod font_feature_values;
45pub mod font_palette_values;
46pub mod import;
47pub mod keyframes;
48pub mod layer;
49pub mod media;
50pub mod namespace;
51pub mod nesting;
52pub mod page;
53pub mod position_try;
54pub mod property;
55pub mod scope;
56pub mod starting_style;
57pub mod style;
58pub mod supports;
59pub mod unknown;
60pub mod view_transition;
61pub mod viewport;
62
63use self::font_feature_values::FontFeatureValuesRule;
64use self::font_palette_values::FontPaletteValuesRule;
65use self::layer::{LayerBlockRule, LayerStatementRule};
66use self::property::PropertyRule;
67use crate::context::PropertyHandlerContext;
68use crate::declaration::{DeclarationBlock, DeclarationHandler};
69use crate::dependencies::{Dependency, ImportDependency};
70use crate::error::{MinifyError, ParserError, PrinterError, PrinterErrorKind};
71use crate::parser::{parse_rule_list, parse_style_block, DefaultAtRule, DefaultAtRuleParser, TopLevelRuleParser};
72use crate::prefixes::Feature;
73use crate::printer::{Printer, PrinterOptions};
74use crate::properties::custom::CustomPropertyName;
75use crate::properties::Property;
76use crate::rules::keyframes::KeyframesName;
77use crate::selector::{has_nesting, is_compatible, is_equivalent, Component, Selector, SelectorList};
78use crate::stylesheet::ParserOptions;
79use crate::targets::{should_compile, Targets, TargetsWithSupportsScope};
80use crate::traits::{AtRuleParser, ToCss};
81use crate::values::string::CowArcStr;
82use crate::vendor_prefix::VendorPrefix;
83#[cfg(feature = "visitor")]
84use crate::visitor::{Visit, VisitTypes, Visitor};
85use container::ContainerRule;
86use counter_style::CounterStyleRule;
87use cssparser::{parse_one_rule, ParseError, Parser, ParserInput};
88use custom_media::CustomMediaRule;
89use document::MozDocumentRule;
90use font_face::FontFaceRule;
91use import::ImportRule;
92use itertools::Itertools;
93use keyframes::KeyframesRule;
94use media::MediaRule;
95use namespace::NamespaceRule;
96use nesting::{NestedDeclarationsRule, NestingRule};
97use page::PageRule;
98use position_try::PositionTryRule;
99use scope::ScopeRule;
100use smallvec::{smallvec, SmallVec};
101use starting_style::StartingStyleRule;
102use std::collections::{HashMap, HashSet};
103use std::hash::{BuildHasherDefault, Hasher};
104use style::StyleRule;
105use supports::SupportsRule;
106use unknown::UnknownAtRule;
107use view_transition::ViewTransitionRule;
108use viewport::ViewportRule;
109
110#[derive(Clone)]
111pub(crate) struct StyleContext<'a, 'i> {
112  pub selectors: &'a SelectorList<'i>,
113  pub parent: Option<&'a StyleContext<'a, 'i>>,
114}
115
116pub(crate) type StyleContextPtr = *const StyleContext<'static, 'static>;
117
118pub(crate) fn style_context_ptr(context: &StyleContext<'_, '_>) -> StyleContextPtr {
119  context as *const _ as StyleContextPtr
120}
121
122pub(crate) fn detach_style_context(
123  context: Option<StyleContextPtr>,
124) -> Option<&'static StyleContext<'static, 'static>> {
125  context.map(|ptr| unsafe { &*ptr })
126}
127
128/// A source location.
129#[derive(PartialEq, Eq, Debug, Clone, Copy)]
130#[cfg_attr(any(feature = "serde", feature = "nodejs"), derive(serde::Serialize))]
131#[cfg_attr(feature = "serde", derive(serde::Deserialize))]
132#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
133#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
134pub struct Location {
135  /// The index of the source file within the source map.
136  pub source_index: u32,
137  /// The line number, starting at 0.
138  pub line: u32,
139  /// The column number within a line, starting at 1 for first the character of the line.
140  /// Column numbers are counted in UTF-16 code units.
141  pub column: u32,
142}
143
144/// A CSS rule.
145#[derive(Debug, PartialEq, Clone)]
146#[cfg_attr(feature = "visitor", derive(Visit))]
147#[cfg_attr(feature = "visitor", visit(visit_rule, RULES))]
148#[cfg_attr(
149  feature = "serde",
150  derive(serde::Serialize),
151  serde(tag = "type", content = "value", rename_all = "kebab-case")
152)]
153#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema), schemars(rename = "Rule"))]
154#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
155pub enum CssRule<'i, R = DefaultAtRule> {
156  /// A `@media` rule.
157  #[cfg_attr(feature = "serde", serde(borrow))]
158  Media(MediaRule<'i, R>),
159  /// An `@import` rule.
160  Import(ImportRule<'i>),
161  /// A style rule.
162  Style(StyleRule<'i, R>),
163  /// A `@keyframes` rule.
164  Keyframes(KeyframesRule<'i>),
165  /// A `@font-face` rule.
166  FontFace(FontFaceRule<'i>),
167  /// A `@font-palette-values` rule.
168  FontPaletteValues(FontPaletteValuesRule<'i>),
169  /// A `@font-feature-values` rule.
170  FontFeatureValues(FontFeatureValuesRule<'i>),
171  /// A `@page` rule.
172  Page(PageRule<'i>),
173  /// A `@supports` rule.
174  Supports(SupportsRule<'i, R>),
175  /// A `@counter-style` rule.
176  CounterStyle(CounterStyleRule<'i>),
177  /// A `@namespace` rule.
178  Namespace(NamespaceRule<'i>),
179  /// A `@-moz-document` rule.
180  MozDocument(MozDocumentRule<'i, R>),
181  /// A `@nest` rule.
182  Nesting(NestingRule<'i, R>),
183  /// A nested declarations rule.
184  NestedDeclarations(NestedDeclarationsRule<'i>),
185  /// A `@viewport` rule.
186  Viewport(ViewportRule<'i>),
187  /// A `@custom-media` rule.
188  CustomMedia(CustomMediaRule<'i>),
189  /// A `@layer` statement rule.
190  LayerStatement(LayerStatementRule<'i>),
191  /// A `@layer` block rule.
192  LayerBlock(LayerBlockRule<'i, R>),
193  /// A `@property` rule.
194  Property(PropertyRule<'i>),
195  /// A `@container` rule.
196  Container(ContainerRule<'i, R>),
197  /// A `@scope` rule.
198  Scope(ScopeRule<'i, R>),
199  /// A `@starting-style` rule.
200  StartingStyle(StartingStyleRule<'i, R>),
201  /// A `@view-transition` rule.
202  ViewTransition(ViewTransitionRule<'i>),
203  /// A `@position-try` rule.
204  PositionTry(PositionTryRule<'i>),
205  /// A placeholder for a rule that was removed.
206  Ignored,
207  /// An unknown at-rule.
208  Unknown(UnknownAtRule<'i>),
209  /// A custom at-rule.
210  Custom(R),
211}
212
213// Manually implemented deserialize to reduce binary size.
214#[cfg(feature = "serde")]
215#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
216impl<'i, 'de: 'i, R: serde::Deserialize<'de>> serde::Deserialize<'de> for CssRule<'i, R> {
217  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
218  where
219    D: serde::Deserializer<'de>,
220  {
221    #[derive(serde::Deserialize)]
222    #[serde(field_identifier, rename_all = "snake_case")]
223    enum Field {
224      Type,
225      Value,
226    }
227
228    struct PartialRule<'de> {
229      rule_type: CowArcStr<'de>,
230      content: serde_content::Value<'de>,
231    }
232
233    struct CssRuleVisitor;
234
235    impl<'de> serde::de::Visitor<'de> for CssRuleVisitor {
236      type Value = PartialRule<'de>;
237
238      fn expecting(&self, formatter: &mut std::fmt::Formatter) -> std::fmt::Result {
239        formatter.write_str("a CssRule")
240      }
241
242      fn visit_map<A>(self, mut map: A) -> Result<Self::Value, A::Error>
243      where
244        A: serde::de::MapAccess<'de>,
245      {
246        let mut rule_type: Option<CowArcStr<'de>> = None;
247        let mut value: Option<serde_content::Value> = None;
248        while let Some(key) = map.next_key()? {
249          match key {
250            Field::Type => {
251              rule_type = Some(map.next_value()?);
252            }
253            Field::Value => {
254              value = Some(map.next_value()?);
255            }
256          }
257        }
258
259        let rule_type = rule_type.ok_or_else(|| serde::de::Error::missing_field("type"))?;
260        let content = value.ok_or_else(|| serde::de::Error::missing_field("value"))?;
261        Ok(PartialRule { rule_type, content })
262      }
263    }
264
265    let partial = deserializer.deserialize_map(CssRuleVisitor)?;
266    let deserializer = serde_content::Deserializer::new(partial.content).coerce_numbers();
267
268    match partial.rule_type.as_ref() {
269      "media" => {
270        let rule = MediaRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
271        Ok(CssRule::Media(rule))
272      }
273      "import" => {
274        let rule = ImportRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
275        Ok(CssRule::Import(rule))
276      }
277      "style" => {
278        let rule = StyleRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
279        Ok(CssRule::Style(rule))
280      }
281      "keyframes" => {
282        let rule =
283          KeyframesRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
284        Ok(CssRule::Keyframes(rule))
285      }
286      "font-face" => {
287        let rule = FontFaceRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
288        Ok(CssRule::FontFace(rule))
289      }
290      "font-palette-values" => {
291        let rule =
292          FontPaletteValuesRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
293        Ok(CssRule::FontPaletteValues(rule))
294      }
295      "font-feature-values" => {
296        let rule =
297          FontFeatureValuesRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
298        Ok(CssRule::FontFeatureValues(rule))
299      }
300      "page" => {
301        let rule = PageRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
302        Ok(CssRule::Page(rule))
303      }
304      "supports" => {
305        let rule = SupportsRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
306        Ok(CssRule::Supports(rule))
307      }
308      "counter-style" => {
309        let rule =
310          CounterStyleRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
311        Ok(CssRule::CounterStyle(rule))
312      }
313      "namespace" => {
314        let rule =
315          NamespaceRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
316        Ok(CssRule::Namespace(rule))
317      }
318      "moz-document" => {
319        let rule =
320          MozDocumentRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
321        Ok(CssRule::MozDocument(rule))
322      }
323      "nesting" => {
324        let rule = NestingRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
325        Ok(CssRule::Nesting(rule))
326      }
327      "nested-declarations" => {
328        let rule = NestedDeclarationsRule::deserialize(deserializer)
329          .map_err(|e| serde::de::Error::custom(e.to_string()))?;
330        Ok(CssRule::NestedDeclarations(rule))
331      }
332      "viewport" => {
333        let rule = ViewportRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
334        Ok(CssRule::Viewport(rule))
335      }
336      "custom-media" => {
337        let rule =
338          CustomMediaRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
339        Ok(CssRule::CustomMedia(rule))
340      }
341      "layer-statement" => {
342        let rule =
343          LayerStatementRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
344        Ok(CssRule::LayerStatement(rule))
345      }
346      "layer-block" => {
347        let rule =
348          LayerBlockRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
349        Ok(CssRule::LayerBlock(rule))
350      }
351      "property" => {
352        let rule = PropertyRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
353        Ok(CssRule::Property(rule))
354      }
355      "container" => {
356        let rule =
357          ContainerRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
358        Ok(CssRule::Container(rule))
359      }
360      "scope" => {
361        let rule = ScopeRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
362        Ok(CssRule::Scope(rule))
363      }
364      "starting-style" => {
365        let rule =
366          StartingStyleRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
367        Ok(CssRule::StartingStyle(rule))
368      }
369      "view-transition" => {
370        let rule =
371          ViewTransitionRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
372        Ok(CssRule::ViewTransition(rule))
373      }
374      "position-try" => {
375        let rule =
376          PositionTryRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
377        Ok(CssRule::PositionTry(rule))
378      }
379      "ignored" => Ok(CssRule::Ignored),
380      "unknown" => {
381        let rule =
382          UnknownAtRule::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
383        Ok(CssRule::Unknown(rule))
384      }
385      "custom" => {
386        let rule = R::deserialize(deserializer).map_err(|e| serde::de::Error::custom(e.to_string()))?;
387        Ok(CssRule::Custom(rule))
388      }
389      t => Err(serde::de::Error::unknown_variant(t, &[])),
390    }
391  }
392}
393
394impl<'a, 'i, T: ToCss> ToCss for CssRule<'i, T> {
395  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
396    match self {
397      CssRule::Media(media) => media.to_css(dest),
398      CssRule::Import(import) => import.to_css(dest),
399      CssRule::Style(style) => style.to_css(dest),
400      CssRule::Keyframes(keyframes) => keyframes.to_css(dest),
401      CssRule::FontFace(font_face) => font_face.to_css(dest),
402      CssRule::FontPaletteValues(f) => f.to_css(dest),
403      CssRule::FontFeatureValues(font_feature_values) => font_feature_values.to_css(dest),
404      CssRule::Page(font_face) => font_face.to_css(dest),
405      CssRule::Supports(supports) => supports.to_css(dest),
406      CssRule::CounterStyle(counter_style) => counter_style.to_css(dest),
407      CssRule::Namespace(namespace) => namespace.to_css(dest),
408      CssRule::MozDocument(document) => document.to_css(dest),
409      CssRule::Nesting(nesting) => nesting.to_css(dest),
410      CssRule::NestedDeclarations(nested) => nested.to_css(dest),
411      CssRule::Viewport(viewport) => viewport.to_css(dest),
412      CssRule::CustomMedia(custom_media) => custom_media.to_css(dest),
413      CssRule::LayerStatement(layer) => layer.to_css(dest),
414      CssRule::LayerBlock(layer) => layer.to_css(dest),
415      CssRule::Property(property) => property.to_css(dest),
416      CssRule::StartingStyle(rule) => rule.to_css(dest),
417      CssRule::Container(container) => container.to_css(dest),
418      CssRule::Scope(scope) => scope.to_css(dest),
419      CssRule::ViewTransition(rule) => rule.to_css(dest),
420      CssRule::PositionTry(rule) => rule.to_css(dest),
421      CssRule::Unknown(unknown) => unknown.to_css(dest),
422      CssRule::Custom(rule) => rule.to_css(dest).map_err(|_| PrinterError {
423        kind: PrinterErrorKind::FmtError,
424        loc: None,
425      }),
426      CssRule::Ignored => Ok(()),
427    }
428  }
429}
430
431impl<'i> CssRule<'i, DefaultAtRule> {
432  /// Parse a single rule.
433  pub fn parse<'t>(
434    input: &mut Parser<'i, 't>,
435    options: &ParserOptions<'i>,
436  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
437    Self::parse_with(input, options, &mut DefaultAtRuleParser)
438  }
439
440  /// Parse a single rule from a string.
441  pub fn parse_string(
442    input: &'i str,
443    options: ParserOptions<'i>,
444  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
445    Self::parse_string_with(input, options, &mut DefaultAtRuleParser)
446  }
447}
448
449impl<'i, T> CssRule<'i, T> {
450  /// Parse a single rule.
451  pub fn parse_with<'t, P: AtRuleParser<'i, AtRule = T>>(
452    input: &mut Parser<'i, 't>,
453    options: &ParserOptions<'i>,
454    at_rule_parser: &mut P,
455  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
456    let mut rules = CssRuleList(Vec::new());
457    parse_one_rule(input, &mut TopLevelRuleParser::new(options, at_rule_parser, &mut rules))?;
458    Ok(rules.0.pop().unwrap())
459  }
460
461  /// Parse a single rule from a string.
462  pub fn parse_string_with<P: AtRuleParser<'i, AtRule = T>>(
463    input: &'i str,
464    options: ParserOptions<'i>,
465    at_rule_parser: &mut P,
466  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
467    let mut input = ParserInput::new(input);
468    let mut parser = Parser::new(&mut input);
469    Self::parse_with(&mut parser, &options, at_rule_parser)
470  }
471}
472
473/// A list of CSS rules.
474#[derive(Debug, PartialEq, Clone, Default)]
475#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(transparent))]
476#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
477#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
478pub struct CssRuleList<'i, R = DefaultAtRule>(
479  #[cfg_attr(feature = "serde", serde(borrow))] pub Vec<CssRule<'i, R>>,
480);
481
482impl<'i> CssRuleList<'i, DefaultAtRule> {
483  /// Parse a rule list.
484  pub fn parse<'t>(
485    input: &mut Parser<'i, 't>,
486    options: &ParserOptions<'i>,
487  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
488    Self::parse_with(input, options, &mut DefaultAtRuleParser)
489  }
490
491  /// Parse a style block, with both declarations and rules.
492  /// Resulting declarations are returned in a nested style rule.
493  pub fn parse_style_block<'t>(
494    input: &mut Parser<'i, 't>,
495    options: &ParserOptions<'i>,
496    is_nested: bool,
497  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
498    Self::parse_style_block_with(input, options, &mut DefaultAtRuleParser, is_nested)
499  }
500}
501
502impl<'i, T> CssRuleList<'i, T> {
503  /// Parse a rule list with a custom at rule parser.
504  pub fn parse_with<'t, P: AtRuleParser<'i, AtRule = T>>(
505    input: &mut Parser<'i, 't>,
506    options: &ParserOptions<'i>,
507    at_rule_parser: &mut P,
508  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
509    parse_rule_list(input, options, at_rule_parser)
510  }
511
512  /// Parse a style block, with both declarations and rules.
513  /// Resulting declarations are returned in a nested style rule.
514  pub fn parse_style_block_with<'t, P: AtRuleParser<'i, AtRule = T>>(
515    input: &mut Parser<'i, 't>,
516    options: &ParserOptions<'i>,
517    at_rule_parser: &mut P,
518    is_nested: bool,
519  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
520    parse_style_block(input, options, at_rule_parser, is_nested)
521  }
522}
523
524// Manually implemented to avoid circular child types.
525#[cfg(feature = "visitor")]
526#[cfg_attr(docsrs, doc(cfg(feature = "visitor")))]
527impl<'i, T: Visit<'i, T, V>, V: ?Sized + Visitor<'i, T>> Visit<'i, T, V> for CssRuleList<'i, T> {
528  const CHILD_TYPES: VisitTypes = VisitTypes::all();
529
530  fn visit(&mut self, visitor: &mut V) -> Result<(), V::Error> {
531    if visitor.visit_types().contains(VisitTypes::RULES) {
532      visitor.visit_rule_list(self)
533    } else {
534      self.0.visit(visitor)
535    }
536  }
537
538  fn visit_children(&mut self, visitor: &mut V) -> Result<(), V::Error> {
539    self.0.visit(visitor)
540  }
541}
542
543pub(crate) struct MinifyContext<'a, 'i> {
544  pub targets: TargetsWithSupportsScope,
545  pub handler: &'a mut DeclarationHandler<'i>,
546  pub important_handler: &'a mut DeclarationHandler<'i>,
547  pub handler_context: PropertyHandlerContext<'i, 'a>,
548  pub unused_symbols: &'a HashSet<String>,
549  pub custom_media: Option<HashMap<CowArcStr<'i>, CustomMediaRule<'i>>>,
550  pub css_modules: bool,
551  pub pure_css_modules: bool,
552}
553
554impl<'i, T: Clone> CssRuleList<'i, T> {
555  fn coalesce_adjacent_conditional_rules(&mut self) {
556    // Merge adjacent conditional rules before minifying their contents. Otherwise,
557    // long runs of identical @media/@supports/@container rules repeatedly re-minify
558    // the accumulated rule list as each block is appended.
559    if self.0.len() < 2
560      || !self.0.windows(2).any(|rules| match (&rules[0], &rules[1]) {
561        (CssRule::Media(a), CssRule::Media(b)) => a.query == b.query,
562        (CssRule::Supports(a), CssRule::Supports(b)) => a.condition == b.condition,
563        (CssRule::Container(a), CssRule::Container(b)) => a.name == b.name && a.condition == b.condition,
564        _ => false,
565      })
566    {
567      return;
568    }
569
570    let mut rules = Vec::with_capacity(self.0.len());
571    for rule in std::mem::take(&mut self.0) {
572      match rule {
573        CssRule::Media(mut media) => {
574          if let Some(CssRule::Media(last_rule)) = rules.last_mut() {
575            if last_rule.query == media.query {
576              last_rule.rules.0.append(&mut media.rules.0);
577              continue;
578            }
579          }
580
581          rules.push(CssRule::Media(media));
582        }
583        CssRule::Supports(mut supports) => {
584          if let Some(CssRule::Supports(last_rule)) = rules.last_mut() {
585            if last_rule.condition == supports.condition {
586              last_rule.rules.0.append(&mut supports.rules.0);
587              continue;
588            }
589          }
590
591          rules.push(CssRule::Supports(supports));
592        }
593        CssRule::Container(mut container) => {
594          if let Some(CssRule::Container(last_rule)) = rules.last_mut() {
595            if last_rule.name == container.name && last_rule.condition == container.condition {
596              last_rule.rules.0.append(&mut container.rules.0);
597              continue;
598            }
599          }
600
601          rules.push(CssRule::Container(container));
602        }
603        rule => rules.push(rule),
604      }
605    }
606
607    self.0 = rules;
608  }
609
610  pub(crate) fn minify(
611    &mut self,
612    context: &mut MinifyContext<'_, 'i>,
613    parent_is_unused: bool,
614  ) -> Result<(), MinifyError> {
615    self.coalesce_adjacent_conditional_rules();
616
617    let mut keyframe_rules = HashMap::new();
618    let mut layer_rules = HashMap::new();
619    let mut has_layers = false;
620    let mut property_rules = HashMap::new();
621    let mut font_feature_values_rules = Vec::new();
622    let mut style_rules =
623      HashMap::with_capacity_and_hasher(self.0.len(), BuildHasherDefault::<PrecomputedHasher>::default());
624    let mut rules = Vec::new();
625    for mut rule in self.0.drain(..) {
626      // Other rules may contribute to the same layers, including through
627      // conditional groups or imported stylesheets. Do not move layer content
628      // across them without analyzing those contributions.
629      if !matches!(
630        &rule,
631        CssRule::LayerBlock(_) | CssRule::LayerStatement(_) | CssRule::Ignored
632      ) && !matches!(&rule, CssRule::Style(style) if style.rules.0.is_empty())
633      {
634        layer_rules.clear();
635      }
636      match &mut rule {
637        CssRule::Keyframes(keyframes) => {
638          if context.unused_symbols.contains(match &keyframes.name {
639            KeyframesName::Ident(ident) => ident.0.as_ref(),
640            KeyframesName::Custom(string) => string.as_ref(),
641          }) {
642            continue;
643          }
644          keyframes.minify(context);
645
646          macro_rules! set_prefix {
647            ($keyframes: ident) => {
648              $keyframes.vendor_prefix =
649                context.targets.current.prefixes($keyframes.vendor_prefix, Feature::AtKeyframes);
650            };
651          }
652
653          // Merge @keyframes rules with the same name.
654          if let Some(existing_idx) = keyframe_rules.get(&keyframes.name) {
655            if let Some(CssRule::Keyframes(existing)) = &mut rules.get_mut(*existing_idx) {
656              // If the existing rule has the same vendor prefixes, replace it with this rule.
657              if existing.vendor_prefix == keyframes.vendor_prefix {
658                *existing = keyframes.clone();
659                continue;
660              }
661              // Otherwise, if the keyframes are identical, merge the prefixes.
662              if existing.keyframes == keyframes.keyframes {
663                existing.vendor_prefix |= keyframes.vendor_prefix;
664                set_prefix!(existing);
665                continue;
666              }
667            }
668          }
669
670          set_prefix!(keyframes);
671          keyframe_rules.insert(keyframes.name.clone(), rules.len());
672
673          let fallbacks = keyframes.get_fallbacks(&context.targets.current);
674          rules.push(rule);
675          rules.extend(fallbacks);
676          continue;
677        }
678        CssRule::CustomMedia(_) => {
679          if context.custom_media.is_some() {
680            continue;
681          }
682        }
683        CssRule::Media(media) => {
684          if let Some(CssRule::Media(last_rule)) = rules.last_mut() {
685            if last_rule.query == media.query {
686              last_rule.rules.0.extend(media.rules.0.drain(..));
687              last_rule.minify(context, parent_is_unused)?;
688              continue;
689            }
690          }
691
692          if media.minify(context, parent_is_unused)? {
693            continue;
694          }
695        }
696        CssRule::Supports(supports) => {
697          if let Some(CssRule::Supports(last_rule)) = rules.last_mut() {
698            if last_rule.condition == supports.condition {
699              last_rule.rules.0.extend(supports.rules.0.drain(..));
700              last_rule.minify(context, parent_is_unused)?;
701              continue;
702            }
703          }
704
705          supports.minify(context, parent_is_unused)?;
706          if supports.rules.0.is_empty() {
707            continue;
708          }
709        }
710        CssRule::Container(container) => {
711          if let Some(CssRule::Container(last_rule)) = rules.last_mut() {
712            if last_rule.name == container.name && last_rule.condition == container.condition {
713              last_rule.rules.0.extend(container.rules.0.drain(..));
714              last_rule.minify(context, parent_is_unused)?;
715              continue;
716            }
717          }
718
719          if container.minify(context, parent_is_unused)? {
720            continue;
721          }
722        }
723        CssRule::LayerBlock(layer) => {
724          // Remember the last block per top-level layer. A different path in
725          // the same hierarchy (e.g. `a.b` between two `a` blocks) may establish
726          // sublayer order or add styles that must not be reordered by merging.
727          if let Some(name) = &layer.name {
728            let root = &name.0[0];
729            if let Some(idx) = layer_rules.get(root) {
730              if let Some(CssRule::LayerBlock(last_rule)) = rules.get_mut(*idx) {
731                if last_rule.name.as_ref() == Some(name) {
732                  last_rule.rules.0.extend(layer.rules.0.drain(..));
733                  continue;
734                }
735              }
736            }
737
738            layer_rules.insert(root.clone(), rules.len());
739            has_layers = true;
740          }
741        }
742        CssRule::LayerStatement(layer) => {
743          // Create @layer block rules for each declared layer name,
744          // so we can merge other blocks into it later on.
745          for name in &layer.names {
746            let root = &name.0[0];
747            let exists = layer_rules.get(root).is_some_and(|idx| {
748              matches!(rules.get(*idx), Some(CssRule::LayerBlock(layer)) if layer.name.as_ref() == Some(name))
749            });
750            if !exists {
751              layer_rules.insert(root.clone(), rules.len());
752              has_layers = true;
753              rules.push(CssRule::LayerBlock(LayerBlockRule {
754                name: Some(name.clone()),
755                rules: CssRuleList(vec![]),
756                loc: layer.loc.clone(),
757              }));
758            }
759          }
760          continue;
761        }
762        CssRule::MozDocument(document) => document.minify(context)?,
763        CssRule::Style(style) => {
764          if parent_is_unused || style.minify(context, parent_is_unused)? {
765            continue;
766          }
767
768          // If some of the selectors in this rule are not compatible with the targets,
769          // we need to either wrap in :is() or split them into multiple rules.
770          let incompatible = if style.selectors.0.len() > 1
771            && context.targets.current.should_compile_selectors()
772            && !style.is_compatible(context.targets.current)
773          {
774            // The :is() selector accepts a forgiving selector list, so use that if possible.
775            // Note that :is() does not allow pseudo elements, so we need to check for that.
776            // In addition, :is() takes the highest specificity of its arguments, so if the selectors
777            // have different weights, we need to split them into separate rules as well.
778            if context.targets.current.is_compatible(crate::compat::Feature::IsSelector)
779              && !style.selectors.0.iter().any(|selector| selector.has_pseudo_element())
780              && style.selectors.0.iter().map(|selector| selector.specificity()).all_equal()
781            {
782              style.selectors =
783                SelectorList::new(smallvec![
784                  Component::Is(style.selectors.0.clone().into_boxed_slice()).into()
785                ]);
786              smallvec![]
787            } else {
788              // Otherwise, partition the selectors and keep the compatible ones in this rule.
789              // We will generate additional rules for incompatible selectors later.
790              let (compatible, incompatible) = style
791                .selectors
792                .0
793                .iter()
794                .cloned()
795                .partition::<SmallVec<[Selector; 1]>, _>(|selector| {
796                  let list = SelectorList::new(smallvec![selector.clone()]);
797                  is_compatible(&list.0, context.targets.current)
798                });
799              style.selectors = SelectorList::new(compatible);
800              incompatible
801            }
802          } else {
803            smallvec![]
804          };
805
806          style.update_prefix(context);
807
808          // Attempt to merge the new rule with the last rule we added.
809          let mut merged = false;
810          if let Some(CssRule::Style(last_style_rule)) = rules.last_mut() {
811            if merge_style_rules(style, last_style_rule, context) {
812              // If that was successful, then the last rule has been updated to include the
813              // selectors/declarations of the new rule. This might mean that we can merge it
814              // with the previous rule, so continue trying while we have style rules available.
815              while rules.len() >= 2 {
816                let len = rules.len();
817                let (a, b) = rules.split_at_mut(len - 1);
818                if let (CssRule::Style(last), CssRule::Style(prev)) = (&mut b[0], &mut a[len - 2]) {
819                  if merge_style_rules(last, prev, context) {
820                    // If we were able to merge the last rule into the previous one, remove the last.
821                    rules.pop();
822                    continue;
823                  }
824                }
825                // If we didn't see a style rule, or were unable to merge, stop.
826                break;
827              }
828              merged = true;
829            }
830          }
831
832          // Create additional rules for logical properties, @supports overrides, and incompatible selectors.
833          let supports = context.handler_context.get_supports_rules(&style);
834          let logical = context.handler_context.get_additional_rules(&style);
835
836          let incompatible_rules = incompatible
837            .into_iter()
838            .map(|selector| {
839              // Create a clone of the rule with only the one incompatible selector.
840              let list = SelectorList::new(smallvec![selector]);
841              let mut clone = style.clone();
842              clone.selectors = list;
843              clone.update_prefix(context);
844
845              // Also add rules for logical properties and @supports overrides.
846              let supports = context.handler_context.get_supports_rules(&clone);
847              let logical = context.handler_context.get_additional_rules(&clone);
848              (clone, logical, supports)
849            })
850            .collect::<Vec<_>>();
851
852          context.handler_context.reset();
853
854          // If the rule has nested rules, and we have extra rules to insert such as for logical properties,
855          // we need to split the rule in two so we can insert the extra rules in between the declarations from
856          // the main rule and the nested rules.
857          let nested_rule = if !style.rules.0.is_empty()
858            // can happen if there are no compatible rules, above.
859            && !style.selectors.0.is_empty()
860            && (!logical.is_empty() || !supports.is_empty() || !incompatible_rules.is_empty())
861          {
862            let mut rules = CssRuleList(vec![]);
863            std::mem::swap(&mut style.rules, &mut rules);
864            Some(StyleRule {
865              selectors: style.selectors.clone(),
866              declarations: DeclarationBlock::default(),
867              rules,
868              vendor_prefix: style.vendor_prefix,
869              loc: style.loc,
870            })
871          } else {
872            None
873          };
874
875          if !merged && !style.is_empty() {
876            let source_index = style.loc.source_index;
877            let has_no_rules = style.rules.0.is_empty();
878            let idx = rules.len();
879            rules.push(rule);
880
881            // Check if this rule is a duplicate of an earlier rule, meaning it has
882            // the same selectors and defines the same properties. If so, remove the
883            // earlier rule because this one completely overrides it.
884            if has_no_rules {
885              // SAFETY: StyleRuleKeys never live beyond this method.
886              let key = StyleRuleKey::new(unsafe { &*(&rules as *const _) }, idx);
887              if idx > 0 {
888                if let Some(i) = style_rules.remove(&key) {
889                  if let CssRule::Style(other) = &rules[i] {
890                    // Don't remove the rule if this is a CSS module and the other rule came from a different file.
891                    if !context.css_modules || source_index == other.loc.source_index {
892                      // Only mark the rule as ignored so we don't need to change all of the indices.
893                      rules[i] = CssRule::Ignored;
894                    }
895                  }
896                }
897              }
898
899              style_rules.insert(key, idx);
900            }
901          }
902
903          if !logical.is_empty() {
904            let mut logical = CssRuleList(logical);
905            logical.minify(context, parent_is_unused)?;
906            rules.extend(logical.0)
907          }
908
909          rules.extend(supports);
910          for (rule, logical, supports) in incompatible_rules {
911            if !rule.is_empty() {
912              rules.push(CssRule::Style(rule));
913            }
914            if !logical.is_empty() {
915              let mut logical = CssRuleList(logical);
916              logical.minify(context, parent_is_unused)?;
917              rules.extend(logical.0)
918            }
919            rules.extend(supports);
920          }
921
922          if let Some(nested_rule) = nested_rule {
923            rules.push(CssRule::Style(nested_rule));
924          }
925
926          continue;
927        }
928        CssRule::CounterStyle(counter_style) => {
929          if context.unused_symbols.contains(counter_style.name.0.as_ref()) {
930            continue;
931          }
932        }
933        CssRule::Scope(scope) => scope.minify(context)?,
934        CssRule::Nesting(nesting) => {
935          if nesting.minify(context, parent_is_unused)? {
936            continue;
937          }
938        }
939        CssRule::NestedDeclarations(nested) => {
940          if nested.minify(context, parent_is_unused) {
941            continue;
942          }
943        }
944        CssRule::StartingStyle(rule) => {
945          if rule.minify(context, parent_is_unused)? {
946            continue;
947          }
948        }
949        CssRule::FontPaletteValues(f) => {
950          if context.unused_symbols.contains(f.name.0.as_ref()) {
951            continue;
952          }
953
954          f.minify(context, parent_is_unused);
955
956          let fallbacks = f.get_fallbacks(context.targets.current);
957          rules.push(rule);
958          rules.extend(fallbacks);
959          continue;
960        }
961        CssRule::FontFeatureValues(rule) => {
962          if let Some(index) = font_feature_values_rules
963            .iter()
964            .find(|index| matches!(&rules[**index], CssRule::FontFeatureValues(r) if r.name == rule.name))
965          {
966            if let CssRule::FontFeatureValues(existing) = &mut rules[*index] {
967              existing.merge(rule);
968            }
969            continue;
970          } else {
971            font_feature_values_rules.push(rules.len());
972          }
973        }
974        CssRule::PositionTry(rule) => {
975          if context.unused_symbols.contains(rule.name.0.as_ref()) {
976            continue;
977          }
978        }
979        CssRule::Property(property) => {
980          if context.unused_symbols.contains(property.name.0.as_ref()) {
981            continue;
982          }
983
984          if let Some(index) = property_rules.get(&property.name) {
985            rules[*index] = rule;
986            continue;
987          } else {
988            property_rules.insert(property.name.clone(), rules.len());
989          }
990        }
991        _ => {}
992      }
993
994      rules.push(rule)
995    }
996
997    // Optimize @layer rules. Combine subsequent empty layer blocks into a single @layer statement
998    // so that layers are declared in the correct order.
999    if has_layers {
1000      let mut declared_layers = HashSet::new();
1001      let mut layer_statement = None;
1002      for index in 0..rules.len() {
1003        match &mut rules[index] {
1004          CssRule::LayerBlock(layer) => {
1005            if layer.minify(context, parent_is_unused)? {
1006              if let Some(name) = &layer.name {
1007                if declared_layers.contains(name) {
1008                  // Remove empty layer that has already been declared.
1009                  rules[index] = CssRule::Ignored;
1010                  continue;
1011                }
1012
1013                let name = name.clone();
1014                declared_layers.insert(name.clone());
1015
1016                if let Some(layer_index) = layer_statement {
1017                  if let CssRule::LayerStatement(layer) = &mut rules[layer_index] {
1018                    // Add name to previous layer statement rule and remove this one.
1019                    layer.names.push(name);
1020                    rules[index] = CssRule::Ignored;
1021                  }
1022                } else {
1023                  // Create a new layer statement rule to declare the name.
1024                  rules[index] = CssRule::LayerStatement(LayerStatementRule {
1025                    names: vec![name],
1026                    loc: layer.loc,
1027                  });
1028                  layer_statement = Some(index);
1029                }
1030              } else {
1031                // Remove empty anonymous layer.
1032                rules[index] = CssRule::Ignored;
1033              }
1034            } else {
1035              // Non-empty @layer block. Start a new statement.
1036              layer_statement = None;
1037            }
1038          }
1039          CssRule::Import(import) => {
1040            // Even an unlayered import can declare layers in its stylesheet.
1041            layer_statement = None;
1042            if import.supports.is_none() && import.media.always_matches() {
1043              if let Some(Some(name)) = &import.layer {
1044                declared_layers.insert(name.clone());
1045              }
1046            }
1047          }
1048          CssRule::Ignored => {}
1049          CssRule::Style(style) if style.rules.0.is_empty() => {}
1050          // Do not hoist declarations across rules that may establish layers,
1051          // including conditionally. Keep their first-declaration order intact.
1052          _ => layer_statement = None,
1053        }
1054      }
1055    }
1056
1057    // The duplicate-rule keys borrow rules and their declarations. Finish using
1058    // them before extracting declarations into new rules.
1059    drop(style_rules);
1060    self.0 = if context.css_modules {
1061      rules
1062    } else {
1063      factor_custom_properties(rules, context.targets.current)
1064    };
1065    Ok(())
1066  }
1067}
1068
1069fn factor_custom_properties<'i, T>(mut rules: Vec<CssRule<'i, T>>, targets: Targets) -> Vec<CssRule<'i, T>> {
1070  if rules.len() < 2 {
1071    return rules;
1072  }
1073
1074  let mut result = Vec::with_capacity(rules.len());
1075  rules.reverse();
1076  while let Some(mut rule) = rules.pop() {
1077    if matches!(rule, CssRule::Ignored) {
1078      continue;
1079    }
1080
1081    if let (Some(CssRule::Style(previous)), CssRule::Style(current)) = (result.last_mut(), &mut rule) {
1082      if merge_after_custom_property_extraction(previous, current, targets) {
1083        rules.push(result.pop().unwrap());
1084        continue;
1085      }
1086      if let Some(shared) = extract_common_custom_properties(previous, current, targets) {
1087        let previous_is_empty = previous.is_empty();
1088        if !current.is_empty() {
1089          rules.push(rule);
1090        }
1091        rules.push(CssRule::Style(shared));
1092        let previous = result.pop().unwrap();
1093        if !previous_is_empty {
1094          rules.push(previous);
1095        }
1096        // A rewrite can enable a merge with the predecessor. Revisit only the
1097        // changed neighborhood. Every rewrite strictly reduces serialized size.
1098        continue;
1099      }
1100    }
1101    result.push(rule);
1102  }
1103  result
1104}
1105
1106fn merge_after_custom_property_extraction<'i, T>(
1107  previous: &mut StyleRule<'i, T>,
1108  current: &mut StyleRule<'i, T>,
1109  targets: Targets,
1110) -> bool {
1111  let only_custom_properties = |declarations: &DeclarationBlock<'i>| {
1112    declarations.iter().all(|(property, _)| {
1113      matches!(property, Property::Custom(custom) if matches!(custom.name, CustomPropertyName::Custom(_)))
1114    })
1115  };
1116  if (previous.selectors != current.selectors && previous.declarations != current.declarations)
1117    || !previous.rules.0.is_empty()
1118    || !current.rules.0.is_empty()
1119    || previous.loc.source_index != current.loc.source_index
1120    || (previous.vendor_prefix | current.vendor_prefix).intersects(!VendorPrefix::None)
1121    || previous.selectors.0.iter().any(has_nesting)
1122    || current.selectors.0.iter().any(has_nesting)
1123    || !previous.is_compatible(targets)
1124    || !current.is_compatible(targets)
1125  {
1126    return false;
1127  }
1128
1129  if previous.declarations == current.declarations {
1130    if previous.selectors != current.selectors {
1131      previous.selectors.0.extend(current.selectors.0.drain(..));
1132    }
1133    previous.vendor_prefix |= current.vendor_prefix;
1134    return true;
1135  }
1136
1137  if !(only_custom_properties(&previous.declarations) || only_custom_properties(&current.declarations)) {
1138    return false;
1139  }
1140
1141  // At least one block contains only custom properties, so ordinary properties
1142  // cannot interact across the blocks. Resolve repeated custom properties within
1143  // each importance level without re-running handlers that generate fallbacks.
1144  for (previous, current) in [
1145    (
1146      &mut previous.declarations.declarations,
1147      &mut current.declarations.declarations,
1148    ),
1149    (
1150      &mut previous.declarations.important_declarations,
1151      &mut current.declarations.important_declarations,
1152    ),
1153  ] {
1154    let mut indices = HashMap::new();
1155    for (index, property) in previous.iter().enumerate() {
1156      if let Property::Custom(custom) = property {
1157        indices.insert(custom.name.clone(), index);
1158      }
1159    }
1160    for property in current.drain(..) {
1161      if let Property::Custom(custom) = &property {
1162        if let Some(index) = indices.get(&custom.name) {
1163          previous[*index] = property;
1164          continue;
1165        }
1166        indices.insert(custom.name.clone(), previous.len());
1167      }
1168      previous.push(property);
1169    }
1170  }
1171  previous.vendor_prefix |= current.vendor_prefix;
1172  true
1173}
1174
1175fn extract_common_custom_properties<'i, T>(
1176  previous: &mut StyleRule<'i, T>,
1177  current: &mut StyleRule<'i, T>,
1178  targets: Targets,
1179) -> Option<StyleRule<'i, T>> {
1180  if !previous.rules.0.is_empty()
1181    || !current.rules.0.is_empty()
1182    || previous.loc.source_index != current.loc.source_index
1183    || (previous.vendor_prefix | current.vendor_prefix).intersects(!VendorPrefix::None)
1184  {
1185    return None;
1186  }
1187
1188  // Custom properties have no shorthand interactions, and `all` does not reset
1189  // them. Only equal names, values, and importance can move into the shared rule.
1190  let mut properties = HashMap::new();
1191  for (property, important) in previous.declarations.iter() {
1192    if let Property::Custom(custom) = property {
1193      if matches!(custom.name, CustomPropertyName::Custom(_)) {
1194        properties.insert((&custom.name, important), property);
1195      }
1196    }
1197  }
1198  if properties.is_empty() {
1199    return None;
1200  }
1201
1202  let mut common = HashSet::new();
1203  let mut css = String::new();
1204  let mut printer = Printer::new(
1205    &mut css,
1206    PrinterOptions {
1207      minify: true,
1208      targets,
1209      ..PrinterOptions::default()
1210    },
1211  );
1212  for (property, important) in current.declarations.iter() {
1213    if let Property::Custom(custom) = property {
1214      if properties
1215        .get(&(&custom.name, important))
1216        .is_some_and(|other| **other == *property)
1217      {
1218        property.to_css(&mut printer, important).ok()?;
1219        printer.write_char(';').ok()?;
1220        common.insert((custom.name.clone(), important));
1221      }
1222    }
1223  }
1224  if common.is_empty()
1225    || previous.selectors.0.iter().any(has_nesting)
1226    || current.selectors.0.iter().any(has_nesting)
1227    || !previous.is_compatible(targets)
1228    || !current.is_compatible(targets)
1229  {
1230    return None;
1231  }
1232
1233  let shared_size = css.len() - 1;
1234  let options = || PrinterOptions {
1235    minify: true,
1236    targets,
1237    ..PrinterOptions::default()
1238  };
1239  let previous_selectors_size = previous.selectors.to_css_string(options()).ok()?.len();
1240  let current_selectors_size = current.selectors.to_css_string(options()).ok()?.len();
1241  let previous_remains = previous.declarations.len() > common.len();
1242  let current_remains = current.declarations.len() > common.len();
1243
1244  // Account for the extra selector list and braces, and for semicolons removed
1245  // from the original blocks. Do not factor when the minified output would grow.
1246  let overhead = match (previous_remains, current_remains) {
1247    (true, true) => previous_selectors_size + current_selectors_size + 1,
1248    (false, true) => current_selectors_size,
1249    (true, false) => previous_selectors_size,
1250    (false, false) => 0,
1251  };
1252  if shared_size <= overhead {
1253    return None;
1254  }
1255
1256  let mut declarations = DeclarationBlock::new();
1257  for (previous, current, shared, important) in [
1258    (
1259      &mut previous.declarations.declarations,
1260      &mut current.declarations.declarations,
1261      &mut declarations.declarations,
1262      false,
1263    ),
1264    (
1265      &mut previous.declarations.important_declarations,
1266      &mut current.declarations.important_declarations,
1267      &mut declarations.important_declarations,
1268      true,
1269    ),
1270  ] {
1271    let is_common = |property: &Property<'i>| match property {
1272      Property::Custom(custom) => common.contains(&(custom.name.clone(), important)),
1273      _ => false,
1274    };
1275    shared.extend(previous.extract_if(.., |property| is_common(property)));
1276    current.retain(|property| !is_common(property));
1277  }
1278
1279  let mut selectors = previous.selectors.clone();
1280  selectors.0.extend(current.selectors.0.iter().cloned());
1281  Some(StyleRule {
1282    selectors,
1283    vendor_prefix: previous.vendor_prefix | current.vendor_prefix,
1284    declarations,
1285    rules: CssRuleList(vec![]),
1286    loc: previous.loc,
1287  })
1288}
1289
1290fn merge_style_rules<'i, T>(
1291  style: &mut StyleRule<'i, T>,
1292  last_style_rule: &mut StyleRule<'i, T>,
1293  context: &mut MinifyContext<'_, 'i>,
1294) -> bool {
1295  // Merge declarations if the selectors are equivalent, and both are compatible with all targets.
1296  if style.selectors == last_style_rule.selectors
1297    && style.is_compatible(context.targets.current)
1298    && last_style_rule.is_compatible(context.targets.current)
1299    && style.rules.0.is_empty()
1300    && last_style_rule.rules.0.is_empty()
1301    && (!context.css_modules || style.loc.source_index == last_style_rule.loc.source_index)
1302  {
1303    last_style_rule
1304      .declarations
1305      .declarations
1306      .extend(style.declarations.declarations.drain(..));
1307    last_style_rule
1308      .declarations
1309      .important_declarations
1310      .extend(style.declarations.important_declarations.drain(..));
1311    last_style_rule
1312      .declarations
1313      .minify(context.handler, context.important_handler, &mut context.handler_context);
1314    return true;
1315  } else if style.declarations == last_style_rule.declarations
1316    && style.rules.0.is_empty()
1317    && last_style_rule.rules.0.is_empty()
1318  {
1319    // If both selectors are potentially vendor prefixable, and they are
1320    // equivalent minus prefixes, add the prefix to the last rule.
1321    if !style.vendor_prefix.is_empty()
1322      && !last_style_rule.vendor_prefix.is_empty()
1323      && is_equivalent(&style.selectors.0, &last_style_rule.selectors.0)
1324    {
1325      // If the new rule is unprefixed, replace the prefixes of the last rule.
1326      // Otherwise, add the new prefix.
1327      if style.vendor_prefix.contains(VendorPrefix::None) && context.targets.current.should_compile_selectors() {
1328        last_style_rule.vendor_prefix = style.vendor_prefix;
1329      } else {
1330        last_style_rule.vendor_prefix |= style.vendor_prefix;
1331      }
1332      return true;
1333    }
1334
1335    // Append the selectors to the last rule if the declarations are the same, and all selectors are compatible.
1336    if style.is_compatible(context.targets.current) && last_style_rule.is_compatible(context.targets.current) {
1337      last_style_rule.selectors.0.extend(style.selectors.0.drain(..));
1338      if style.vendor_prefix.contains(VendorPrefix::None) && context.targets.current.should_compile_selectors() {
1339        last_style_rule.vendor_prefix = style.vendor_prefix;
1340      } else {
1341        last_style_rule.vendor_prefix |= style.vendor_prefix;
1342      }
1343      return true;
1344    }
1345  }
1346  false
1347}
1348
1349impl<'a, 'i, T: ToCss> ToCss for CssRuleList<'i, T> {
1350  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1351    let mut first = true;
1352    let mut last_without_block = false;
1353
1354    for (i, rule) in self.0.iter().enumerate() {
1355      if let CssRule::Ignored = &rule {
1356        continue;
1357      }
1358
1359      // Skip @import rules if collecting dependencies.
1360      if let CssRule::Import(rule) = &rule {
1361        if dest.state().remove_imports {
1362          let dep = if dest.state().dependencies.is_some() {
1363            Some(Dependency::Import(ImportDependency::new(&rule, dest.filename())))
1364          } else {
1365            None
1366          };
1367
1368          if let Some(dependencies) = dest.state_mut().dependencies.as_mut() {
1369            dependencies.push(dep.unwrap());
1370            continue;
1371          }
1372        }
1373      }
1374
1375      if first {
1376        first = false;
1377      } else {
1378        if !dest.options().minify
1379          && !(last_without_block
1380            && matches!(
1381              rule,
1382              CssRule::Import(..) | CssRule::Namespace(..) | CssRule::LayerStatement(..)
1383            ))
1384        {
1385          dest.write_char('\n')?;
1386        }
1387        dest.newline()?;
1388      }
1389      rule.to_css(dest)?;
1390
1391      // If this is an invisible nested declarations rule, and not the last rule in the block, add a semicolon.
1392      if dest.options().minify
1393        && !should_compile!(dest.state().targets.current, Nesting)
1394        && matches!(rule, CssRule::NestedDeclarations(_))
1395        && i != self.0.len() - 1
1396      {
1397        dest.write_char(';')?;
1398      }
1399
1400      last_without_block = matches!(
1401        rule,
1402        CssRule::Import(..) | CssRule::Namespace(..) | CssRule::LayerStatement(..)
1403      );
1404    }
1405
1406    Ok(())
1407  }
1408}
1409
1410impl<'i, T> std::ops::Index<usize> for CssRuleList<'i, T> {
1411  type Output = CssRule<'i, T>;
1412
1413  fn index(&self, index: usize) -> &Self::Output {
1414    &self.0[index]
1415  }
1416}
1417
1418impl<'i, T> std::ops::IndexMut<usize> for CssRuleList<'i, T> {
1419  fn index_mut(&mut self, index: usize) -> &mut Self::Output {
1420    &mut self.0[index]
1421  }
1422}
1423
1424/// A hasher that expects to be called with a single u64, which is already a hash.
1425#[derive(Default)]
1426struct PrecomputedHasher {
1427  hash: Option<u64>,
1428}
1429
1430impl Hasher for PrecomputedHasher {
1431  #[inline]
1432  fn write(&mut self, _: &[u8]) {
1433    unreachable!()
1434  }
1435
1436  #[inline]
1437  fn write_u64(&mut self, i: u64) {
1438    debug_assert!(self.hash.is_none());
1439    self.hash = Some(i);
1440  }
1441
1442  #[inline]
1443  fn finish(&self) -> u64 {
1444    self.hash.unwrap()
1445  }
1446}
1447
1448/// A key to a StyleRule meant for use in a HashMap for quickly detecting duplicates.
1449/// It stores a reference to a list and an index so it can access items without cloning
1450/// even when the list is reallocated. A hash is also pre-computed for fast lookups.
1451#[derive(Clone)]
1452pub(crate) struct StyleRuleKey<'a, 'i, R> {
1453  list: &'a Vec<CssRule<'i, R>>,
1454  index: usize,
1455  hash: u64,
1456}
1457
1458impl<'a, 'i, R> StyleRuleKey<'a, 'i, R> {
1459  fn new(list: &'a Vec<CssRule<'i, R>>, index: usize) -> Self {
1460    let rule = match &list[index] {
1461      CssRule::Style(style) => style,
1462      _ => unreachable!(),
1463    };
1464
1465    Self {
1466      list,
1467      index,
1468      hash: rule.hash_key(),
1469    }
1470  }
1471}
1472
1473impl<'a, 'i, R> PartialEq for StyleRuleKey<'a, 'i, R> {
1474  fn eq(&self, other: &Self) -> bool {
1475    let rule = match self.list.get(self.index) {
1476      Some(CssRule::Style(style)) => style,
1477      _ => return false,
1478    };
1479
1480    let other_rule = match other.list.get(other.index) {
1481      Some(CssRule::Style(style)) => style,
1482      _ => return false,
1483    };
1484
1485    rule.is_duplicate(other_rule)
1486  }
1487}
1488
1489impl<'a, 'i, R> Eq for StyleRuleKey<'a, 'i, R> {}
1490
1491impl<'a, 'i, R> std::hash::Hash for StyleRuleKey<'a, 'i, R> {
1492  fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
1493    state.write_u64(self.hash);
1494  }
1495}