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