Skip to main content

rspack_lightningcss/
visitor.rs

1//! Visitors for traversing the values in a StyleSheet.
2//!
3//! The [Visitor](Visitor) trait includes methods for visiting and transforming rules, properties, and values within a StyleSheet.
4//! Each value implements the [Visit](Visit) trait, which knows how to visit the value itself, as well as its children.
5//! A Visitor is configured to only visit specific types of values using [VisitTypes](VisitTypes) flags. This enables
6//! entire branches to be skipped when a type does not contain any relevant values.
7//!
8//! # Example
9//!
10//! This example transforms a stylesheet, adding a prefix to all URLs, and converting pixels to rems.
11//!
12//! ```
13//! use std::convert::Infallible;
14//! use rspack_lightningcss::{
15//!   stylesheet::{StyleSheet, ParserOptions, PrinterOptions},
16//!   visitor::{Visitor, Visit, VisitTypes},
17//!   visit_types,
18//!   values::length::LengthValue,
19//!   values::url::Url
20//! };
21//!
22//! let mut stylesheet = StyleSheet::parse(
23//!   r#"
24//!     .foo {
25//!       background: url(bg.png);
26//!       width: 32px;
27//!     }
28//!   "#,
29//!   ParserOptions::default()
30//! ).unwrap();
31//!
32//! struct MyVisitor;
33//! impl<'i> Visitor<'i> for MyVisitor {
34//!   type Error = Infallible;
35//!
36//!   fn visit_types(&self) -> VisitTypes {
37//!     visit_types!(URLS | LENGTHS)
38//!   }
39//!
40//!   fn visit_url(&mut self, url: &mut Url<'i>) -> Result<(), Self::Error> {
41//!     url.url = format!("https://mywebsite.com/{}", url.url).into();
42//!     Ok(())
43//!   }
44//!
45//!   fn visit_length(&mut self, length: &mut LengthValue) -> Result<(), Self::Error> {
46//!     match length {
47//!       LengthValue::Px(px) => *length = LengthValue::Rem(*px / 16.0),
48//!       _ => {}
49//!     }
50//!
51//!     Ok(())
52//!   }
53//! }
54//!
55//! stylesheet.visit(&mut MyVisitor).unwrap();
56//!
57//! let res = stylesheet
58//!   .to_css(PrinterOptions { minify: true, ..Default::default() }, None::<&mut ()>)
59//!   .unwrap();
60//! assert_eq!(res.code, ".foo{background:url(https://mywebsite.com/bg.png);width:2rem}");
61//! ```
62
63use crate::{
64  declaration::DeclarationBlock,
65  media_query::{MediaFeature, MediaFeatureValue, MediaList, MediaQuery},
66  parser::DefaultAtRule,
67  properties::{
68    custom::{EnvironmentVariable, Function, TokenList, TokenOrValue, Variable},
69    Property,
70  },
71  rules::{supports::SupportsCondition, CssRule, CssRuleList},
72  selector::{Selector, SelectorList},
73  stylesheet::StyleSheet,
74  values::{
75    angle::Angle,
76    color::CssColor,
77    ident::{CustomIdent, DashedIdent},
78    image::Image,
79    length::LengthValue,
80    ratio::Ratio,
81    resolution::Resolution,
82    time::Time,
83    url::Url,
84  },
85};
86use bitflags::bitflags;
87use indexmap::IndexMap;
88use smallvec::SmallVec;
89
90pub(crate) use rspack_lightningcss_derive::Visit;
91
92bitflags! {
93  /// Describes what a [Visitor](Visitor) will visit when traversing a StyleSheet.
94  ///
95  /// Flags may be combined to visit multiple types. The [visit_types](visit_types) macro allows
96  /// combining flags in a `const` expression.
97  #[derive(PartialEq, Eq, Clone, Copy)]
98  pub struct VisitTypes: u32 {
99    /// Visit rules.
100    const RULES = 1 << 0;
101    /// Visit properties;
102    const PROPERTIES = 1 << 1;
103    /// Visit urls.
104    const URLS = 1 << 2;
105    /// Visit colors.
106    const COLORS = 1 << 3;
107    /// Visit images.
108    const IMAGES = 1 << 4;
109    /// Visit lengths.
110    const LENGTHS = 1 << 5;
111    /// Visit angles.
112    const ANGLES = 1 << 6;
113    /// Visit ratios.
114    const RATIOS = 1 << 7;
115    /// Visit resolutions.
116    const RESOLUTIONS = 1 << 8;
117    /// Visit times.
118    const TIMES = 1 << 9;
119    /// Visit custom identifiers.
120    const CUSTOM_IDENTS = 1 << 10;
121    /// Visit dashed identifiers.
122    const DASHED_IDENTS = 1 << 11;
123    /// Visit variables.
124    const VARIABLES = 1 << 12;
125    /// Visit environment variables.
126    const ENVIRONMENT_VARIABLES = 1 << 13;
127    /// Visit media queries.
128    const MEDIA_QUERIES = 1 << 14;
129    /// Visit supports conditions.
130    const SUPPORTS_CONDITIONS = 1 << 15;
131    /// Visit selectors.
132    const SELECTORS = 1 << 16;
133    /// Visit custom functions.
134    const FUNCTIONS = 1 << 17;
135    /// Visit a token.
136    const TOKENS = 1 << 18;
137  }
138}
139
140/// Constructs a constant [VisitTypes](VisitTypes) from flags.
141#[macro_export]
142macro_rules! visit_types {
143  ($( $flag: ident )|+) => {
144    $crate::visitor::VisitTypes::from_bits_truncate(0 $(| $crate::visitor::VisitTypes::$flag.bits())+)
145  }
146}
147
148/// A trait for visiting or transforming rules, properties, and values in a StyleSheet.
149pub trait Visitor<'i, T: Visit<'i, T, Self> = DefaultAtRule> {
150  /// The `Err` value for `Result`s returned by `visit_*` methods.
151  type Error;
152
153  /// Returns the types of values that this visitor should visit. By default, it returns
154  /// `Self::TYPES`, but this can be overridden to change the value at runtime.
155  fn visit_types(&self) -> VisitTypes;
156
157  /// Visits a stylesheet.
158  #[inline]
159  fn visit_stylesheet<'o>(&mut self, stylesheet: &mut StyleSheet<'i, T>) -> Result<(), Self::Error> {
160    stylesheet.visit_children(self)
161  }
162
163  /// Visits a rule list.
164  #[inline]
165  fn visit_rule_list(&mut self, rules: &mut CssRuleList<'i, T>) -> Result<(), Self::Error> {
166    rules.visit_children(self)
167  }
168
169  /// Visits a rule.
170  #[inline]
171  fn visit_rule(&mut self, rule: &mut CssRule<'i, T>) -> Result<(), Self::Error> {
172    rule.visit_children(self)
173  }
174
175  /// Visits a declaration block.
176  #[inline]
177  fn visit_declaration_block(&mut self, decls: &mut DeclarationBlock<'i>) -> Result<(), Self::Error> {
178    decls.visit_children(self)
179  }
180
181  /// Visits a property.
182  #[inline]
183  fn visit_property(&mut self, property: &mut Property<'i>) -> Result<(), Self::Error> {
184    property.visit_children(self)
185  }
186
187  /// Visits a url.
188  fn visit_url(&mut self, _url: &mut Url<'i>) -> Result<(), Self::Error> {
189    Ok(())
190  }
191
192  /// Visits a color.
193  #[allow(unused_variables)]
194  fn visit_color(&mut self, color: &mut CssColor) -> Result<(), Self::Error> {
195    Ok(())
196  }
197
198  /// Visits an image.
199  #[inline]
200  fn visit_image(&mut self, image: &mut Image<'i>) -> Result<(), Self::Error> {
201    image.visit_children(self)
202  }
203
204  /// Visits a length.
205  #[allow(unused_variables)]
206  fn visit_length(&mut self, length: &mut LengthValue) -> Result<(), Self::Error> {
207    Ok(())
208  }
209
210  /// Visits an angle.
211  #[allow(unused_variables)]
212  fn visit_angle(&mut self, angle: &mut Angle) -> Result<(), Self::Error> {
213    Ok(())
214  }
215
216  /// Visits a ratio.
217  #[allow(unused_variables)]
218  fn visit_ratio(&mut self, ratio: &mut Ratio) -> Result<(), Self::Error> {
219    Ok(())
220  }
221
222  /// Visits a resolution.
223  #[allow(unused_variables)]
224  fn visit_resolution(&mut self, resolution: &mut Resolution) -> Result<(), Self::Error> {
225    Ok(())
226  }
227
228  /// Visits a time.
229  #[allow(unused_variables)]
230  fn visit_time(&mut self, time: &mut Time) -> Result<(), Self::Error> {
231    Ok(())
232  }
233
234  /// Visits a custom ident.
235  #[allow(unused_variables)]
236  fn visit_custom_ident(&mut self, ident: &mut CustomIdent) -> Result<(), Self::Error> {
237    Ok(())
238  }
239
240  /// Visits a dashed ident.
241  #[allow(unused_variables)]
242  fn visit_dashed_ident(&mut self, ident: &mut DashedIdent) -> Result<(), Self::Error> {
243    Ok(())
244  }
245
246  /// Visits a variable reference.
247  #[inline]
248  fn visit_variable(&mut self, var: &mut Variable<'i>) -> Result<(), Self::Error> {
249    var.visit_children(self)
250  }
251
252  /// Visits an environment variable reference.
253  #[inline]
254  fn visit_environment_variable(&mut self, env: &mut EnvironmentVariable<'i>) -> Result<(), Self::Error> {
255    env.visit_children(self)
256  }
257
258  /// Visits a media query list.
259  #[inline]
260  fn visit_media_list(&mut self, media: &mut MediaList<'i>) -> Result<(), Self::Error> {
261    media.visit_children(self)
262  }
263
264  /// Visits a media query.
265  #[inline]
266  fn visit_media_query(&mut self, query: &mut MediaQuery<'i>) -> Result<(), Self::Error> {
267    query.visit_children(self)
268  }
269
270  /// Visits a media feature.
271  #[inline]
272  fn visit_media_feature(&mut self, feature: &mut MediaFeature<'i>) -> Result<(), Self::Error> {
273    feature.visit_children(self)
274  }
275
276  /// Visits a media feature value.
277  #[inline]
278  fn visit_media_feature_value(&mut self, value: &mut MediaFeatureValue<'i>) -> Result<(), Self::Error> {
279    value.visit_children(self)
280  }
281
282  /// Visits a supports condition.
283  #[inline]
284  fn visit_supports_condition(&mut self, condition: &mut SupportsCondition<'i>) -> Result<(), Self::Error> {
285    condition.visit_children(self)
286  }
287
288  /// Visits a selector list.
289  #[inline]
290  fn visit_selector_list(&mut self, selectors: &mut SelectorList<'i>) -> Result<(), Self::Error> {
291    selectors.visit_children(self)
292  }
293
294  /// Visits a selector.
295  #[allow(unused_variables)]
296  fn visit_selector(&mut self, selector: &mut Selector<'i>) -> Result<(), Self::Error> {
297    Ok(())
298  }
299
300  /// Visits a custom function.
301  #[inline]
302  fn visit_function(&mut self, function: &mut Function<'i>) -> Result<(), Self::Error> {
303    function.visit_children(self)
304  }
305
306  /// Visits a token list.
307  #[inline]
308  fn visit_token_list(&mut self, tokens: &mut TokenList<'i>) -> Result<(), Self::Error> {
309    tokens.visit_children(self)
310  }
311
312  /// Visits a token or value in an unparsed property.
313  #[inline]
314  fn visit_token(&mut self, token: &mut TokenOrValue<'i>) -> Result<(), Self::Error> {
315    token.visit_children(self)
316  }
317}
318
319/// A trait for values that can be visited by a [Visitor](Visitor).
320pub trait Visit<'i, T: Visit<'i, T, V>, V: ?Sized + Visitor<'i, T>> {
321  /// The types of values contained within this value and its children.
322  /// This is used to skip branches that don't have any values requested
323  /// by the Visitor.
324  const CHILD_TYPES: VisitTypes;
325
326  /// Visits the value by calling an appropriate method on the Visitor.
327  /// If no corresponding visitor method exists, then the children are visited.
328  #[inline]
329  fn visit(&mut self, visitor: &mut V) -> Result<(), V::Error> {
330    self.visit_children(visitor)
331  }
332
333  /// Visit the children of this value.
334  fn visit_children(&mut self, visitor: &mut V) -> Result<(), V::Error>;
335}
336
337impl<'i, T: Visit<'i, T, V>, V: ?Sized + Visitor<'i, T>, U: Visit<'i, T, V>> Visit<'i, T, V> for Option<U> {
338  const CHILD_TYPES: VisitTypes = U::CHILD_TYPES;
339
340  fn visit(&mut self, visitor: &mut V) -> Result<(), V::Error> {
341    if let Some(v) = self {
342      v.visit(visitor)
343    } else {
344      Ok(())
345    }
346  }
347
348  fn visit_children(&mut self, visitor: &mut V) -> Result<(), V::Error> {
349    if let Some(v) = self {
350      v.visit_children(visitor)
351    } else {
352      Ok(())
353    }
354  }
355}
356
357impl<'i, T: Visit<'i, T, V>, V: ?Sized + Visitor<'i, T>, U: Visit<'i, T, V>> Visit<'i, T, V> for Box<U> {
358  const CHILD_TYPES: VisitTypes = U::CHILD_TYPES;
359
360  fn visit(&mut self, visitor: &mut V) -> Result<(), V::Error> {
361    self.as_mut().visit(visitor)
362  }
363
364  fn visit_children(&mut self, visitor: &mut V) -> Result<(), V::Error> {
365    self.as_mut().visit_children(visitor)
366  }
367}
368
369impl<'i, T: Visit<'i, T, V>, V: ?Sized + Visitor<'i, T>, U: Visit<'i, T, V>> Visit<'i, T, V> for Vec<U> {
370  const CHILD_TYPES: VisitTypes = U::CHILD_TYPES;
371
372  fn visit(&mut self, visitor: &mut V) -> Result<(), V::Error> {
373    self.iter_mut().try_for_each(|v| v.visit(visitor))
374  }
375
376  fn visit_children(&mut self, visitor: &mut V) -> Result<(), V::Error> {
377    self.iter_mut().try_for_each(|v| v.visit_children(visitor))
378  }
379}
380
381impl<'i, A: smallvec::Array<Item = U>, U: Visit<'i, T, V>, T: Visit<'i, T, V>, V: ?Sized + Visitor<'i, T>>
382  Visit<'i, T, V> for SmallVec<A>
383{
384  const CHILD_TYPES: VisitTypes = U::CHILD_TYPES;
385
386  fn visit(&mut self, visitor: &mut V) -> Result<(), V::Error> {
387    self.iter_mut().try_for_each(|v| v.visit(visitor))
388  }
389
390  fn visit_children(&mut self, visitor: &mut V) -> Result<(), V::Error> {
391    self.iter_mut().try_for_each(|v| v.visit_children(visitor))
392  }
393}
394
395impl<'i, T, V, U, W> Visit<'i, T, V> for IndexMap<U, W>
396where
397  T: Visit<'i, T, V>,
398  V: ?Sized + Visitor<'i, T>,
399  W: Visit<'i, T, V>,
400{
401  const CHILD_TYPES: VisitTypes = W::CHILD_TYPES;
402
403  fn visit(&mut self, visitor: &mut V) -> Result<(), V::Error> {
404    self.iter_mut().try_for_each(|(_k, v)| v.visit(visitor))
405  }
406
407  fn visit_children(&mut self, visitor: &mut V) -> Result<(), V::Error> {
408    self.iter_mut().try_for_each(|(_k, v)| v.visit_children(visitor))
409  }
410}
411
412macro_rules! impl_visit {
413  ($t: ty) => {
414    impl<'i, V: ?Sized + Visitor<'i, T>, T: Visit<'i, T, V>> Visit<'i, T, V> for $t {
415      const CHILD_TYPES: VisitTypes = VisitTypes::empty();
416
417      fn visit_children(&mut self, _: &mut V) -> Result<(), V::Error> {
418        Ok(())
419      }
420    }
421  };
422}
423
424impl_visit!(u8);
425impl_visit!(u16);
426impl_visit!(u32);
427impl_visit!(i32);
428impl_visit!(f32);
429impl_visit!(bool);
430impl_visit!(char);
431impl_visit!(str);
432impl_visit!(String);
433impl_visit!((f32, f32));