Skip to main content

lightningcss/values/
ident.rs

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