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