Skip to main content

rspack_lightningcss/properties/
custom.rs

1//! CSS custom properties and unparsed token values.
2
3use crate::error::{ParserError, PrinterError, PrinterErrorKind};
4use crate::macros::enum_property;
5use crate::prefixes::Feature;
6#[cfg(feature = "substitute_variables")]
7use crate::printer::Printer;
8use crate::properties::PropertyId;
9use crate::rules::supports::SupportsCondition;
10use crate::stylesheet::ParserOptions;
11use crate::targets::{should_compile, Features, Targets};
12use crate::traits::{Parse, ParseWithOptions, ToCss};
13use crate::values::angle::Angle;
14use crate::values::color::{
15  parse_hsl_hwb_components, parse_rgb_components, ColorFallbackKind, ComponentParser, CssColor, LightDarkColor,
16  HSL, RGB, RGBA,
17};
18use crate::values::ident::{CustomIdent, DashedIdent, DashedIdentReference, Ident};
19use crate::values::length::{serialize_dimension, LengthValue};
20use crate::values::number::CSSInteger;
21use crate::values::percentage::Percentage;
22use crate::values::resolution::Resolution;
23use crate::values::string::CowArcStr;
24use crate::values::time::Time;
25use crate::values::url::Url;
26#[cfg(feature = "visitor")]
27use crate::visitor::Visit;
28use cssparser::color::parse_hash_color;
29use cssparser::*;
30
31use super::AnimationName;
32#[cfg(feature = "serde")]
33use crate::serialization::ValueWrapper;
34
35/// A CSS custom property, representing any unknown property.
36#[derive(Debug, Clone, PartialEq)]
37#[cfg_attr(feature = "visitor", derive(Visit))]
38#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
39#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
40#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
41pub struct CustomProperty<'i> {
42  /// The name of the property.
43  #[cfg_attr(feature = "serde", serde(borrow))]
44  pub name: CustomPropertyName<'i>,
45  /// The property value, stored as a raw token list.
46  pub value: TokenList<'i>,
47}
48
49impl<'i> CustomProperty<'i> {
50  /// Parses a custom property with the given name.
51  pub fn parse<'t>(
52    name: CustomPropertyName<'i>,
53    input: &mut Parser<'i, 't>,
54    options: &ParserOptions<'i>,
55  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
56    let value = input.parse_until_before(Delimiter::Bang | Delimiter::Semicolon, |input| {
57      TokenList::parse(input, options, 0)
58    })?;
59    Ok(CustomProperty { name, value })
60  }
61}
62
63/// A CSS custom property name.
64#[derive(Debug, Clone, PartialEq, Eq, Hash)]
65#[cfg_attr(feature = "visitor", derive(Visit))]
66#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
67#[cfg_attr(feature = "serde", derive(serde::Serialize), serde(untagged))]
68#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
69pub enum CustomPropertyName<'i> {
70  /// An author-defined CSS custom property.
71  #[cfg_attr(feature = "serde", serde(borrow))]
72  Custom(DashedIdent<'i>),
73  /// An unknown CSS property.
74  Unknown(Ident<'i>),
75}
76
77impl<'i> From<CowArcStr<'i>> for CustomPropertyName<'i> {
78  fn from(name: CowArcStr<'i>) -> Self {
79    if name.starts_with("--") {
80      CustomPropertyName::Custom(DashedIdent(name))
81    } else {
82      CustomPropertyName::Unknown(Ident(name))
83    }
84  }
85}
86
87impl<'i> From<CowRcStr<'i>> for CustomPropertyName<'i> {
88  fn from(name: CowRcStr<'i>) -> Self {
89    CustomPropertyName::from(CowArcStr::from(name))
90  }
91}
92
93impl<'i> AsRef<str> for CustomPropertyName<'i> {
94  #[inline]
95  fn as_ref(&self) -> &str {
96    match self {
97      CustomPropertyName::Custom(c) => c.as_ref(),
98      CustomPropertyName::Unknown(u) => u.as_ref(),
99    }
100  }
101}
102
103impl<'i> ToCss for CustomPropertyName<'i> {
104  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
105    match self {
106      CustomPropertyName::Custom(c) => c.to_css(dest),
107      CustomPropertyName::Unknown(u) => u.to_css(dest),
108    }
109  }
110}
111
112#[cfg(feature = "serde")]
113#[cfg_attr(docsrs, doc(cfg(feature = "serde")))]
114impl<'i, 'de: 'i> serde::Deserialize<'de> for CustomPropertyName<'i> {
115  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
116  where
117    D: serde::Deserializer<'de>,
118  {
119    let name = CowArcStr::deserialize(deserializer)?;
120    Ok(name.into())
121  }
122}
123
124/// A known property with an unparsed value.
125///
126/// This type is used when the value of a known property could not
127/// be parsed, e.g. in the case css `var()` references are encountered.
128/// In this case, the raw tokens are stored instead.
129#[derive(Debug, Clone, PartialEq)]
130#[cfg_attr(feature = "visitor", derive(Visit))]
131#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
132#[cfg_attr(
133  feature = "serde",
134  derive(serde::Serialize, serde::Deserialize),
135  serde(rename_all = "camelCase")
136)]
137#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
138pub struct UnparsedProperty<'i> {
139  /// The id of the property.
140  pub property_id: PropertyId<'i>,
141  /// The property value, stored as a raw token list.
142  #[cfg_attr(feature = "serde", serde(borrow))]
143  pub value: TokenList<'i>,
144}
145
146impl<'i> UnparsedProperty<'i> {
147  /// Parses a property with the given id as a token list.
148  pub fn parse<'t>(
149    property_id: PropertyId<'i>,
150    input: &mut Parser<'i, 't>,
151    options: &ParserOptions<'i>,
152  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
153    let value = input.parse_until_before(Delimiter::Bang | Delimiter::Semicolon, |input| {
154      TokenList::parse(input, options, 0)
155    })?;
156    Ok(UnparsedProperty { property_id, value })
157  }
158
159  pub(crate) fn get_prefixed(&self, targets: Targets, feature: Feature) -> UnparsedProperty<'i> {
160    let mut clone = self.clone();
161    let prefix = self.property_id.prefix();
162    clone.property_id = clone.property_id.with_prefix(targets.prefixes(prefix.or_none(), feature));
163    clone
164  }
165
166  /// Returns a new UnparsedProperty with the same value and the given property id.
167  pub fn with_property_id(&self, property_id: PropertyId<'i>) -> UnparsedProperty<'i> {
168    UnparsedProperty {
169      property_id,
170      value: self.value.clone(),
171    }
172  }
173
174  /// Substitutes variables and re-parses the property.
175  #[cfg(feature = "substitute_variables")]
176  #[cfg_attr(docsrs, doc(cfg(feature = "substitute_variables")))]
177  pub fn substitute_variables<'x>(
178    mut self,
179    vars: &std::collections::HashMap<&str, TokenList<'i>>,
180  ) -> Result<super::Property<'x>, ()> {
181    use super::Property;
182    use crate::stylesheet::PrinterOptions;
183    use rspack_lightningcss_static_self::IntoOwned;
184
185    // Substitute variables in the token list.
186    self.value.substitute_variables(vars);
187
188    // Now stringify and re-parse the property to its fully parsed form.
189    // Ideally we'd be able to reuse the tokens rather than printing, but cssparser doesn't provide a way to do that.
190    let mut css = String::new();
191    let mut dest = Printer::new(&mut css, PrinterOptions::default());
192    self.value.to_css(&mut dest, false).unwrap();
193    let property =
194      Property::parse_string(self.property_id.clone(), &css, ParserOptions::default()).map_err(|_| ())?;
195    Ok(property.into_owned())
196  }
197}
198
199/// A raw list of CSS tokens, with embedded parsed values.
200#[derive(Debug, Clone, PartialEq, Eq, Hash)]
201#[cfg_attr(feature = "visitor", derive(Visit), visit(visit_token_list, TOKENS))]
202#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
203#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(transparent))]
204#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
205pub struct TokenList<'i>(#[cfg_attr(feature = "serde", serde(borrow))] pub Vec<TokenOrValue<'i>>);
206
207/// A raw CSS token, or a parsed value.
208#[derive(Debug, Clone, PartialEq)]
209#[cfg_attr(feature = "visitor", derive(Visit), visit(visit_token, TOKENS), visit_types(TOKENS | COLORS | URLS | VARIABLES | ENVIRONMENT_VARIABLES | FUNCTIONS | LENGTHS | ANGLES | TIMES | RESOLUTIONS | DASHED_IDENTS))]
210#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
211#[cfg_attr(
212  feature = "serde",
213  derive(serde::Serialize, serde::Deserialize),
214  serde(tag = "type", content = "value", rename_all = "kebab-case")
215)]
216#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
217pub enum TokenOrValue<'i> {
218  /// A token.
219  #[cfg_attr(feature = "serde", serde(borrow))]
220  Token(Token<'i>),
221  /// A parsed CSS color.
222  Color(CssColor),
223  /// A color with unresolved components.
224  UnresolvedColor(UnresolvedColor<'i>),
225  /// A parsed CSS url.
226  Url(Url<'i>),
227  /// A CSS variable reference.
228  Var(Variable<'i>),
229  /// A CSS environment variable reference.
230  Env(EnvironmentVariable<'i>),
231  /// A custom CSS function.
232  Function(Function<'i>),
233  /// A length.
234  Length(LengthValue),
235  /// An angle.
236  Angle(Angle),
237  /// A time.
238  Time(Time),
239  /// A resolution.
240  Resolution(Resolution),
241  /// A dashed ident.
242  DashedIdent(DashedIdent<'i>),
243  /// An animation name.
244  AnimationName(AnimationName<'i>),
245}
246
247impl<'i> From<Token<'i>> for TokenOrValue<'i> {
248  fn from(token: Token<'i>) -> TokenOrValue<'i> {
249    TokenOrValue::Token(token)
250  }
251}
252
253impl<'i> TokenOrValue<'i> {
254  /// Returns whether the token is whitespace.
255  pub fn is_whitespace(&self) -> bool {
256    matches!(self, TokenOrValue::Token(Token::WhiteSpace(_)))
257  }
258}
259
260impl<'a> Eq for TokenOrValue<'a> {}
261
262impl<'a> std::hash::Hash for TokenOrValue<'a> {
263  fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
264    let tag = std::mem::discriminant(self);
265    tag.hash(state);
266    match self {
267      TokenOrValue::Token(t) => t.hash(state),
268      _ => {
269        // This function is primarily used to deduplicate selectors.
270        // Values inside selectors should be exceedingly rare and implementing
271        // Hash for them is somewhat complex due to floating point values.
272        // For now, we just ignore them, which only means there are more
273        // hash collisions. For such a rare case this is probably fine.
274      }
275    }
276  }
277}
278
279impl<'i> ParseWithOptions<'i> for TokenList<'i> {
280  fn parse_with_options<'t>(
281    input: &mut Parser<'i, 't>,
282    options: &ParserOptions<'i>,
283  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
284    TokenList::parse(input, options, 0)
285  }
286}
287
288impl<'i> TokenList<'i> {
289  pub(crate) fn parse<'t>(
290    input: &mut Parser<'i, 't>,
291    options: &ParserOptions<'i>,
292    depth: usize,
293  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
294    let mut tokens = vec![];
295    TokenList::parse_into(input, &mut tokens, options, depth)?;
296
297    // Slice off leading and trailing whitespace if there are at least two tokens.
298    // If there is only one token, we must preserve it. e.g. `--foo: ;` is valid.
299    if tokens.len() >= 2 {
300      let mut slice = &tokens[..];
301      if matches!(tokens.first(), Some(token) if token.is_whitespace()) {
302        slice = &slice[1..];
303      }
304      if matches!(tokens.last(), Some(token) if token.is_whitespace()) {
305        slice = &slice[..slice.len() - 1];
306      }
307      return Ok(TokenList(slice.to_vec()));
308    }
309
310    return Ok(TokenList(tokens));
311  }
312
313  pub(crate) fn parse_raw<'t>(
314    input: &mut Parser<'i, 't>,
315    tokens: &mut Vec<TokenOrValue<'i>>,
316    options: &ParserOptions<'i>,
317    depth: usize,
318  ) -> Result<(), ParseError<'i, ParserError<'i>>> {
319    if depth > 500 {
320      return Err(input.new_custom_error(ParserError::MaximumNestingDepth));
321    }
322
323    loop {
324      let state = input.state();
325      match input.next_including_whitespace_and_comments() {
326        Ok(token @ &cssparser::Token::ParenthesisBlock)
327        | Ok(token @ &cssparser::Token::SquareBracketBlock)
328        | Ok(token @ &cssparser::Token::CurlyBracketBlock) => {
329          tokens.push(Token::from(token).into());
330          let closing_delimiter = match token {
331            cssparser::Token::ParenthesisBlock => Token::CloseParenthesis,
332            cssparser::Token::SquareBracketBlock => Token::CloseSquareBracket,
333            cssparser::Token::CurlyBracketBlock => Token::CloseCurlyBracket,
334            _ => unreachable!(),
335          };
336
337          input.parse_nested_block(|input| TokenList::parse_raw(input, tokens, options, depth + 1))?;
338          tokens.push(closing_delimiter.into());
339        }
340        Ok(token @ &cssparser::Token::Function(_)) => {
341          tokens.push(Token::from(token).into());
342          input.parse_nested_block(|input| TokenList::parse_raw(input, tokens, options, depth + 1))?;
343          tokens.push(Token::CloseParenthesis.into());
344        }
345        Ok(token) if token.is_parse_error() => {
346          return Err(ParseError {
347            kind: ParseErrorKind::Basic(BasicParseErrorKind::UnexpectedToken(token.clone())),
348            location: state.source_location(),
349          })
350        }
351        Ok(token) => {
352          tokens.push(Token::from(token).into());
353        }
354        Err(_) => break,
355      }
356    }
357
358    Ok(())
359  }
360
361  fn parse_into<'t>(
362    input: &mut Parser<'i, 't>,
363    tokens: &mut Vec<TokenOrValue<'i>>,
364    options: &ParserOptions<'i>,
365    depth: usize,
366  ) -> Result<(), ParseError<'i, ParserError<'i>>> {
367    if depth > 500 {
368      return Err(input.new_custom_error(ParserError::MaximumNestingDepth));
369    }
370
371    loop {
372      let state = input.state();
373      match input.next_including_whitespace_and_comments() {
374        Ok(&cssparser::Token::Function(ref f)) => {
375          // Attempt to parse embedded color values into hex tokens.
376          let f = f.into();
377          if let Some(color) = try_parse_color_token(&f, &state, input) {
378            tokens.push(TokenOrValue::Color(color));
379          } else if let Ok(color) = input.try_parse(|input| UnresolvedColor::parse(&f, input, options)) {
380            tokens.push(TokenOrValue::UnresolvedColor(color));
381          } else if f == "url" {
382            input.reset(&state);
383            tokens.push(TokenOrValue::Url(Url::parse(input)?));
384          } else if f == "var" {
385            let var = input.parse_nested_block(|input| {
386              let var = Variable::parse(input, options, depth + 1)?;
387              Ok(TokenOrValue::Var(var))
388            })?;
389            tokens.push(var);
390          } else if f == "env" {
391            let env = input.parse_nested_block(|input| {
392              let env = EnvironmentVariable::parse_nested(input, options, depth + 1)?;
393              Ok(TokenOrValue::Env(env))
394            })?;
395            tokens.push(env);
396          } else {
397            let arguments = input.parse_nested_block(|input| TokenList::parse(input, options, depth + 1))?;
398            tokens.push(TokenOrValue::Function(Function {
399              name: Ident(f),
400              arguments,
401            }));
402          }
403        }
404        Ok(&cssparser::Token::Hash(ref h)) | Ok(&cssparser::Token::IDHash(ref h)) => {
405          if let Ok((r, g, b, a)) = parse_hash_color(h.as_bytes()) {
406            tokens.push(TokenOrValue::Color(CssColor::RGBA(RGBA::new(r, g, b, a))));
407          } else {
408            tokens.push(Token::Hash(h.into()).into());
409          }
410        }
411        Ok(&cssparser::Token::UnquotedUrl(_)) => {
412          input.reset(&state);
413          tokens.push(TokenOrValue::Url(Url::parse(input)?));
414        }
415        Ok(&cssparser::Token::Ident(ref name)) if name.starts_with("--") => {
416          tokens.push(TokenOrValue::DashedIdent(name.into()));
417        }
418        Ok(token @ &cssparser::Token::ParenthesisBlock)
419        | Ok(token @ &cssparser::Token::SquareBracketBlock)
420        | Ok(token @ &cssparser::Token::CurlyBracketBlock) => {
421          tokens.push(Token::from(token).into());
422          let closing_delimiter = match token {
423            cssparser::Token::ParenthesisBlock => Token::CloseParenthesis,
424            cssparser::Token::SquareBracketBlock => Token::CloseSquareBracket,
425            cssparser::Token::CurlyBracketBlock => Token::CloseCurlyBracket,
426            _ => unreachable!(),
427          };
428
429          input.parse_nested_block(|input| TokenList::parse_into(input, tokens, options, depth + 1))?;
430
431          tokens.push(closing_delimiter.into());
432        }
433        Ok(token @ cssparser::Token::Dimension { .. }) => {
434          let value = if let Ok(length) = LengthValue::try_from(token) {
435            TokenOrValue::Length(length)
436          } else if let Ok(angle) = Angle::try_from(token) {
437            TokenOrValue::Angle(angle)
438          } else if let Ok(time) = Time::try_from(token) {
439            TokenOrValue::Time(time)
440          } else if let Ok(resolution) = Resolution::try_from(token) {
441            TokenOrValue::Resolution(resolution)
442          } else {
443            TokenOrValue::Token(token.into())
444          };
445          tokens.push(value);
446        }
447        Ok(token) if token.is_parse_error() => {
448          return Err(ParseError {
449            kind: ParseErrorKind::Basic(BasicParseErrorKind::UnexpectedToken(token.clone())),
450            location: state.source_location(),
451          })
452        }
453        Ok(token) => {
454          tokens.push(Token::from(token).into());
455        }
456        Err(_) => break,
457      }
458    }
459
460    Ok(())
461  }
462}
463
464#[inline]
465fn try_parse_color_token<'i, 't>(
466  f: &CowArcStr<'i>,
467  state: &ParserState,
468  input: &mut Parser<'i, 't>,
469) -> Option<CssColor> {
470  match_ignore_ascii_case! { &*f,
471    "rgb" | "rgba" | "hsl" | "hsla" | "hwb" | "lab" | "lch" | "oklab" | "oklch" | "color" | "color-mix" | "light-dark" | "alpha" => {
472      let s = input.state();
473      input.reset(&state);
474      if let Ok(color) = CssColor::parse(input) {
475        return Some(color)
476      }
477      input.reset(&s);
478    },
479    _ => {}
480  }
481
482  None
483}
484
485impl<'i> TokenList<'i> {
486  pub(crate) fn to_css<PrinterT: crate::printer::PrinterTrait>(
487    &self,
488    dest: &mut PrinterT,
489    is_custom_property: bool,
490  ) -> Result<(), PrinterError> {
491    for token_or_value in self.0.iter() {
492      match token_or_value {
493        TokenOrValue::Color(color) => {
494          color.to_css(dest)?;
495        }
496        TokenOrValue::UnresolvedColor(color) => {
497          color.to_css(dest, is_custom_property)?;
498        }
499        TokenOrValue::Url(url) => {
500          if dest.state().dependencies.is_some() && is_custom_property && !url.is_absolute() {
501            return Err(dest.error(
502              PrinterErrorKind::AmbiguousUrlInCustomProperty {
503                url: url.url.as_ref().to_owned(),
504              },
505              url.loc,
506            ));
507          }
508          url.to_css(dest)?;
509        }
510        TokenOrValue::Var(var) => {
511          var.to_css(dest, is_custom_property)?;
512        }
513        TokenOrValue::Env(env) => {
514          env.to_css(dest, is_custom_property)?;
515        }
516        TokenOrValue::Function(f) => {
517          f.to_css(dest, is_custom_property)?;
518        }
519        TokenOrValue::Length(v) => {
520          // Do not serialize unitless zero lengths in custom properties as it may break calc().
521          let (value, unit) = v.to_unit_value();
522          serialize_dimension(value, unit, dest)?;
523        }
524        TokenOrValue::Angle(v) => {
525          v.to_css(dest)?;
526        }
527        TokenOrValue::Time(v) => {
528          v.to_css(dest)?;
529        }
530        TokenOrValue::Resolution(v) => {
531          v.to_css(dest)?;
532        }
533        TokenOrValue::DashedIdent(v) => {
534          v.to_css(dest)?;
535        }
536        TokenOrValue::AnimationName(v) => {
537          v.to_css(dest)?;
538        }
539        TokenOrValue::Token(token) => match token {
540          Token::Dimension { value, unit, .. } => {
541            serialize_dimension(*value, unit, dest)?;
542          }
543          Token::Number { value, .. } => {
544            value.to_css(dest)?;
545          }
546          _ => {
547            token.to_css(dest)?;
548          }
549        },
550      };
551    }
552
553    Ok(())
554  }
555
556  pub(crate) fn to_css_raw<PrinterT: crate::printer::PrinterTrait>(
557    &self,
558    dest: &mut PrinterT,
559  ) -> Result<(), PrinterError> {
560    for token_or_value in &self.0 {
561      match token_or_value {
562        TokenOrValue::Token(token) => {
563          token.to_css(dest)?;
564        }
565        _ => {
566          return Err(PrinterError {
567            kind: PrinterErrorKind::FmtError,
568            loc: None,
569          })
570        }
571      }
572    }
573
574    Ok(())
575  }
576
577  pub(crate) fn starts_with_whitespace(&self) -> bool {
578    matches!(self.0.get(0), Some(TokenOrValue::Token(Token::WhiteSpace(_))))
579  }
580}
581
582/// A raw CSS token.
583// Copied from cssparser to change CowRcStr to CowArcStr
584#[derive(Debug, Clone, PartialEq)]
585#[cfg_attr(feature = "visitor", derive(Visit))]
586#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
587#[cfg_attr(
588  feature = "serde",
589  derive(serde::Serialize, serde::Deserialize),
590  serde(tag = "type", rename_all = "kebab-case")
591)]
592#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
593pub enum Token<'a> {
594  /// A [`<ident-token>`](https://drafts.csswg.org/css-syntax/#ident-token-diagram)
595  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<CowArcStr>"))]
596  Ident(#[cfg_attr(feature = "serde", serde(borrow))] CowArcStr<'a>),
597
598  /// A [`<at-keyword-token>`](https://drafts.csswg.org/css-syntax/#at-keyword-token-diagram)
599  ///
600  /// The value does not include the `@` marker.
601  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<CowArcStr>"))]
602  AtKeyword(CowArcStr<'a>),
603
604  /// A [`<hash-token>`](https://drafts.csswg.org/css-syntax/#hash-token-diagram) with the type flag set to "unrestricted"
605  ///
606  /// The value does not include the `#` marker.
607  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<CowArcStr>"))]
608  Hash(CowArcStr<'a>),
609
610  /// A [`<hash-token>`](https://drafts.csswg.org/css-syntax/#hash-token-diagram) with the type flag set to "id"
611  ///
612  /// The value does not include the `#` marker.
613  #[cfg_attr(feature = "serde", serde(rename = "id-hash", with = "ValueWrapper::<CowArcStr>"))]
614  IDHash(CowArcStr<'a>), // Hash that is a valid ID selector.
615
616  /// A [`<string-token>`](https://drafts.csswg.org/css-syntax/#string-token-diagram)
617  ///
618  /// The value does not include the quotes.
619  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<CowArcStr>"))]
620  String(CowArcStr<'a>),
621
622  /// A [`<url-token>`](https://drafts.csswg.org/css-syntax/#url-token-diagram)
623  ///
624  /// The value does not include the `url(` `)` markers.  Note that `url( <string-token> )` is represented by a
625  /// `Function` token.
626  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<CowArcStr>"))]
627  UnquotedUrl(CowArcStr<'a>),
628
629  /// A `<delim-token>`
630  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<char>"))]
631  Delim(char),
632
633  /// A [`<number-token>`](https://drafts.csswg.org/css-syntax/#number-token-diagram)
634  Number {
635    /// Whether the number had a `+` or `-` sign.
636    ///
637    /// This is used is some cases like the <An+B> micro syntax. (See the `parse_nth` function.)
638    #[cfg_attr(feature = "serde", serde(skip))]
639    has_sign: bool,
640
641    /// The value as a float
642    value: f32,
643
644    /// If the origin source did not include a fractional part, the value as an integer.
645    #[cfg_attr(feature = "serde", serde(skip))]
646    int_value: Option<i32>,
647  },
648
649  /// A [`<percentage-token>`](https://drafts.csswg.org/css-syntax/#percentage-token-diagram)
650  Percentage {
651    /// Whether the number had a `+` or `-` sign.
652    #[cfg_attr(feature = "serde", serde(skip))]
653    has_sign: bool,
654
655    /// The value as a float, divided by 100 so that the nominal range is 0.0 to 1.0.
656    #[cfg_attr(feature = "serde", serde(rename = "value"))]
657    unit_value: f32,
658
659    /// If the origin source did not include a fractional part, the value as an integer.
660    /// It is **not** divided by 100.
661    #[cfg_attr(feature = "serde", serde(skip))]
662    int_value: Option<i32>,
663  },
664
665  /// A [`<dimension-token>`](https://drafts.csswg.org/css-syntax/#dimension-token-diagram)
666  Dimension {
667    /// Whether the number had a `+` or `-` sign.
668    ///
669    /// This is used is some cases like the <An+B> micro syntax. (See the `parse_nth` function.)
670    #[cfg_attr(feature = "serde", serde(skip))]
671    has_sign: bool,
672
673    /// The value as a float
674    value: f32,
675
676    /// If the origin source did not include a fractional part, the value as an integer.
677    #[cfg_attr(feature = "serde", serde(skip))]
678    int_value: Option<i32>,
679
680    /// The unit, e.g. "px" in `12px`
681    unit: CowArcStr<'a>,
682  },
683
684  /// A [`<whitespace-token>`](https://drafts.csswg.org/css-syntax/#whitespace-token-diagram)
685  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<CowArcStr>"))]
686  WhiteSpace(CowArcStr<'a>),
687
688  /// A comment.
689  ///
690  /// The CSS Syntax spec does not generate tokens for comments,
691  /// But we do, because we can (borrowed &str makes it cheap).
692  ///
693  /// The value does not include the `/*` `*/` markers.
694  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<CowArcStr>"))]
695  Comment(CowArcStr<'a>),
696
697  /// A `:` `<colon-token>`
698  Colon, // :
699
700  /// A `;` `<semicolon-token>`
701  Semicolon, // ;
702
703  /// A `,` `<comma-token>`
704  Comma, // ,
705
706  /// A `~=` [`<include-match-token>`](https://drafts.csswg.org/css-syntax/#include-match-token-diagram)
707  IncludeMatch,
708
709  /// A `|=` [`<dash-match-token>`](https://drafts.csswg.org/css-syntax/#dash-match-token-diagram)
710  DashMatch,
711
712  /// A `^=` [`<prefix-match-token>`](https://drafts.csswg.org/css-syntax/#prefix-match-token-diagram)
713  PrefixMatch,
714
715  /// A `$=` [`<suffix-match-token>`](https://drafts.csswg.org/css-syntax/#suffix-match-token-diagram)
716  SuffixMatch,
717
718  /// A `*=` [`<substring-match-token>`](https://drafts.csswg.org/css-syntax/#substring-match-token-diagram)
719  SubstringMatch,
720
721  /// A `<!--` [`<CDO-token>`](https://drafts.csswg.org/css-syntax/#CDO-token-diagram)
722  #[cfg_attr(feature = "serde", serde(rename = "cdo"))]
723  CDO,
724
725  /// A `-->` [`<CDC-token>`](https://drafts.csswg.org/css-syntax/#CDC-token-diagram)
726  #[cfg_attr(feature = "serde", serde(rename = "cdc"))]
727  CDC,
728
729  /// A [`<function-token>`](https://drafts.csswg.org/css-syntax/#function-token-diagram)
730  ///
731  /// The value (name) does not include the `(` marker.
732  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<CowArcStr>"))]
733  Function(CowArcStr<'a>),
734
735  /// A `<(-token>`
736  ParenthesisBlock,
737
738  /// A `<[-token>`
739  SquareBracketBlock,
740
741  /// A `<{-token>`
742  CurlyBracketBlock,
743
744  /// A `<bad-url-token>`
745  ///
746  /// This token always indicates a parse error.
747  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<CowArcStr>"))]
748  BadUrl(CowArcStr<'a>),
749
750  /// A `<bad-string-token>`
751  ///
752  /// This token always indicates a parse error.
753  #[cfg_attr(feature = "serde", serde(with = "ValueWrapper::<CowArcStr>"))]
754  BadString(CowArcStr<'a>),
755
756  /// A `<)-token>`
757  ///
758  /// When obtained from one of the `Parser::next*` methods,
759  /// this token is always unmatched and indicates a parse error.
760  CloseParenthesis,
761
762  /// A `<]-token>`
763  ///
764  /// When obtained from one of the `Parser::next*` methods,
765  /// this token is always unmatched and indicates a parse error.
766  CloseSquareBracket,
767
768  /// A `<}-token>`
769  ///
770  /// When obtained from one of the `Parser::next*` methods,
771  /// this token is always unmatched and indicates a parse error.
772  CloseCurlyBracket,
773}
774
775impl<'a> From<&cssparser::Token<'a>> for Token<'a> {
776  #[inline]
777  fn from(t: &cssparser::Token<'a>) -> Token<'a> {
778    match t {
779      cssparser::Token::Ident(x) => Token::Ident(x.into()),
780      cssparser::Token::AtKeyword(x) => Token::AtKeyword(x.into()),
781      cssparser::Token::Hash(x) => Token::Hash(x.into()),
782      cssparser::Token::IDHash(x) => Token::IDHash(x.into()),
783      cssparser::Token::QuotedString(x) => Token::String(x.into()),
784      cssparser::Token::UnquotedUrl(x) => Token::UnquotedUrl(x.into()),
785      cssparser::Token::Function(x) => Token::Function(x.into()),
786      cssparser::Token::BadUrl(x) => Token::BadUrl(x.into()),
787      cssparser::Token::BadString(x) => Token::BadString(x.into()),
788      cssparser::Token::Delim(c) => Token::Delim(*c),
789      cssparser::Token::Number {
790        has_sign,
791        value,
792        int_value,
793      } => Token::Number {
794        has_sign: *has_sign,
795        value: *value,
796        int_value: *int_value,
797      },
798      cssparser::Token::Dimension {
799        has_sign,
800        value,
801        int_value,
802        unit,
803      } => Token::Dimension {
804        has_sign: *has_sign,
805        value: *value,
806        int_value: *int_value,
807        unit: unit.into(),
808      },
809      cssparser::Token::Percentage {
810        has_sign,
811        unit_value,
812        int_value,
813      } => Token::Percentage {
814        has_sign: *has_sign,
815        unit_value: *unit_value,
816        int_value: *int_value,
817      },
818      cssparser::Token::WhiteSpace(w) => Token::WhiteSpace((*w).into()),
819      cssparser::Token::Comment(c) => Token::Comment((*c).into()),
820      cssparser::Token::Colon => Token::Colon,
821      cssparser::Token::Semicolon => Token::Semicolon,
822      cssparser::Token::Comma => Token::Comma,
823      cssparser::Token::IncludeMatch => Token::IncludeMatch,
824      cssparser::Token::DashMatch => Token::DashMatch,
825      cssparser::Token::PrefixMatch => Token::PrefixMatch,
826      cssparser::Token::SuffixMatch => Token::SuffixMatch,
827      cssparser::Token::SubstringMatch => Token::SubstringMatch,
828      cssparser::Token::CDO => Token::CDO,
829      cssparser::Token::CDC => Token::CDC,
830      cssparser::Token::ParenthesisBlock => Token::ParenthesisBlock,
831      cssparser::Token::SquareBracketBlock => Token::SquareBracketBlock,
832      cssparser::Token::CurlyBracketBlock => Token::CurlyBracketBlock,
833      cssparser::Token::CloseParenthesis => Token::CloseParenthesis,
834      cssparser::Token::CloseSquareBracket => Token::CloseSquareBracket,
835      cssparser::Token::CloseCurlyBracket => Token::CloseCurlyBracket,
836    }
837  }
838}
839
840impl<'a> ToCss for Token<'a> {
841  #[inline]
842  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
843    use cssparser::ToCss;
844    match self {
845      Token::Ident(x) => cssparser::Token::Ident(x.as_ref().into()).to_css(dest)?,
846      Token::AtKeyword(x) => cssparser::Token::AtKeyword(x.as_ref().into()).to_css(dest)?,
847      Token::Hash(x) => cssparser::Token::Hash(x.as_ref().into()).to_css(dest)?,
848      Token::IDHash(x) => cssparser::Token::IDHash(x.as_ref().into()).to_css(dest)?,
849      Token::String(x) => cssparser::Token::QuotedString(x.as_ref().into()).to_css(dest)?,
850      Token::UnquotedUrl(x) => cssparser::Token::UnquotedUrl(x.as_ref().into()).to_css(dest)?,
851      Token::Function(x) => cssparser::Token::Function(x.as_ref().into()).to_css(dest)?,
852      Token::BadUrl(x) => cssparser::Token::BadUrl(x.as_ref().into()).to_css(dest)?,
853      Token::BadString(x) => cssparser::Token::BadString(x.as_ref().into()).to_css(dest)?,
854      Token::Delim(c) => cssparser::Token::Delim(*c).to_css(dest)?,
855      Token::Number {
856        has_sign,
857        value,
858        int_value,
859      } => cssparser::Token::Number {
860        has_sign: *has_sign,
861        value: *value,
862        int_value: *int_value,
863      }
864      .to_css(dest)?,
865      Token::Dimension {
866        has_sign,
867        value,
868        int_value,
869        unit,
870      } => cssparser::Token::Dimension {
871        has_sign: *has_sign,
872        value: *value,
873        int_value: *int_value,
874        unit: unit.as_ref().into(),
875      }
876      .to_css(dest)?,
877      Token::Percentage {
878        has_sign,
879        unit_value,
880        int_value,
881      } => cssparser::Token::Percentage {
882        has_sign: *has_sign,
883        unit_value: *unit_value,
884        int_value: *int_value,
885      }
886      .to_css(dest)?,
887      Token::WhiteSpace(w) => {
888        if dest.options().minify {
889          dest.write_char(' ')?;
890        } else {
891          dest.write_str(&w)?;
892        }
893      }
894      Token::Comment(c) => {
895        if !dest.options().minify {
896          cssparser::Token::Comment(c).to_css(dest)?;
897        }
898      }
899      Token::Colon => cssparser::Token::Colon.to_css(dest)?,
900      Token::Semicolon => cssparser::Token::Semicolon.to_css(dest)?,
901      Token::Comma => cssparser::Token::Comma.to_css(dest)?,
902      Token::IncludeMatch => cssparser::Token::IncludeMatch.to_css(dest)?,
903      Token::DashMatch => cssparser::Token::DashMatch.to_css(dest)?,
904      Token::PrefixMatch => cssparser::Token::PrefixMatch.to_css(dest)?,
905      Token::SuffixMatch => cssparser::Token::SuffixMatch.to_css(dest)?,
906      Token::SubstringMatch => cssparser::Token::SubstringMatch.to_css(dest)?,
907      Token::CDO => cssparser::Token::CDO.to_css(dest)?,
908      Token::CDC => cssparser::Token::CDC.to_css(dest)?,
909      Token::ParenthesisBlock => cssparser::Token::ParenthesisBlock.to_css(dest)?,
910      Token::SquareBracketBlock => cssparser::Token::SquareBracketBlock.to_css(dest)?,
911      Token::CurlyBracketBlock => cssparser::Token::CurlyBracketBlock.to_css(dest)?,
912      Token::CloseParenthesis => cssparser::Token::CloseParenthesis.to_css(dest)?,
913      Token::CloseSquareBracket => cssparser::Token::CloseSquareBracket.to_css(dest)?,
914      Token::CloseCurlyBracket => cssparser::Token::CloseCurlyBracket.to_css(dest)?,
915    }
916
917    Ok(())
918  }
919}
920
921impl<'a> Eq for Token<'a> {}
922
923impl<'a> std::hash::Hash for Token<'a> {
924  fn hash<H: std::hash::Hasher>(&self, state: &mut H) {
925    let tag = std::mem::discriminant(self);
926    tag.hash(state);
927    match self {
928      Token::Ident(x) => x.hash(state),
929      Token::AtKeyword(x) => x.hash(state),
930      Token::Hash(x) => x.hash(state),
931      Token::IDHash(x) => x.hash(state),
932      Token::String(x) => x.hash(state),
933      Token::UnquotedUrl(x) => x.hash(state),
934      Token::Function(x) => x.hash(state),
935      Token::BadUrl(x) => x.hash(state),
936      Token::BadString(x) => x.hash(state),
937      Token::Delim(x) => x.hash(state),
938      Token::Number {
939        has_sign,
940        value,
941        int_value,
942      } => {
943        has_sign.hash(state);
944        integer_decode(*value).hash(state);
945        int_value.hash(state);
946      }
947      Token::Dimension {
948        has_sign,
949        value,
950        int_value,
951        unit,
952      } => {
953        has_sign.hash(state);
954        integer_decode(*value).hash(state);
955        int_value.hash(state);
956        unit.hash(state);
957      }
958      Token::Percentage {
959        has_sign,
960        unit_value,
961        int_value,
962      } => {
963        has_sign.hash(state);
964        integer_decode(*unit_value).hash(state);
965        int_value.hash(state);
966      }
967      Token::WhiteSpace(w) => w.hash(state),
968      Token::Comment(c) => c.hash(state),
969      Token::Colon
970      | Token::Semicolon
971      | Token::Comma
972      | Token::IncludeMatch
973      | Token::DashMatch
974      | Token::PrefixMatch
975      | Token::SuffixMatch
976      | Token::SubstringMatch
977      | Token::CDO
978      | Token::CDC
979      | Token::ParenthesisBlock
980      | Token::SquareBracketBlock
981      | Token::CurlyBracketBlock
982      | Token::CloseParenthesis
983      | Token::CloseSquareBracket
984      | Token::CloseCurlyBracket => {}
985    }
986  }
987}
988
989/// Converts a floating point value into its mantissa, exponent,
990/// and sign components so that it can be hashed.
991fn integer_decode(v: f32) -> (u32, i16, i8) {
992  let bits: u32 = f32::to_bits(v);
993  let sign: i8 = if bits >> 31 == 0 { 1 } else { -1 };
994  let mut exponent: i16 = ((bits >> 23) & 0xff) as i16;
995  let mantissa = if exponent == 0 {
996    (bits & 0x7fffff) << 1
997  } else {
998    (bits & 0x7fffff) | 0x800000
999  };
1000  // Exponent bias + mantissa shift
1001  exponent -= 127 + 23;
1002  (mantissa, exponent, sign)
1003}
1004
1005impl<'i> TokenList<'i> {
1006  pub(crate) fn get_necessary_fallbacks(&self, targets: Targets) -> ColorFallbackKind {
1007    let mut fallbacks = ColorFallbackKind::empty();
1008    for token in &self.0 {
1009      match token {
1010        TokenOrValue::Color(color) => {
1011          fallbacks |= color.get_possible_fallbacks(targets);
1012        }
1013        TokenOrValue::Function(f) => {
1014          fallbacks |= f.arguments.get_necessary_fallbacks(targets);
1015        }
1016        TokenOrValue::Var(v) => {
1017          if let Some(fallback) = &v.fallback {
1018            fallbacks |= fallback.get_necessary_fallbacks(targets);
1019          }
1020        }
1021        TokenOrValue::Env(v) => {
1022          if let Some(fallback) = &v.fallback {
1023            fallbacks |= fallback.get_necessary_fallbacks(targets);
1024          }
1025        }
1026        _ => {}
1027      }
1028    }
1029
1030    fallbacks
1031  }
1032
1033  pub(crate) fn get_fallback(&self, kind: ColorFallbackKind) -> Self {
1034    let tokens = self
1035      .0
1036      .iter()
1037      .map(|token| match token {
1038        TokenOrValue::Color(color) => TokenOrValue::Color(color.get_fallback(kind)),
1039        TokenOrValue::Function(f) => TokenOrValue::Function(f.get_fallback(kind)),
1040        TokenOrValue::Var(v) => TokenOrValue::Var(v.get_fallback(kind)),
1041        TokenOrValue::Env(e) => TokenOrValue::Env(e.get_fallback(kind)),
1042        _ => token.clone(),
1043      })
1044      .collect();
1045    TokenList(tokens)
1046  }
1047
1048  pub(crate) fn get_fallbacks(&mut self, targets: Targets) -> Vec<(SupportsCondition<'i>, Self)> {
1049    // Get the full list of possible fallbacks, and remove the lowest one, which will replace
1050    // the original declaration. The remaining fallbacks need to be added as @supports rules.
1051    let mut fallbacks = self.get_necessary_fallbacks(targets);
1052    let lowest_fallback = fallbacks.lowest();
1053    fallbacks.remove(lowest_fallback);
1054
1055    let mut res = Vec::new();
1056    if fallbacks.contains(ColorFallbackKind::P3) {
1057      res.push((
1058        ColorFallbackKind::P3.supports_condition(),
1059        self.get_fallback(ColorFallbackKind::P3),
1060      ));
1061    }
1062
1063    if fallbacks.contains(ColorFallbackKind::LAB) {
1064      res.push((
1065        ColorFallbackKind::LAB.supports_condition(),
1066        self.get_fallback(ColorFallbackKind::LAB),
1067      ));
1068    }
1069
1070    if !lowest_fallback.is_empty() {
1071      for token in self.0.iter_mut() {
1072        match token {
1073          TokenOrValue::Color(color) => {
1074            *color = color.get_fallback(lowest_fallback);
1075          }
1076          TokenOrValue::Function(f) => *f = f.get_fallback(lowest_fallback),
1077          TokenOrValue::Var(v) if v.fallback.is_some() => *v = v.get_fallback(lowest_fallback),
1078          TokenOrValue::Env(v) if v.fallback.is_some() => *v = v.get_fallback(lowest_fallback),
1079          _ => {}
1080        }
1081      }
1082    }
1083
1084    res
1085  }
1086
1087  pub(crate) fn get_features(&self) -> Features {
1088    let mut features = Features::empty();
1089    for token in &self.0 {
1090      match token {
1091        TokenOrValue::Color(color) => {
1092          features |= color.get_features();
1093        }
1094        TokenOrValue::UnresolvedColor(unresolved_color) => {
1095          features |= Features::SpaceSeparatedColorNotation;
1096          match unresolved_color {
1097            UnresolvedColor::LightDark { light, dark } => {
1098              features |= Features::LightDark;
1099              features |= light.get_features();
1100              features |= dark.get_features();
1101            }
1102            _ => {}
1103          }
1104        }
1105        TokenOrValue::Function(f) => {
1106          features |= f.arguments.get_features();
1107        }
1108        TokenOrValue::Var(v) => {
1109          if let Some(fallback) = &v.fallback {
1110            features |= fallback.get_features();
1111          }
1112        }
1113        TokenOrValue::Env(v) => {
1114          if let Some(fallback) = &v.fallback {
1115            features |= fallback.get_features();
1116          }
1117        }
1118        _ => {}
1119      }
1120    }
1121
1122    features
1123  }
1124
1125  /// Substitutes variables with the provided values.
1126  #[cfg(feature = "substitute_variables")]
1127  #[cfg_attr(docsrs, doc(cfg(feature = "substitute_variables")))]
1128  pub fn substitute_variables(&mut self, vars: &std::collections::HashMap<&str, TokenList<'i>>) {
1129    self.visit(&mut VarInliner { vars }).unwrap()
1130  }
1131}
1132
1133#[cfg(feature = "substitute_variables")]
1134struct VarInliner<'a, 'i> {
1135  vars: &'a std::collections::HashMap<&'a str, TokenList<'i>>,
1136}
1137
1138#[cfg(feature = "substitute_variables")]
1139impl<'a, 'i> crate::visitor::Visitor<'i> for VarInliner<'a, 'i> {
1140  type Error = std::convert::Infallible;
1141
1142  fn visit_types(&self) -> crate::visitor::VisitTypes {
1143    crate::visit_types!(TOKENS | VARIABLES)
1144  }
1145
1146  fn visit_token_list(&mut self, tokens: &mut TokenList<'i>) -> Result<(), Self::Error> {
1147    let mut i = 0;
1148    let mut seen = std::collections::HashSet::new();
1149    while i < tokens.0.len() {
1150      let token = &mut tokens.0[i];
1151      token.visit(self).unwrap();
1152      if let TokenOrValue::Var(var) = token {
1153        if let Some(value) = self.vars.get(var.name.ident.0.as_ref()) {
1154          // Ignore circular references.
1155          if seen.insert(var.name.ident.0.clone()) {
1156            tokens.0.splice(i..i + 1, value.0.iter().cloned());
1157            // Don't advance. We need to replace any variables in the value.
1158            continue;
1159          }
1160        } else if let Some(fallback) = &var.fallback {
1161          let fallback = fallback.0.clone();
1162          if seen.insert(var.name.ident.0.clone()) {
1163            tokens.0.splice(i..i + 1, fallback.into_iter());
1164            continue;
1165          }
1166        }
1167      }
1168      seen.clear();
1169      i += 1;
1170    }
1171    Ok(())
1172  }
1173}
1174
1175/// A CSS variable reference.
1176#[derive(Debug, Clone, PartialEq)]
1177#[cfg_attr(feature = "visitor", derive(Visit))]
1178#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1179#[cfg_attr(feature = "visitor", visit(visit_variable, VARIABLES))]
1180#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1181#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1182pub struct Variable<'i> {
1183  /// The variable name.
1184  #[cfg_attr(feature = "serde", serde(borrow))]
1185  pub name: DashedIdentReference<'i>,
1186  /// A fallback value in case the variable is not defined.
1187  pub fallback: Option<TokenList<'i>>,
1188}
1189
1190impl<'i> Variable<'i> {
1191  fn parse<'t>(
1192    input: &mut Parser<'i, 't>,
1193    options: &ParserOptions<'i>,
1194    depth: usize,
1195  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1196    let name = DashedIdentReference::parse_with_options(input, options)?;
1197
1198    let fallback = if input.try_parse(|input| input.expect_comma()).is_ok() {
1199      Some(TokenList::parse(input, options, depth)?)
1200    } else {
1201      None
1202    };
1203
1204    Ok(Variable { name, fallback })
1205  }
1206
1207  fn to_css<PrinterT: crate::printer::PrinterTrait>(
1208    &self,
1209    dest: &mut PrinterT,
1210    is_custom_property: bool,
1211  ) -> Result<(), PrinterError> {
1212    dest.write_str("var(")?;
1213    self.name.to_css(dest)?;
1214    if let Some(fallback) = &self.fallback {
1215      dest.write_char(',')?;
1216      if !fallback.starts_with_whitespace() {
1217        dest.whitespace()?;
1218      }
1219      fallback.to_css(dest, is_custom_property)?;
1220    }
1221    dest.write_char(')')?;
1222    Ok(())
1223  }
1224
1225  fn get_fallback(&self, kind: ColorFallbackKind) -> Self {
1226    Variable {
1227      name: self.name.clone(),
1228      fallback: self.fallback.as_ref().map(|fallback| fallback.get_fallback(kind)),
1229    }
1230  }
1231}
1232
1233/// A CSS environment variable reference.
1234#[derive(Debug, Clone, PartialEq)]
1235#[cfg_attr(
1236  feature = "visitor",
1237  derive(Visit),
1238  visit(visit_environment_variable, ENVIRONMENT_VARIABLES)
1239)]
1240#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1241#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1242#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1243pub struct EnvironmentVariable<'i> {
1244  /// The environment variable name.
1245  #[cfg_attr(feature = "serde", serde(borrow))]
1246  pub name: EnvironmentVariableName<'i>,
1247  /// Optional indices into the dimensions of the environment variable.
1248  #[cfg_attr(feature = "serde", serde(default))]
1249  pub indices: Vec<CSSInteger>,
1250  /// A fallback value in case the variable is not defined.
1251  pub fallback: Option<TokenList<'i>>,
1252}
1253
1254/// A CSS environment variable name.
1255#[derive(Debug, Clone, PartialEq)]
1256#[cfg_attr(feature = "visitor", derive(Visit))]
1257#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1258#[cfg_attr(
1259  feature = "serde",
1260  derive(serde::Serialize, serde::Deserialize),
1261  serde(tag = "type", rename_all = "lowercase")
1262)]
1263#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1264pub enum EnvironmentVariableName<'i> {
1265  /// A UA-defined environment variable.
1266  #[cfg_attr(
1267    feature = "serde",
1268    serde(with = "crate::serialization::ValueWrapper::<UAEnvironmentVariable>")
1269  )]
1270  UA(UAEnvironmentVariable),
1271  /// A custom author-defined environment variable.
1272  #[cfg_attr(feature = "serde", serde(borrow))]
1273  Custom(DashedIdentReference<'i>),
1274  /// An unknown environment variable.
1275  #[cfg_attr(feature = "serde", serde(with = "crate::serialization::ValueWrapper::<CustomIdent>"))]
1276  Unknown(CustomIdent<'i>),
1277}
1278
1279enum_property! {
1280  /// A UA-defined environment variable name.
1281  pub enum UAEnvironmentVariable {
1282    /// The safe area inset from the top of the viewport.
1283    SafeAreaInsetTop,
1284    /// The safe area inset from the right of the viewport.
1285    SafeAreaInsetRight,
1286    /// The safe area inset from the bottom of the viewport.
1287    SafeAreaInsetBottom,
1288    /// The safe area inset from the left of the viewport.
1289    SafeAreaInsetLeft,
1290    /// The viewport segment width.
1291    ViewportSegmentWidth,
1292    /// The viewport segment height.
1293    ViewportSegmentHeight,
1294    /// The viewport segment top position.
1295    ViewportSegmentTop,
1296    /// The viewport segment left position.
1297    ViewportSegmentLeft,
1298    /// The viewport segment bottom position.
1299    ViewportSegmentBottom,
1300    /// The viewport segment right position.
1301    ViewportSegmentRight,
1302  }
1303}
1304
1305impl<'i> EnvironmentVariableName<'i> {
1306  /// Returns the name of the environment variable as a string.
1307  pub fn name(&self) -> &str {
1308    match self {
1309      EnvironmentVariableName::UA(ua) => ua.as_str(),
1310      EnvironmentVariableName::Custom(c) => c.ident.as_ref(),
1311      EnvironmentVariableName::Unknown(u) => u.0.as_ref(),
1312    }
1313  }
1314}
1315
1316impl<'i> Parse<'i> for EnvironmentVariableName<'i> {
1317  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1318    if let Ok(ua) = input.try_parse(UAEnvironmentVariable::parse) {
1319      return Ok(EnvironmentVariableName::UA(ua));
1320    }
1321
1322    if let Ok(dashed) =
1323      input.try_parse(|input| DashedIdentReference::parse_with_options(input, &ParserOptions::default()))
1324    {
1325      return Ok(EnvironmentVariableName::Custom(dashed));
1326    }
1327
1328    let ident = CustomIdent::parse(input)?;
1329    return Ok(EnvironmentVariableName::Unknown(ident));
1330  }
1331}
1332
1333impl<'i> ToCss for EnvironmentVariableName<'i> {
1334  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
1335    match self {
1336      EnvironmentVariableName::UA(ua) => ua.to_css(dest),
1337      EnvironmentVariableName::Custom(custom) => custom.to_css(dest),
1338      EnvironmentVariableName::Unknown(unknown) => unknown.to_css(dest),
1339    }
1340  }
1341}
1342
1343impl<'i> EnvironmentVariable<'i> {
1344  pub(crate) fn parse<'t>(
1345    input: &mut Parser<'i, 't>,
1346    options: &ParserOptions<'i>,
1347    depth: usize,
1348  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1349    input.expect_function_matching("env")?;
1350    input.parse_nested_block(|input| Self::parse_nested(input, options, depth))
1351  }
1352
1353  pub(crate) fn parse_nested<'t>(
1354    input: &mut Parser<'i, 't>,
1355    options: &ParserOptions<'i>,
1356    depth: usize,
1357  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1358    let name = EnvironmentVariableName::parse(input)?;
1359    let mut indices = Vec::new();
1360    while let Ok(index) = input.try_parse(CSSInteger::parse) {
1361      indices.push(index);
1362    }
1363
1364    let fallback = if input.try_parse(|input| input.expect_comma()).is_ok() {
1365      Some(TokenList::parse(input, options, depth + 1)?)
1366    } else {
1367      None
1368    };
1369
1370    Ok(EnvironmentVariable {
1371      name,
1372      indices,
1373      fallback,
1374    })
1375  }
1376
1377  pub(crate) fn to_css<PrinterT: crate::printer::PrinterTrait>(
1378    &self,
1379    dest: &mut PrinterT,
1380    is_custom_property: bool,
1381  ) -> Result<(), PrinterError> {
1382    dest.write_str("env(")?;
1383    self.name.to_css(dest)?;
1384
1385    for item in &self.indices {
1386      dest.write_char(' ')?;
1387      item.to_css(dest)?;
1388    }
1389
1390    if let Some(fallback) = &self.fallback {
1391      dest.write_char(',')?;
1392      if !fallback.starts_with_whitespace() {
1393        dest.whitespace()?;
1394      }
1395      fallback.to_css(dest, is_custom_property)?;
1396    }
1397    dest.write_char(')')?;
1398    Ok(())
1399  }
1400
1401  fn get_fallback(&self, kind: ColorFallbackKind) -> Self {
1402    EnvironmentVariable {
1403      name: self.name.clone(),
1404      indices: self.indices.clone(),
1405      fallback: self.fallback.as_ref().map(|fallback| fallback.get_fallback(kind)),
1406    }
1407  }
1408}
1409
1410/// A custom CSS function.
1411#[derive(Debug, Clone, PartialEq)]
1412#[cfg_attr(feature = "visitor", derive(Visit))]
1413#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1414#[cfg_attr(feature = "visitor", visit(visit_function, FUNCTIONS))]
1415#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
1416#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1417pub struct Function<'i> {
1418  /// The function name.
1419  #[cfg_attr(feature = "serde", serde(borrow))]
1420  pub name: Ident<'i>,
1421  /// The function arguments.
1422  pub arguments: TokenList<'i>,
1423}
1424
1425impl<'i> Function<'i> {
1426  fn to_css<PrinterT: crate::printer::PrinterTrait>(
1427    &self,
1428    dest: &mut PrinterT,
1429    is_custom_property: bool,
1430  ) -> Result<(), PrinterError> {
1431    self.name.to_css(dest)?;
1432    dest.write_char('(')?;
1433    self.arguments.to_css(dest, is_custom_property)?;
1434    dest.write_char(')')?;
1435    Ok(())
1436  }
1437
1438  fn get_fallback(&self, kind: ColorFallbackKind) -> Self {
1439    Function {
1440      name: self.name.clone(),
1441      arguments: self.arguments.get_fallback(kind),
1442    }
1443  }
1444}
1445
1446/// A color value with an unresolved alpha value (e.g. a variable).
1447/// These can be converted from the modern slash syntax to older comma syntax.
1448/// This can only be done when the only unresolved component is the alpha
1449/// since variables can resolve to multiple tokens.
1450#[derive(Debug, Clone, PartialEq)]
1451#[cfg_attr(feature = "visitor", derive(Visit))]
1452#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
1453#[cfg_attr(
1454  feature = "serde",
1455  derive(serde::Serialize, serde::Deserialize),
1456  serde(tag = "type", rename_all = "lowercase")
1457)]
1458#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
1459pub enum UnresolvedColor<'i> {
1460  /// An rgb() color.
1461  RGB {
1462    /// The red component.
1463    r: f32,
1464    /// The green component.
1465    g: f32,
1466    /// The blue component.
1467    b: f32,
1468    /// The unresolved alpha component.
1469    #[cfg_attr(feature = "serde", serde(borrow))]
1470    alpha: TokenList<'i>,
1471  },
1472  /// An hsl() color.
1473  HSL {
1474    /// The hue component.
1475    h: f32,
1476    /// The saturation component.
1477    s: f32,
1478    /// The lightness component.
1479    l: f32,
1480    /// The unresolved alpha component.
1481    #[cfg_attr(feature = "serde", serde(borrow))]
1482    alpha: TokenList<'i>,
1483  },
1484  /// The light-dark() function.
1485  #[cfg_attr(feature = "serde", serde(rename = "light-dark"))]
1486  LightDark {
1487    /// The light value.
1488    light: TokenList<'i>,
1489    /// The dark value.
1490    dark: TokenList<'i>,
1491  },
1492}
1493
1494impl<'i> LightDarkColor for UnresolvedColor<'i> {
1495  #[inline]
1496  fn light_dark(light: Self, dark: Self) -> Self {
1497    UnresolvedColor::LightDark {
1498      light: TokenList(vec![TokenOrValue::UnresolvedColor(light)]),
1499      dark: TokenList(vec![TokenOrValue::UnresolvedColor(dark)]),
1500    }
1501  }
1502}
1503
1504impl<'i> UnresolvedColor<'i> {
1505  fn parse<'t>(
1506    f: &CowArcStr<'i>,
1507    input: &mut Parser<'i, 't>,
1508    options: &ParserOptions<'i>,
1509  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
1510    let mut parser = ComponentParser::new(false);
1511    match_ignore_ascii_case! { &*f,
1512      "rgb" => {
1513        input.parse_nested_block(|input| {
1514          parser.parse_relative::<RGB, _, _>(input, |input, parser| {
1515            let (r, g, b, is_legacy) = parse_rgb_components(input, parser)?;
1516            if is_legacy {
1517              return Err(input.new_custom_error(ParserError::InvalidValue))
1518            }
1519            input.expect_delim('/')?;
1520            let alpha = TokenList::parse(input, options, 0)?;
1521            Ok(UnresolvedColor::RGB { r, g, b, alpha })
1522          })
1523        })
1524      },
1525      "hsl" => {
1526        input.parse_nested_block(|input| {
1527          parser.parse_relative::<HSL, _, _>(input, |input, parser| {
1528            let (h, s, l, is_legacy) = parse_hsl_hwb_components::<HSL>(input, parser, false)?;
1529            if is_legacy {
1530              return Err(input.new_custom_error(ParserError::InvalidValue))
1531            }
1532            input.expect_delim('/')?;
1533            let alpha = TokenList::parse(input, options, 0)?;
1534            Ok(UnresolvedColor::HSL { h, s, l, alpha })
1535          })
1536        })
1537      },
1538      "light-dark" => {
1539        input.parse_nested_block(|input| {
1540          let light = input.parse_until_before(Delimiter::Comma, |input|
1541            TokenList::parse(input, options, 0)
1542          )?;
1543          input.expect_comma()?;
1544          let dark = TokenList::parse(input, options, 0)?;
1545          Ok(UnresolvedColor::LightDark { light, dark })
1546        })
1547      },
1548      _ => Err(input.new_custom_error(ParserError::InvalidValue))
1549    }
1550  }
1551
1552  fn to_css<PrinterT: crate::printer::PrinterTrait>(
1553    &self,
1554    dest: &mut PrinterT,
1555    is_custom_property: bool,
1556  ) -> Result<(), PrinterError> {
1557    match self {
1558      UnresolvedColor::RGB { r, g, b, alpha } => {
1559        if should_compile!(dest.state().targets.current, SpaceSeparatedColorNotation) {
1560          dest.write_str("rgba(")?;
1561          r.to_css(dest)?;
1562          dest.delim(',', false)?;
1563          g.to_css(dest)?;
1564          dest.delim(',', false)?;
1565          b.to_css(dest)?;
1566          dest.delim(',', false)?;
1567          alpha.to_css(dest, is_custom_property)?;
1568          dest.write_char(')')?;
1569          return Ok(());
1570        }
1571
1572        dest.write_str("rgb(")?;
1573        r.to_css(dest)?;
1574        dest.write_char(' ')?;
1575        g.to_css(dest)?;
1576        dest.write_char(' ')?;
1577        b.to_css(dest)?;
1578        dest.delim('/', true)?;
1579        alpha.to_css(dest, is_custom_property)?;
1580        dest.write_char(')')?;
1581        Ok(())
1582      }
1583      UnresolvedColor::HSL { h, s, l, alpha } => {
1584        if should_compile!(dest.state().targets.current, SpaceSeparatedColorNotation) {
1585          dest.write_str("hsla(")?;
1586          h.to_css(dest)?;
1587          dest.delim(',', false)?;
1588          Percentage(*s / 100.0).to_css(dest)?;
1589          dest.delim(',', false)?;
1590          Percentage(*l / 100.0).to_css(dest)?;
1591          dest.delim(',', false)?;
1592          alpha.to_css(dest, is_custom_property)?;
1593          dest.write_char(')')?;
1594          return Ok(());
1595        }
1596
1597        dest.write_str("hsl(")?;
1598        h.to_css(dest)?;
1599        dest.write_char(' ')?;
1600        Percentage(*s / 100.0).to_css(dest)?;
1601        dest.write_char(' ')?;
1602        Percentage(*l / 100.0).to_css(dest)?;
1603        dest.delim('/', true)?;
1604        alpha.to_css(dest, is_custom_property)?;
1605        dest.write_char(')')?;
1606        Ok(())
1607      }
1608      UnresolvedColor::LightDark { light, dark } => {
1609        if should_compile!(dest.state().targets.current, LightDark) {
1610          dest.write_str("var(--lightningcss-light")?;
1611          dest.delim(',', false)?;
1612          light.to_css(dest, is_custom_property)?;
1613          dest.write_char(')')?;
1614          dest.whitespace()?;
1615          dest.write_str("var(--lightningcss-dark")?;
1616          dest.delim(',', false)?;
1617          dark.to_css(dest, is_custom_property)?;
1618          dest.write_char(')')?;
1619          return Ok(());
1620        }
1621
1622        dest.write_str("light-dark(")?;
1623        light.to_css(dest, is_custom_property)?;
1624        dest.delim(',', false)?;
1625        dark.to_css(dest, is_custom_property)?;
1626        dest.write_char(')')?;
1627        Ok(())
1628      }
1629    }
1630  }
1631}