Skip to main content

rspack_lightningcss/values/
ident.rs

1//! CSS identifiers.
2
3use crate::error::{ParserError, PrinterError};
4use crate::properties::css_modules::Specifier;
5use crate::traits::{Parse, ParseWithOptions, ToCss};
6use crate::values::string::CowArcStr;
7#[cfg(feature = "visitor")]
8use crate::visitor::Visit;
9use cssparser::*;
10use smallvec::SmallVec;
11use std::borrow::Borrow;
12use std::ops::Deref;
13
14use super::string::impl_string_type;
15
16/// A CSS [`<custom-ident>`](https://www.w3.org/TR/css-values-4/#custom-idents).
17///
18/// Custom idents are author defined, and allow any valid identifier except the
19/// [CSS-wide keywords](https://www.w3.org/TR/css-values-4/#css-wide-keywords).
20/// They may be renamed to include a hash when compiled as part of a CSS module.
21#[derive(Debug, Clone, Eq, Hash)]
22#[cfg_attr(feature = "visitor", derive(Visit))]
23#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
24#[cfg_attr(feature = "visitor", visit(visit_custom_ident, CUSTOM_IDENTS))]
25#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(transparent))]
26#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
27pub struct CustomIdent<'i>(#[cfg_attr(feature = "serde", serde(borrow))] pub CowArcStr<'i>);
28
29impl<'i> Parse<'i> for CustomIdent<'i> {
30  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
31    let location = input.current_source_location();
32    let ident = input.expect_ident()?;
33    let valid = match_ignore_ascii_case! { &ident,
34      "initial" | "inherit" | "unset" | "default" | "revert" | "revert-layer" => false,
35      _ => true
36    };
37
38    if !valid {
39      return Err(location.new_unexpected_token_error(Token::Ident(ident.clone())));
40    }
41
42    Ok(CustomIdent(ident.into()))
43  }
44}
45
46impl<'i> ToCss for CustomIdent<'i> {
47  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
48    self.to_css_with_options(dest, true)
49  }
50}
51
52impl<'i> CustomIdent<'i> {
53  /// Write the custom ident to CSS.
54  pub(crate) fn to_css_with_options<PrinterT: crate::printer::PrinterTrait>(
55    &self,
56    dest: &mut PrinterT,
57    enabled_css_modules: bool,
58  ) -> Result<(), PrinterError> {
59    let css_module_custom_idents_enabled = enabled_css_modules
60      && dest
61        .state_mut()
62        .css_module
63        .as_mut()
64        .map_or(false, |css_module| css_module.config.custom_idents);
65    dest.write_ident(&self.0, css_module_custom_idents_enabled)
66  }
67}
68
69/// A list of CSS [`<custom-ident>`](https://www.w3.org/TR/css-values-4/#custom-idents) values.
70pub type CustomIdentList<'i> = SmallVec<[CustomIdent<'i>; 1]>;
71
72/// The `none` keyword, or a space-separated list of custom idents.
73#[derive(Debug, Clone, PartialEq, Default)]
74#[cfg_attr(feature = "visitor", derive(Visit))]
75#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
76#[cfg_attr(
77  feature = "serde",
78  derive(serde::Serialize, serde::Deserialize),
79  serde(rename_all = "kebab-case")
80)]
81#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
82pub enum NoneOrCustomIdentList<'i> {
83  /// None.
84  #[default]
85  None,
86  /// A list of idents.
87  #[cfg_attr(feature = "serde", serde(borrow, untagged))]
88  Idents(SmallVec<[CustomIdent<'i>; 1]>),
89}
90
91impl<'i> Parse<'i> for NoneOrCustomIdentList<'i> {
92  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
93    let mut types = SmallVec::new();
94    loop {
95      if let Ok(ident) = input.try_parse(CustomIdent::parse) {
96        if ident == "none" {
97          if types.is_empty() {
98            return Ok(NoneOrCustomIdentList::None);
99          } else {
100            return Err(input.new_custom_error(ParserError::InvalidValue));
101          }
102        }
103
104        types.push(ident);
105      } else {
106        return Ok(NoneOrCustomIdentList::Idents(types));
107      }
108    }
109  }
110}
111
112impl<'i> ToCss for NoneOrCustomIdentList<'i> {
113  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
114    match self {
115      NoneOrCustomIdentList::None => {
116        dest.write_str("none")?;
117        Ok(())
118      }
119      NoneOrCustomIdentList::Idents(types) => {
120        let mut first = true;
121        for ident in types {
122          if !first {
123            dest.write_char(' ')?;
124          } else {
125            first = false;
126          }
127          ident.to_css(dest)?;
128        }
129        Ok(())
130      }
131    }
132  }
133}
134
135/// A CSS [`<dashed-ident>`](https://www.w3.org/TR/css-values-4/#dashed-idents) declaration.
136///
137/// Dashed idents are used in cases where an identifier can be either author defined _or_ CSS-defined.
138/// Author defined idents must start with two dash characters ("--") or parsing will fail.
139#[derive(Debug, Clone, Eq, Hash)]
140#[cfg_attr(feature = "visitor", derive(Visit))]
141#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
142#[cfg_attr(feature = "visitor", visit(visit_dashed_ident, DASHED_IDENTS))]
143#[cfg_attr(feature = "serde", derive(serde::Serialize), serde(transparent))]
144#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
145pub struct DashedIdent<'i>(#[cfg_attr(feature = "serde", serde(borrow))] pub CowArcStr<'i>);
146
147impl<'i> Parse<'i> for DashedIdent<'i> {
148  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
149    let location = input.current_source_location();
150    let ident = input.expect_ident()?;
151    if !ident.starts_with("--") {
152      return Err(location.new_unexpected_token_error(Token::Ident(ident.clone())));
153    }
154
155    Ok(DashedIdent(ident.into()))
156  }
157}
158
159impl<'i> ToCss for DashedIdent<'i> {
160  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
161    dest.write_dashed_ident(&self.0, true)
162  }
163}
164
165#[cfg(feature = "serde")]
166impl<'i, 'de: 'i> serde::Deserialize<'de> for DashedIdent<'i> {
167  fn deserialize<D>(deserializer: D) -> Result<Self, D::Error>
168  where
169    D: serde::Deserializer<'de>,
170  {
171    let ident = CowArcStr::deserialize(deserializer)?;
172    if !ident.starts_with("--") {
173      return Err(serde::de::Error::custom("Dashed idents must start with --"));
174    }
175
176    Ok(DashedIdent(ident))
177  }
178}
179
180/// A CSS [`<dashed-ident>`](https://www.w3.org/TR/css-values-4/#dashed-idents) reference.
181///
182/// Dashed idents are used in cases where an identifier can be either author defined _or_ CSS-defined.
183/// Author defined idents must start with two dash characters ("--") or parsing will fail.
184///
185/// In CSS modules, when the `dashed_idents` option is enabled, the identifier may be followed by the
186/// `from` keyword and an argument indicating where the referenced identifier is declared (e.g. a filename).
187#[derive(Debug, Clone, PartialEq)]
188#[cfg_attr(feature = "visitor", derive(Visit))]
189#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
190#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
191#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
192pub struct DashedIdentReference<'i> {
193  /// The referenced identifier.
194  #[cfg_attr(feature = "serde", serde(borrow))]
195  pub ident: DashedIdent<'i>,
196  /// CSS modules extension: the filename where the variable is defined.
197  /// Only enabled when the CSS modules `dashed_idents` option is turned on.
198  pub from: Option<Specifier<'i>>,
199}
200
201impl<'i> ParseWithOptions<'i> for DashedIdentReference<'i> {
202  fn parse_with_options<'t>(
203    input: &mut Parser<'i, 't>,
204    options: &crate::stylesheet::ParserOptions,
205  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
206    let ident = DashedIdent::parse(input)?;
207
208    let from = match &options.css_modules {
209      Some(config) if config.dashed_idents => {
210        if input.try_parse(|input| input.expect_ident_matching("from")).is_ok() {
211          Some(Specifier::parse(input)?)
212        } else {
213          None
214        }
215      }
216      _ => None,
217    };
218
219    Ok(DashedIdentReference { ident, from })
220  }
221}
222
223impl<'i> ToCss for DashedIdentReference<'i> {
224  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
225    let source_index = dest.state().loc.source_index;
226    match dest.state_mut().css_module.as_mut() {
227      Some(css_module) if css_module.config.dashed_idents => {
228        if let Some(name) = css_module.reference_dashed(&self.ident.0, &self.from, source_index) {
229          dest.write_str("--")?;
230          serialize_name(&name, dest)?;
231          return Ok(());
232        }
233      }
234      _ => {}
235    }
236
237    dest.write_dashed_ident(&self.ident.0, false)
238  }
239}
240
241/// A CSS [`<ident>`](https://www.w3.org/TR/css-values-4/#css-css-identifier).
242#[derive(Debug, Clone, Eq, Hash, Default)]
243#[cfg_attr(feature = "visitor", derive(Visit))]
244#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
245#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize), serde(transparent))]
246#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
247pub struct Ident<'i>(#[cfg_attr(feature = "serde", serde(borrow))] pub CowArcStr<'i>);
248
249impl<'i> Parse<'i> for Ident<'i> {
250  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
251    let ident = input.expect_ident()?;
252    Ok(Ident(ident.into()))
253  }
254}
255
256impl<'i> ToCss for Ident<'i> {
257  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
258    serialize_identifier(&self.0, dest)?;
259    Ok(())
260  }
261}
262
263impl<'i> cssparser::ToCss for Ident<'i> {
264  fn to_css<W>(&self, dest: &mut W) -> std::fmt::Result
265  where
266    W: std::fmt::Write,
267  {
268    serialize_identifier(&self.0, dest)
269  }
270}
271
272impl_string_type!(Ident);
273impl_string_type!(CustomIdent);
274impl_string_type!(DashedIdent);