Skip to main content

rspack_lightningcss/rules/
style.rs

1//! Style rules.
2
3use std::hash::{Hash, Hasher};
4use std::ops::Range;
5
6use super::Location;
7use super::MinifyContext;
8use crate::context::DeclarationContext;
9use crate::declaration::DeclarationBlock;
10use crate::error::ParserError;
11use crate::error::{MinifyError, PrinterError};
12use crate::parser::DefaultAtRule;
13use crate::printer::ContextAccess;
14use crate::rules::{CssRule, CssRuleList};
15use crate::selector::{
16  downlevel_selectors, get_prefix, is_compatible, is_pure_css_modules_selector, is_unused, SelectorList,
17};
18use crate::targets::{should_compile, Targets};
19use crate::traits::ToCss;
20use crate::vendor_prefix::VendorPrefix;
21#[cfg(feature = "visitor")]
22use crate::visitor::Visit;
23use cssparser::*;
24
25/// A CSS [style rule](https://drafts.csswg.org/css-syntax/#style-rules).
26#[derive(Debug, PartialEq, Clone)]
27#[cfg_attr(feature = "visitor", derive(Visit))]
28#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
29#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
30#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
31pub struct StyleRule<'i, R = DefaultAtRule> {
32  /// The selectors for the style rule.
33  #[cfg_attr(feature = "serde", serde(borrow))]
34  pub selectors: SelectorList<'i>,
35  /// A vendor prefix override, used during selector printing.
36  #[cfg_attr(feature = "serde", serde(skip, default = "VendorPrefix::empty"))]
37  #[cfg_attr(feature = "visitor", skip_visit)]
38  pub vendor_prefix: VendorPrefix,
39  /// The declarations within the style rule.
40  #[cfg_attr(feature = "serde", serde(default))]
41  pub declarations: DeclarationBlock<'i>,
42  /// Nested rules within the style rule.
43  #[cfg_attr(feature = "serde", serde(default = "default_rule_list::<R>"))]
44  pub rules: CssRuleList<'i, R>,
45  /// The location of the rule in the source file.
46  #[cfg_attr(feature = "visitor", skip_visit)]
47  pub loc: Location,
48}
49
50#[cfg(feature = "serde")]
51fn default_rule_list<'i, R>() -> CssRuleList<'i, R> {
52  CssRuleList(Vec::new())
53}
54
55impl<'i, T: Clone> StyleRule<'i, T> {
56  pub(crate) fn minify(
57    &mut self,
58    context: &mut MinifyContext<'_, 'i>,
59    parent_is_unused: bool,
60  ) -> Result<bool, MinifyError> {
61    let mut unused = false;
62    if !context.unused_symbols.is_empty() {
63      if is_unused(&mut self.selectors.0.iter(), &context.unused_symbols, parent_is_unused) {
64        if self.rules.0.is_empty() {
65          return Ok(true);
66        }
67
68        self.declarations.declarations.clear();
69        self.declarations.important_declarations.clear();
70        unused = true;
71      }
72    }
73
74    let pure_css_modules = context.pure_css_modules;
75    if context.pure_css_modules {
76      if !self.selectors.0.iter().all(is_pure_css_modules_selector) {
77        return Err(MinifyError {
78          kind: crate::error::MinifyErrorKind::ImpureCSSModuleSelector,
79          loc: self.loc,
80        });
81      }
82
83      // Parent rule contained id or class, so child rules don't need to.
84      context.pure_css_modules = false;
85    }
86
87    context.handler_context.context = DeclarationContext::StyleRule;
88    self
89      .declarations
90      .minify(context.handler, context.important_handler, &mut context.handler_context);
91    context.handler_context.context = DeclarationContext::None;
92
93    if !self.rules.0.is_empty() {
94      let mut handler_context = context.handler_context.child(DeclarationContext::StyleRule);
95      std::mem::swap(&mut context.handler_context, &mut handler_context);
96      self.rules.minify(context, unused)?;
97      context.handler_context = handler_context;
98      if unused && self.rules.0.is_empty() {
99        return Ok(true);
100      }
101    }
102
103    context.pure_css_modules = pure_css_modules;
104    Ok(false)
105  }
106}
107
108impl<'i, T> StyleRule<'i, T> {
109  /// Returns whether the rule is empty.
110  pub fn is_empty(&self) -> bool {
111    self.selectors.0.is_empty() || (self.declarations.is_empty() && self.rules.0.is_empty())
112  }
113
114  /// Returns whether the selectors in the rule are compatible
115  /// with all of the given browser targets.
116  pub fn is_compatible(&self, targets: Targets) -> bool {
117    is_compatible(&self.selectors.0, targets)
118  }
119
120  /// Returns the line and column range of the property key and value at the given index in this style rule.
121  ///
122  /// For performance and memory efficiency in non-error cases, source locations are not stored during parsing.
123  /// Instead, they are computed lazily using the original source string that was used to parse the stylesheet/rule.
124  pub fn property_location<'t>(
125    &self,
126    code: &'i str,
127    index: usize,
128  ) -> Result<(Range<SourceLocation>, Range<SourceLocation>), ParseError<'i, ParserError<'i>>> {
129    let mut input = ParserInput::new(code);
130    let mut parser = Parser::new(&mut input);
131
132    // advance until start location of this rule.
133    parse_at(&mut parser, self.loc, |parser| {
134      // skip selector
135      parser.parse_until_before(Delimiter::CurlyBracketBlock, |parser| {
136        while parser.next().is_ok() {}
137        Ok(())
138      })?;
139
140      parser.expect_curly_bracket_block()?;
141      parser.parse_nested_block(|parser| {
142        let loc = self.declarations.property_location(parser, index);
143        while parser.next().is_ok() {}
144        loc
145      })
146    })
147  }
148
149  /// Returns a hash of this rule for use when deduplicating.
150  /// Includes the selectors, properties, and importance.
151  #[inline]
152  pub(crate) fn hash_key(&self) -> u64 {
153    let mut hasher = ahash::AHasher::default();
154    self.selectors.hash(&mut hasher);
155    for (property, important) in self.declarations.iter() {
156      property.property_id().hash(&mut hasher);
157      important.hash(&mut hasher);
158    }
159    hasher.finish()
160  }
161
162  /// Returns whether this rule is a duplicate of another rule.
163  /// This means it has the same selectors, properties, and importance.
164  #[inline]
165  pub(crate) fn is_duplicate(&self, other_rule: &StyleRule<'i, T>) -> bool {
166    self.declarations.len() == other_rule.declarations.len()
167      && self.selectors == other_rule.selectors
168      && self.declarations.iter().zip(other_rule.declarations.iter()).all(
169        |((a, a_important), (b, b_important))| a_important == b_important && a.property_id() == b.property_id(),
170      )
171  }
172
173  pub(crate) fn update_prefix(&mut self, context: &mut MinifyContext<'_, 'i>) {
174    self.vendor_prefix = get_prefix(&self.selectors);
175    if self.vendor_prefix.contains(VendorPrefix::None) && context.targets.current.should_compile_selectors() {
176      self.vendor_prefix = downlevel_selectors(self.selectors.0.as_mut_slice(), context.targets.current);
177    }
178  }
179}
180
181fn parse_at<'i, 't, T, F>(
182  parser: &mut Parser<'i, 't>,
183  dest: Location,
184  parse: F,
185) -> Result<T, ParseError<'i, ParserError<'i>>>
186where
187  F: Copy + for<'tt> FnOnce(&mut Parser<'i, 'tt>) -> Result<T, ParseError<'i, ParserError<'i>>>,
188{
189  loop {
190    let loc = parser.current_source_location();
191    if loc.line >= dest.line || (loc.line == dest.line && loc.column >= dest.column) {
192      return parse(parser);
193    }
194
195    match parser.next()? {
196      Token::CurlyBracketBlock => {
197        // Recursively parse nested blocks.
198        let res = parser.parse_nested_block(|parser| {
199          let res = parse_at(parser, dest, parse);
200          while parser.next().is_ok() {}
201          res
202        });
203
204        if let Ok(v) = res {
205          return Ok(v);
206        }
207      }
208      _ => {}
209    }
210  }
211}
212
213impl<'a, 'i, T: ToCss> ToCss for StyleRule<'i, T> {
214  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
215    if self.vendor_prefix.is_empty() {
216      self.to_css_base(dest)
217    } else {
218      let mut first_rule = true;
219      for prefix in self.vendor_prefix {
220        if first_rule {
221          first_rule = false;
222        } else {
223          if !dest.options().minify {
224            dest.write_char('\n')?; // no indent
225          }
226          dest.newline()?;
227        }
228        dest.set_vendor_prefix(prefix);
229        self.to_css_base(dest)?;
230      }
231      dest.set_vendor_prefix(VendorPrefix::empty());
232      Ok(())
233    }
234  }
235}
236
237impl<'a, 'i, T: ToCss> StyleRule<'i, T> {
238  fn to_css_base<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
239    // If supported, or there are no targets, preserve nesting. Otherwise, write nested rules after parent.
240    let supports_nesting = self.rules.0.is_empty() || !should_compile!(dest.targets().current, Nesting);
241    let must_preserve_rule = |rule: &CssRule<'i, T>| matches!(rule, CssRule::Unknown(_));
242    let has_preserved_rules = !supports_nesting && self.rules.0.iter().any(must_preserve_rule);
243    let has_hoisted_rules = !supports_nesting && self.rules.0.iter().any(|rule| !must_preserve_rule(rule));
244    let len = self.declarations.declarations.len() + self.declarations.important_declarations.len();
245    let has_declarations = supports_nesting || len > 0 || self.rules.0.is_empty() || has_preserved_rules;
246
247    if has_declarations {
248      #[cfg(feature = "custom_sourcemap")]
249      dest.add_mapping(self.loc);
250      self.selectors.to_css(dest)?;
251      dest.whitespace()?;
252      dest.write_char('{')?;
253      dest.indent();
254      if len > 0 {
255        dest.newline()?;
256      }
257
258      self.declarations.to_css_declarations(
259        dest,
260        (supports_nesting && !self.rules.0.is_empty()) || has_preserved_rules,
261        &self.selectors,
262        self.loc.source_index,
263      )?;
264    }
265
266    macro_rules! newline {
267      () => {
268        if !dest.options().minify
269          && (supports_nesting || len > 0 || has_preserved_rules)
270          && !self.rules.0.is_empty()
271        {
272          if len > 0 || has_preserved_rules {
273            dest.write_char('\n')?;
274          }
275          dest.newline()?;
276        }
277      };
278    }
279
280    macro_rules! end {
281      () => {
282        if has_declarations {
283          dest.dedent();
284          dest.newline()?;
285          dest.write_char('}')?;
286        }
287      };
288    }
289
290    // Write nested rules after the parent, except unknown at-rules, which must remain in the style block.
291    if supports_nesting {
292      newline!();
293      self.rules.to_css(dest)?;
294      end!();
295    } else {
296      let mut first = true;
297      for rule in self.rules.0.iter().filter(|rule| must_preserve_rule(rule)) {
298        if !dest.options().minify || first {
299          dest.newline()?;
300        }
301        rule.to_css(dest)?;
302        first = false;
303      }
304      end!();
305
306      if has_hoisted_rules {
307        newline!();
308        dest.with_context(ContextAccess, &self.selectors, |dest| self.to_css_hoisted_rules(dest))?;
309      }
310    }
311
312    Ok(())
313  }
314
315  fn to_css_hoisted_rules<PrinterT: crate::printer::PrinterTrait>(
316    &self,
317    dest: &mut PrinterT,
318  ) -> Result<(), PrinterError> {
319    let mut first = true;
320    for rule in self.rules.0.iter().filter(|rule| !matches!(rule, CssRule::Unknown(_))) {
321      if first {
322        first = false;
323      } else {
324        if !dest.options().minify {
325          dest.write_char('\n')?;
326        }
327        dest.newline()?;
328      }
329      rule.to_css(dest)?;
330    }
331
332    Ok(())
333  }
334}
335
336#[cfg(test)]
337mod tests {
338  use super::*;
339  use crate::printer::{Printer, PrinterOptions, PrinterTrait};
340  use crate::rules::StyleContext;
341  use crate::stylesheet::{ParserOptions, StyleSheet};
342  use crate::targets::Features;
343  use std::cell::Cell;
344
345  fn nesting_options() -> PrinterOptions<'static> {
346    PrinterOptions {
347      targets: Targets {
348        include: Features::Nesting,
349        ..Targets::default()
350      },
351      ..PrinterOptions::default()
352    }
353  }
354
355  #[test]
356  fn restores_context_after_nested_writer_error() {
357    struct FailingWriter<'a> {
358      writes: &'a Cell<usize>,
359      fail_at: usize,
360    }
361
362    impl std::fmt::Write for FailingWriter<'_> {
363      fn write_str(&mut self, _: &str) -> std::fmt::Result {
364        let index = self.writes.get();
365        self.writes.set(index + 1);
366        if index == self.fail_at {
367          Err(std::fmt::Error)
368        } else {
369          Ok(())
370        }
371      }
372    }
373
374    let sheet = StyleSheet::parse(
375      ".a { & .b { & .c { color: red } } & .d { color: blue } }",
376      ParserOptions::default(),
377    )
378    .unwrap();
379    let CssRule::Style(rule) = &sheet.rules.0[0] else {
380      panic!("expected style rule");
381    };
382    let parent = StyleContext {
383      selectors: &rule.selectors,
384      parent: None,
385    };
386
387    for context in [None, Some(&parent)] {
388      let writes = Cell::new(0);
389      let mut writer = FailingWriter {
390        writes: &writes,
391        fail_at: usize::MAX,
392      };
393      let mut printer = Printer::new(&mut writer, nesting_options());
394      printer.state.context = context;
395      rule.to_css(&mut printer).unwrap();
396      let total_writes = writes.get();
397
398      // Fail at every write, including separators between hoisted rules.
399      for fail_at in 0..total_writes {
400        writes.set(0);
401        let mut writer = FailingWriter {
402          writes: &writes,
403          fail_at,
404        };
405        let mut printer = Printer::new(&mut writer, nesting_options());
406        printer.state.context = context;
407        assert!(rule.to_css(&mut printer).is_err());
408        assert!(same_context(printer.state.context, context), "write {fail_at}");
409        rule.to_css(&mut printer).unwrap();
410        assert!(same_context(printer.state.context, context));
411      }
412    }
413  }
414
415  #[test]
416  fn restores_context_after_nested_custom_rule_error() {
417    struct FailingRule;
418
419    impl ToCss for FailingRule {
420      fn to_css<P: PrinterTrait>(&self, _: &mut P) -> Result<(), PrinterError> {
421        Err(std::fmt::Error.into())
422      }
423    }
424
425    let sheet = StyleSheet::parse(".a {}", ParserOptions::default()).unwrap();
426    let CssRule::Style(parsed) = &sheet.rules.0[0] else {
427      panic!("expected style rule");
428    };
429    let rule = StyleRule {
430      selectors: parsed.selectors.clone(),
431      vendor_prefix: parsed.vendor_prefix,
432      declarations: parsed.declarations.clone(),
433      rules: CssRuleList(vec![CssRule::Custom(FailingRule)]),
434      loc: parsed.loc,
435    };
436    let parent = StyleContext {
437      selectors: &parsed.selectors,
438      parent: None,
439    };
440    for context in [None, Some(&parent)] {
441      let mut css = String::new();
442      let mut printer = Printer::new(&mut css, nesting_options());
443      printer.state.context = context;
444      assert!(rule.to_css(&mut printer).is_err());
445      assert!(same_context(printer.state.context, context));
446      parsed.to_css(&mut printer).unwrap();
447    }
448  }
449
450  fn same_context<'i>(a: Option<&StyleContext<'_, 'i>>, b: Option<&StyleContext<'_, 'i>>) -> bool {
451    match (a, b) {
452      (Some(a), Some(b)) => std::ptr::eq(a, b),
453      (None, None) => true,
454      _ => false,
455    }
456  }
457}