Skip to main content

rspack_lightningcss/rules/
font_feature_values.rs

1//! The `@font-feature-values` rule.
2
3use super::Location;
4use crate::error::{ParserError, PrinterError};
5use crate::parser::ParserOptions;
6use crate::properties::font::FamilyName;
7use crate::traits::{Parse, ToCss};
8use crate::values::ident::Ident;
9use crate::values::number::CSSInteger;
10#[cfg(feature = "visitor")]
11use crate::visitor::Visit;
12use cssparser::*;
13use indexmap::IndexMap;
14use smallvec::SmallVec;
15
16/// A [@font-feature-values](https://drafts.csswg.org/css-fonts/#font-feature-values) rule.
17#[derive(Debug, PartialEq, Clone)]
18#[cfg_attr(feature = "visitor", derive(Visit))]
19#[cfg_attr(feature = "serde", derive(serde::Serialize, serde::Deserialize))]
20#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
21#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
22pub struct FontFeatureValuesRule<'i> {
23  /// The name of the font feature values.
24  #[cfg_attr(feature = "serde", serde(borrow))]
25  pub name: Vec<FamilyName<'i>>,
26  /// The rules within the `@font-feature-values` rule.
27  pub rules: IndexMap<FontFeatureSubruleType, FontFeatureSubrule<'i>>,
28  /// The location of the rule in the source file.
29  #[cfg_attr(feature = "visitor", skip_visit)]
30  pub loc: Location,
31}
32
33impl<'i> FontFeatureValuesRule<'i> {
34  pub(crate) fn parse<'t>(
35    family_names: Vec<FamilyName<'i>>,
36    input: &mut Parser<'i, 't>,
37    loc: Location,
38    options: &ParserOptions<'i>,
39  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
40    let mut rules = IndexMap::new();
41    let mut rule_parser = FontFeatureValuesRuleParser {
42      rules: &mut rules,
43      options,
44    };
45    let mut parser = RuleBodyParser::new(input, &mut rule_parser);
46
47    while let Some(decl_or_rule) = parser.next() {
48      if let Err((err, _)) = decl_or_rule {
49        if parser.parser.options.error_recovery {
50          parser.parser.options.warn(err);
51          continue;
52        }
53        return Err(err);
54      }
55    }
56
57    Ok(FontFeatureValuesRule {
58      name: family_names,
59      rules,
60      loc,
61    })
62  }
63}
64
65struct FontFeatureValuesRuleParser<'a, 'i> {
66  rules: &'a mut IndexMap<FontFeatureSubruleType, FontFeatureSubrule<'i>>,
67  options: &'a ParserOptions<'i>,
68}
69
70impl<'a, 'i> cssparser::DeclarationParser<'i> for FontFeatureValuesRuleParser<'a, 'i> {
71  type Declaration = ();
72  type Error = ParserError<'i>;
73}
74
75impl<'a, 'i> cssparser::AtRuleParser<'i> for FontFeatureValuesRuleParser<'a, 'i> {
76  type Prelude = FontFeatureSubruleType;
77  type AtRule = ();
78  type Error = ParserError<'i>;
79
80  fn parse_prelude<'t>(
81    &mut self,
82    name: CowRcStr<'i>,
83    input: &mut Parser<'i, 't>,
84  ) -> Result<Self::Prelude, ParseError<'i, Self::Error>> {
85    let loc = input.current_source_location();
86    FontFeatureSubruleType::parse_string(&name)
87      .map_err(|_| loc.new_custom_error(ParserError::AtRuleInvalid(name.clone().into())))
88  }
89
90  fn parse_block<'t>(
91    &mut self,
92    prelude: Self::Prelude,
93    start: &ParserState,
94    input: &mut Parser<'i, 't>,
95  ) -> Result<Self::AtRule, ParseError<'i, Self::Error>> {
96    let loc = start.source_location();
97    let mut decls = IndexMap::new();
98    let mut has_existing = false;
99    let declarations = if let Some(rule) = self.rules.get_mut(&prelude) {
100      has_existing = true;
101      &mut rule.declarations
102    } else {
103      &mut decls
104    };
105    let mut decl_parser = FontFeatureDeclarationParser { declarations };
106    let mut parser = RuleBodyParser::new(input, &mut decl_parser);
107    while let Some(decl) = parser.next() {
108      if let Err((err, _)) = decl {
109        if self.options.error_recovery {
110          self.options.warn(err);
111          continue;
112        }
113        return Err(err);
114      }
115    }
116
117    if !has_existing {
118      self.rules.insert(
119        prelude,
120        FontFeatureSubrule {
121          name: prelude,
122          declarations: decls,
123          loc: Location {
124            source_index: self.options.source_index,
125            line: loc.line,
126            column: loc.column,
127          },
128        },
129      );
130    }
131
132    Ok(())
133  }
134}
135
136impl<'a, 'i> QualifiedRuleParser<'i> for FontFeatureValuesRuleParser<'a, 'i> {
137  type Prelude = ();
138  type QualifiedRule = ();
139  type Error = ParserError<'i>;
140}
141
142impl<'a, 'i> RuleBodyItemParser<'i, (), ParserError<'i>> for FontFeatureValuesRuleParser<'a, 'i> {
143  fn parse_declarations(&self) -> bool {
144    false
145  }
146
147  fn parse_qualified(&self) -> bool {
148    false
149  }
150}
151
152impl<'i> ToCss for FontFeatureValuesRule<'i> {
153  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
154    #[cfg(feature = "custom_sourcemap")]
155    dest.add_mapping(self.loc);
156    dest.write_str("@font-feature-values ")?;
157    self.name.to_css(dest)?;
158    dest.whitespace()?;
159    dest.write_char('{')?;
160    if !self.rules.is_empty() {
161      dest.newline()?;
162      for rule in self.rules.values() {
163        rule.to_css(dest)?;
164        dest.newline()?;
165      }
166    }
167    dest.write_char('}')?;
168    Ok(())
169  }
170}
171
172impl<'i> FontFeatureValuesRule<'i> {
173  pub(crate) fn merge(&mut self, other: &FontFeatureValuesRule<'i>) {
174    debug_assert_eq!(self.name, other.name);
175    for (prelude, rule) in &other.rules {
176      if let Some(existing) = self.rules.get_mut(prelude) {
177        existing
178          .declarations
179          .extend(rule.declarations.iter().map(|(k, v)| (k.clone(), v.clone())));
180      } else {
181        self.rules.insert(*prelude, rule.clone());
182      }
183    }
184  }
185}
186
187/// The name of the `@font-feature-values` sub-rule.
188/// font-feature-value-type = <@stylistic> | <@historical-forms> | <@styleset> | <@character-variant>
189///   | <@swash> | <@ornaments> | <@annotation>
190#[derive(Debug, Clone, Copy, PartialEq, Eq, Hash, Parse, ToCss)]
191#[cfg_attr(feature = "visitor", derive(Visit))]
192#[cfg_attr(
193  feature = "serde",
194  derive(serde::Serialize, serde::Deserialize),
195  serde(rename_all = "kebab-case")
196)]
197#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
198#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
199pub enum FontFeatureSubruleType {
200  /// @stylistic = @stylistic { <declaration-list> }
201  Stylistic,
202  /// @historical-forms = @historical-forms { <declaration-list> }
203  HistoricalForms,
204  /// @styleset = @styleset { <declaration-list> }
205  Styleset,
206  /// @character-variant = @character-variant { <declaration-list> }
207  CharacterVariant,
208  /// @swash = @swash { <declaration-list> }
209  Swash,
210  /// @ornaments = @ornaments { <declaration-list> }
211  Ornaments,
212  /// @annotation = @annotation { <declaration-list> }
213  Annotation,
214}
215
216/// A sub-rule of `@font-feature-values`
217/// https://drafts.csswg.org/css-fonts/#font-feature-values-syntax
218#[derive(Debug, PartialEq, Clone)]
219#[cfg_attr(feature = "visitor", derive(Visit))]
220#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
221#[cfg_attr(
222  feature = "serde",
223  derive(serde::Serialize, serde::Deserialize),
224  serde(rename_all = "camelCase")
225)]
226#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
227pub struct FontFeatureSubrule<'i> {
228  /// The name of the `@font-feature-values` sub-rule.
229  pub name: FontFeatureSubruleType,
230  /// The declarations within the `@font-feature-values` sub-rules.
231  #[cfg_attr(feature = "serde", serde(borrow))]
232  pub declarations: IndexMap<Ident<'i>, SmallVec<[CSSInteger; 1]>>,
233  /// The location of the rule in the source file.
234  #[cfg_attr(feature = "visitor", skip_visit)]
235  pub loc: Location,
236}
237
238impl<'i> ToCss for FontFeatureSubrule<'i> {
239  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
240    #[cfg(feature = "custom_sourcemap")]
241    dest.add_mapping(self.loc);
242    dest.write_char('@')?;
243    self.name.to_css(dest)?;
244    dest.write_char('{')?;
245    dest.indent();
246    let len = self.declarations.len();
247    for (i, (name, value)) in self.declarations.iter().enumerate() {
248      dest.newline()?;
249      name.to_css(dest)?;
250      dest.delim(':', false)?;
251
252      let mut first = true;
253      for index in value {
254        if first {
255          first = false;
256        } else {
257          dest.write_char(' ')?;
258        }
259        index.to_css(dest)?;
260      }
261
262      if i != len - 1 || !dest.options().minify {
263        dest.write_char(';')?;
264      }
265    }
266    dest.dedent();
267    dest.newline()?;
268    dest.write_char('}')?;
269    Ok(())
270  }
271}
272
273struct FontFeatureDeclarationParser<'a, 'i> {
274  declarations: &'a mut IndexMap<Ident<'i>, SmallVec<[CSSInteger; 1]>>,
275}
276
277impl<'a, 'i> cssparser::DeclarationParser<'i> for FontFeatureDeclarationParser<'a, 'i> {
278  type Declaration = ();
279  type Error = ParserError<'i>;
280
281  fn parse_value<'t>(
282    &mut self,
283    name: CowRcStr<'i>,
284    input: &mut cssparser::Parser<'i, 't>,
285    _declaration_start: &ParserState,
286  ) -> Result<Self::Declaration, cssparser::ParseError<'i, Self::Error>> {
287    let mut indices = SmallVec::new();
288    loop {
289      if let Ok(value) = CSSInteger::parse(input) {
290        indices.push(value);
291      } else {
292        break;
293      }
294    }
295
296    if indices.is_empty() {
297      return Err(input.new_custom_error(ParserError::InvalidValue));
298    }
299
300    self.declarations.insert(Ident(name.into()), indices);
301    Ok(())
302  }
303}
304
305/// Default methods reject all at rules.
306impl<'a, 'i> AtRuleParser<'i> for FontFeatureDeclarationParser<'a, 'i> {
307  type Prelude = ();
308  type AtRule = ();
309  type Error = ParserError<'i>;
310}
311
312impl<'a, 'i> QualifiedRuleParser<'i> for FontFeatureDeclarationParser<'a, 'i> {
313  type Prelude = ();
314  type QualifiedRule = ();
315  type Error = ParserError<'i>;
316}
317
318impl<'a, 'i> RuleBodyItemParser<'i, (), ParserError<'i>> for FontFeatureDeclarationParser<'a, 'i> {
319  fn parse_qualified(&self) -> bool {
320    false
321  }
322
323  fn parse_declarations(&self) -> bool {
324    true
325  }
326}