Skip to main content

rspack_lightningcss/values/
calc.rs

1//! Mathematical calculation functions and expressions.
2
3use crate::compat::Feature;
4use crate::error::{ParserError, PrinterError};
5use crate::macros::enum_property;
6use crate::targets::{should_compile, Browsers};
7use crate::traits::private::AddInternal;
8use crate::traits::{IsCompatible, Parse, Sign, ToCss, TryMap, TryOp, TrySign};
9#[cfg(feature = "visitor")]
10use crate::visitor::Visit;
11use cssparser::*;
12
13use super::angle::Angle;
14use super::length::Length;
15use super::number::CSSNumber;
16use super::percentage::Percentage;
17use super::time::Time;
18
19/// A CSS [math function](https://www.w3.org/TR/css-values-4/#math-function).
20///
21/// Math functions may be used in most properties and values that accept numeric
22/// values, including lengths, percentages, angles, times, etc.
23#[derive(Debug, Clone, PartialEq)]
24#[cfg_attr(feature = "visitor", derive(Visit))]
25#[cfg_attr(
26  feature = "serde",
27  derive(serde::Serialize, serde::Deserialize),
28  serde(tag = "type", content = "value", rename_all = "kebab-case")
29)]
30#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
31#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
32pub enum MathFunction<V> {
33  /// The [`calc()`](https://www.w3.org/TR/css-values-4/#calc-func) function.
34  Calc(Calc<V>),
35  /// The [`min()`](https://www.w3.org/TR/css-values-4/#funcdef-min) function.
36  Min(Vec<Calc<V>>),
37  /// The [`max()`](https://www.w3.org/TR/css-values-4/#funcdef-max) function.
38  Max(Vec<Calc<V>>),
39  /// The [`clamp()`](https://www.w3.org/TR/css-values-4/#funcdef-clamp) function.
40  Clamp(Calc<V>, Calc<V>, Calc<V>),
41  /// The [`round()`](https://www.w3.org/TR/css-values-4/#funcdef-round) function.
42  Round(RoundingStrategy, Calc<V>, Calc<V>),
43  /// The [`rem()`](https://www.w3.org/TR/css-values-4/#funcdef-rem) function.
44  Rem(Calc<V>, Calc<V>),
45  /// The [`mod()`](https://www.w3.org/TR/css-values-4/#funcdef-mod) function.
46  Mod(Calc<V>, Calc<V>),
47  /// The [`abs()`](https://drafts.csswg.org/css-values-4/#funcdef-abs) function.
48  Abs(Calc<V>),
49  /// The [`sign()`](https://drafts.csswg.org/css-values-4/#funcdef-sign) function.
50  Sign(Calc<V>),
51  /// The [`hypot()`](https://drafts.csswg.org/css-values-4/#funcdef-hypot) function.
52  Hypot(Vec<Calc<V>>),
53}
54
55impl<V: IsCompatible> IsCompatible for MathFunction<V> {
56  fn is_compatible(&self, browsers: Browsers) -> bool {
57    match self {
58      MathFunction::Calc(v) => Feature::CalcFunction.is_compatible(browsers) && v.is_compatible(browsers),
59      MathFunction::Min(v) => {
60        Feature::MinFunction.is_compatible(browsers) && v.iter().all(|v| v.is_compatible(browsers))
61      }
62      MathFunction::Max(v) => {
63        Feature::MaxFunction.is_compatible(browsers) && v.iter().all(|v| v.is_compatible(browsers))
64      }
65      MathFunction::Clamp(a, b, c) => {
66        Feature::ClampFunction.is_compatible(browsers)
67          && a.is_compatible(browsers)
68          && b.is_compatible(browsers)
69          && c.is_compatible(browsers)
70      }
71      MathFunction::Round(_, a, b) => {
72        Feature::RoundFunction.is_compatible(browsers) && a.is_compatible(browsers) && b.is_compatible(browsers)
73      }
74      MathFunction::Rem(a, b) => {
75        Feature::RemFunction.is_compatible(browsers) && a.is_compatible(browsers) && b.is_compatible(browsers)
76      }
77      MathFunction::Mod(a, b) => {
78        Feature::ModFunction.is_compatible(browsers) && a.is_compatible(browsers) && b.is_compatible(browsers)
79      }
80      MathFunction::Abs(v) => Feature::AbsFunction.is_compatible(browsers) && v.is_compatible(browsers),
81      MathFunction::Sign(v) => Feature::SignFunction.is_compatible(browsers) && v.is_compatible(browsers),
82      MathFunction::Hypot(v) => {
83        Feature::HypotFunction.is_compatible(browsers) && v.iter().all(|v| v.is_compatible(browsers))
84      }
85    }
86  }
87}
88
89enum_property! {
90  /// A [rounding strategy](https://www.w3.org/TR/css-values-4/#typedef-rounding-strategy),
91  /// as used in the `round()` function.
92  pub enum RoundingStrategy {
93    /// Round to the nearest integer.
94    Nearest,
95    /// Round up (ceil).
96    Up,
97    /// Round down (floor).
98    Down,
99    /// Round toward zero (truncate).
100    ToZero,
101  }
102}
103
104impl Default for RoundingStrategy {
105  fn default() -> Self {
106    RoundingStrategy::Nearest
107  }
108}
109
110fn round(value: f32, to: f32, strategy: RoundingStrategy) -> f32 {
111  let v = value / to;
112  match strategy {
113    RoundingStrategy::Down => v.floor() * to,
114    RoundingStrategy::Up => v.ceil() * to,
115    RoundingStrategy::Nearest => v.round() * to,
116    RoundingStrategy::ToZero => v.trunc() * to,
117  }
118}
119
120fn modulo(a: f32, b: f32) -> f32 {
121  ((a % b) + b) % b
122}
123
124impl<V: ToCss + std::ops::Mul<f32, Output = V> + TrySign + Clone + std::fmt::Debug> ToCss for MathFunction<V> {
125  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
126    match self {
127      MathFunction::Calc(calc) => {
128        dest.write_str("calc(")?;
129        calc.to_css(dest)?;
130        dest.write_char(')')?;
131        Ok(())
132      }
133      MathFunction::Min(args) => {
134        dest.write_str("min(")?;
135        let mut first = true;
136        for arg in args {
137          if first {
138            first = false;
139          } else {
140            dest.delim(',', false)?;
141          }
142          arg.to_css(dest)?;
143        }
144        dest.write_char(')')?;
145        Ok(())
146      }
147      MathFunction::Max(args) => {
148        dest.write_str("max(")?;
149        let mut first = true;
150        for arg in args {
151          if first {
152            first = false;
153          } else {
154            dest.delim(',', false)?;
155          }
156          arg.to_css(dest)?;
157        }
158        dest.write_char(')')?;
159        Ok(())
160      }
161      MathFunction::Clamp(a, b, c) => {
162        // If clamp() is unsupported by targets, output min()/max()
163        if should_compile!(dest.targets().current, ClampFunction) {
164          dest.write_str("max(")?;
165          a.to_css(dest)?;
166          dest.delim(',', false)?;
167          dest.write_str("min(")?;
168          b.to_css(dest)?;
169          dest.delim(',', false)?;
170          c.to_css(dest)?;
171          dest.write_str("))")?;
172          return Ok(());
173        }
174
175        dest.write_str("clamp(")?;
176        a.to_css(dest)?;
177        dest.delim(',', false)?;
178        b.to_css(dest)?;
179        dest.delim(',', false)?;
180        c.to_css(dest)?;
181        dest.write_char(')')?;
182        Ok(())
183      }
184      MathFunction::Round(strategy, a, b) => {
185        dest.write_str("round(")?;
186        if *strategy != RoundingStrategy::default() {
187          strategy.to_css(dest)?;
188          dest.delim(',', false)?;
189        }
190        a.to_css(dest)?;
191        dest.delim(',', false)?;
192        b.to_css(dest)?;
193        dest.write_char(')')?;
194        Ok(())
195      }
196      MathFunction::Rem(a, b) => {
197        dest.write_str("rem(")?;
198        a.to_css(dest)?;
199        dest.delim(',', false)?;
200        b.to_css(dest)?;
201        dest.write_char(')')?;
202        Ok(())
203      }
204      MathFunction::Mod(a, b) => {
205        dest.write_str("mod(")?;
206        a.to_css(dest)?;
207        dest.delim(',', false)?;
208        b.to_css(dest)?;
209        dest.write_char(')')?;
210        Ok(())
211      }
212      MathFunction::Abs(v) => {
213        dest.write_str("abs(")?;
214        v.to_css(dest)?;
215        dest.write_char(')')?;
216        Ok(())
217      }
218      MathFunction::Sign(v) => {
219        dest.write_str("sign(")?;
220        v.to_css(dest)?;
221        dest.write_char(')')?;
222        Ok(())
223      }
224      MathFunction::Hypot(args) => {
225        dest.write_str("hypot(")?;
226        let mut first = true;
227        for arg in args {
228          if first {
229            first = false;
230          } else {
231            dest.delim(',', false)?;
232          }
233          arg.to_css(dest)?;
234        }
235        dest.write_char(')')?;
236        Ok(())
237      }
238    }
239  }
240}
241
242/// A mathematical expression used within the [`calc()`](https://www.w3.org/TR/css-values-4/#calc-func) function.
243///
244/// This type supports generic value types. Values such as [Length](super::length::Length), [Percentage](super::percentage::Percentage),
245/// [Time](super::time::Time), and [Angle](super::angle::Angle) support `calc()` expressions.
246#[derive(Debug, Clone, PartialEq)]
247#[cfg_attr(feature = "visitor", derive(Visit))]
248#[cfg_attr(
249  feature = "serde",
250  derive(serde::Serialize, serde::Deserialize),
251  serde(tag = "type", content = "value", rename_all = "kebab-case")
252)]
253#[cfg_attr(feature = "jsonschema", derive(schemars::JsonSchema))]
254#[cfg_attr(feature = "into_owned", derive(rspack_lightningcss_static_self::IntoOwned))]
255pub enum Calc<V> {
256  /// A literal value.
257  Value(Box<V>),
258  /// A literal number.
259  Number(CSSNumber),
260  /// A sum of two calc expressions.
261  #[cfg_attr(feature = "visitor", skip_type)]
262  Sum(Box<Calc<V>>, Box<Calc<V>>),
263  /// A product of a number and another calc expression.
264  #[cfg_attr(feature = "visitor", skip_type)]
265  Product(CSSNumber, Box<Calc<V>>),
266  /// A math function, such as `calc()`, `min()`, or `max()`.
267  #[cfg_attr(feature = "visitor", skip_type)]
268  Function(Box<MathFunction<V>>),
269}
270
271impl<V: IsCompatible> IsCompatible for Calc<V> {
272  fn is_compatible(&self, browsers: Browsers) -> bool {
273    match self {
274      Calc::Sum(a, b) => a.is_compatible(browsers) && b.is_compatible(browsers),
275      Calc::Product(_, v) => v.is_compatible(browsers),
276      Calc::Function(f) => f.is_compatible(browsers),
277      Calc::Value(v) => v.is_compatible(browsers),
278      Calc::Number(..) => true,
279    }
280  }
281}
282
283enum_property! {
284  /// A mathematical constant.
285  pub enum Constant {
286    /// The base of the natural logarithm
287    "e": E,
288    /// The ratio of a circle’s circumference to its diameter
289    "pi": Pi,
290    /// infinity
291    "infinity": Infinity,
292    /// -infinity
293    "-infinity": NegativeInfinity,
294    /// Not a number.
295    "nan": Nan,
296  }
297}
298
299impl Into<f32> for Constant {
300  fn into(self) -> f32 {
301    use std::f32::consts;
302    use Constant::*;
303    match self {
304      E => consts::E,
305      Pi => consts::PI,
306      Infinity => f32::INFINITY,
307      NegativeInfinity => -f32::INFINITY,
308      Nan => f32::NAN,
309    }
310  }
311}
312
313impl<
314    'i,
315    V: Parse<'i>
316      + std::ops::Mul<f32, Output = V>
317      + AddInternal
318      + TryOp
319      + TryMap
320      + TrySign
321      + std::cmp::PartialOrd<V>
322      + Into<Calc<V>>
323      + TryFrom<Calc<V>>
324      + TryFrom<Angle>
325      + TryInto<Angle>
326      + Clone
327      + std::fmt::Debug,
328  > Parse<'i> for Calc<V>
329{
330  fn parse<'t>(input: &mut Parser<'i, 't>) -> Result<Self, ParseError<'i, ParserError<'i>>> {
331    Self::parse_with(input, &|_| None)
332  }
333}
334
335impl<
336    'i,
337    V: Parse<'i>
338      + std::ops::Mul<f32, Output = V>
339      + AddInternal
340      + TryOp
341      + TryMap
342      + TrySign
343      + std::cmp::PartialOrd<V>
344      + Into<Calc<V>>
345      + TryFrom<Calc<V>>
346      + TryFrom<Angle>
347      + TryInto<Angle>
348      + Clone
349      + std::fmt::Debug,
350  > Calc<V>
351{
352  pub(crate) fn parse_with<'t>(
353    input: &mut Parser<'i, 't>,
354    parse_ident: &dyn Fn(&str) -> Option<Calc<V>>,
355  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
356    let location = input.current_source_location();
357    let f = input.expect_function()?;
358    match_ignore_ascii_case! { &f,
359      "calc" => {
360        let calc = input.parse_nested_block(|input| Calc::parse_sum(input, parse_ident))?;
361        match calc {
362          Calc::Value(_) | Calc::Number(_) => Ok(calc),
363          _ => Ok(Calc::Function(Box::new(MathFunction::Calc(calc))))
364        }
365      },
366      "min" => {
367        let mut args = input.parse_nested_block(|input| input.parse_comma_separated(|input| Calc::parse_sum(input, parse_ident)))?;
368        let mut reduced = Calc::reduce_args(&mut args, std::cmp::Ordering::Less);
369        if reduced.len() == 1 {
370          return Ok(reduced.remove(0))
371        }
372        Ok(Calc::Function(Box::new(MathFunction::Min(reduced))))
373      },
374      "max" => {
375        let mut args = input.parse_nested_block(|input| input.parse_comma_separated(|input| Calc::parse_sum(input, parse_ident)))?;
376        let mut reduced = Calc::reduce_args(&mut args, std::cmp::Ordering::Greater);
377        if reduced.len() == 1 {
378          return Ok(reduced.remove(0))
379        }
380        Ok(Calc::Function(Box::new(MathFunction::Max(reduced))))
381      },
382      "clamp" => {
383        let (mut min, mut center, mut max) = input.parse_nested_block(|input| {
384          let min = Some(Calc::parse_sum(input, parse_ident)?);
385          input.expect_comma()?;
386          let center: Calc<V> = Calc::parse_sum(input, parse_ident)?;
387          input.expect_comma()?;
388          let max = Some(Calc::parse_sum(input, parse_ident)?);
389          Ok((min, center, max))
390        })?;
391
392        // According to the spec, the minimum should "win" over the maximum if they are in the wrong order.
393        let cmp = match (&max, &center) {
394          (Some(Calc::Value(max_val)), Calc::Value(center_val)) => center_val.partial_cmp(&max_val),
395          (Some(Calc::Number(max_val)), Calc::Number(center_val)) => center_val.partial_cmp(max_val),
396          _ => None,
397        };
398
399        // If center is known to be greater than the maximum, replace it with maximum and remove the max argument.
400        // Otherwise, if center is known to be less than the maximum, remove the max argument.
401        match cmp {
402          Some(std::cmp::Ordering::Greater) => {
403            center = std::mem::take(&mut max).unwrap();
404          }
405          Some(_) => {
406            max = None;
407          }
408          None => {}
409        }
410
411        if cmp.is_some() {
412          let cmp = match (&min, &center) {
413            (Some(Calc::Value(min_val)), Calc::Value(center_val)) => center_val.partial_cmp(&min_val),
414            (Some(Calc::Number(min_val)), Calc::Number(center_val)) => center_val.partial_cmp(min_val),
415            _ => None,
416          };
417
418          // If center is known to be less than the minimum, replace it with minimum and remove the min argument.
419          // Otherwise, if center is known to be greater than the minimum, remove the min argument.
420          match cmp {
421            Some(std::cmp::Ordering::Less) => {
422              center = std::mem::take(&mut min).unwrap();
423            }
424            Some(_) => {
425              min = None;
426            }
427            None => {}
428          }
429        }
430
431        // Generate clamp(), min(), max(), or value depending on which arguments are left.
432        match (min, max) {
433          (None, None) => Ok(center),
434          (Some(min), None) => Ok(Calc::Function(Box::new(MathFunction::Max(vec![min, center])))),
435          (None, Some(max)) => Ok(Calc::Function(Box::new(MathFunction::Min(vec![center, max])))),
436          (Some(min), Some(max)) => Ok(Calc::Function(Box::new(MathFunction::Clamp(min, center, max))))
437        }
438      },
439      "round" => {
440        input.parse_nested_block(|input| {
441          let strategy = if let Ok(s) = input.try_parse(RoundingStrategy::parse) {
442            input.expect_comma()?;
443            s
444          } else {
445            RoundingStrategy::default()
446          };
447
448          Self::parse_math_fn(
449            input,
450            |a, b| round(a, b, strategy),
451            |a, b| MathFunction::Round(strategy, a, b),
452            parse_ident
453          )
454        })
455      },
456      "rem" => {
457        input.parse_nested_block(|input| {
458          Self::parse_math_fn(input, std::ops::Rem::rem, MathFunction::Rem, parse_ident)
459        })
460      },
461      "mod" => {
462        input.parse_nested_block(|input| {
463          Self::parse_math_fn(input, modulo, MathFunction::Mod, parse_ident)
464        })
465      },
466      "sin" => Self::parse_trig(input, f32::sin, false, parse_ident),
467      "cos" => Self::parse_trig(input, f32::cos, false, parse_ident),
468      "tan" => Self::parse_trig(input, f32::tan, false, parse_ident),
469      "asin" => Self::parse_trig(input, f32::asin, true, parse_ident),
470      "acos" => Self::parse_trig(input, f32::acos, true, parse_ident),
471      "atan" => Self::parse_trig(input, f32::atan, true, parse_ident),
472      "atan2" => {
473        input.parse_nested_block(|input| {
474          let res = Self::parse_atan2(input, parse_ident)?;
475          if let Ok(v) = V::try_from(res) {
476            return Ok(Calc::Value(Box::new(v)))
477          }
478
479          Err(input.new_custom_error(ParserError::InvalidValue))
480        })
481      },
482      "pow" => {
483        input.parse_nested_block(|input| {
484          let a = Self::parse_numeric(input, parse_ident)?;
485          input.expect_comma()?;
486          let b = Self::parse_numeric(input, parse_ident)?;
487          Ok(Calc::Number(a.powf(b)))
488        })
489      },
490      "log" => {
491        input.parse_nested_block(|input| {
492          let value = Self::parse_numeric(input, parse_ident)?;
493          if input.try_parse(|input| input.expect_comma()).is_ok() {
494            let base = Self::parse_numeric(input, parse_ident)?;
495            Ok(Calc::Number(value.log(base)))
496          } else {
497            Ok(Calc::Number(value.ln()))
498          }
499        })
500      },
501      "sqrt" => Self::parse_numeric_fn(input, f32::sqrt, parse_ident),
502      "exp" => Self::parse_numeric_fn(input, f32::exp, parse_ident),
503      "hypot" => {
504        input.parse_nested_block(|input| {
505          let args: Vec<Self> = input.parse_comma_separated(|input| Calc::parse_sum(input, parse_ident))?;
506          Self::parse_hypot(&args)?
507            .map_or_else(
508              || Ok(Calc::Function(Box::new(MathFunction::Hypot(args)))),
509              |v| Ok(v)
510            )
511        })
512      },
513      "abs" => {
514        input.parse_nested_block(|input| {
515          let v: Calc<V> = Self::parse_sum(input, parse_ident)?;
516          Self::apply_map(&v, f32::abs)
517            .map_or_else(
518              || Ok(Calc::Function(Box::new(MathFunction::Abs(v)))),
519              |v| Ok(v)
520            )
521        })
522      },
523      "sign" => {
524        input.parse_nested_block(|input| {
525          let v: Calc<V> = Self::parse_sum(input, parse_ident)?;
526          match &v {
527            Calc::Number(n) => return Ok(Calc::Number(n.sign())),
528            Calc::Value(v) => {
529              // First map so we ignore percentages, which must be resolved to their
530              // computed value in order to determine the sign.
531              if let Some(v) = v.try_map(|s| s.sign()) {
532                // sign() always resolves to a number.
533                return Ok(Calc::Number(v.try_sign().unwrap()));
534              }
535            }
536            _ => {}
537          }
538
539          Ok(Calc::Function(Box::new(MathFunction::Sign(v))))
540        })
541      },
542       _ => Err(location.new_unexpected_token_error(Token::Ident(f.clone()))),
543    }
544  }
545
546  fn parse_sum<'t>(
547    input: &mut Parser<'i, 't>,
548    parse_ident: &dyn Fn(&str) -> Option<Calc<V>>,
549  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
550    let mut cur: Calc<V> = Calc::parse_product(input, parse_ident)?;
551    loop {
552      let start = input.state();
553      match input.next_including_whitespace() {
554        Ok(&Token::WhiteSpace(_)) => {
555          if input.is_exhausted() {
556            break; // allow trailing whitespace
557          }
558          match *input.next()? {
559            Token::Delim('+') => {
560              let next = Calc::parse_product(input, parse_ident)?;
561              cur = cur.add(next).map_err(|_| input.new_custom_error(ParserError::InvalidValue))?;
562            }
563            Token::Delim('-') => {
564              let mut rhs = Calc::parse_product(input, parse_ident)?;
565              rhs = rhs * -1.0;
566              cur = cur.add(rhs).map_err(|_| input.new_custom_error(ParserError::InvalidValue))?;
567            }
568            ref t => {
569              let t = t.clone();
570              return Err(input.new_unexpected_token_error(t));
571            }
572          }
573        }
574        _ => {
575          input.reset(&start);
576          break;
577        }
578      }
579    }
580    Ok(cur)
581  }
582
583  fn parse_product<'t>(
584    input: &mut Parser<'i, 't>,
585    parse_ident: &dyn Fn(&str) -> Option<Calc<V>>,
586  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
587    let mut node = Calc::parse_value(input, parse_ident)?;
588    loop {
589      let start = input.state();
590      match input.next() {
591        Ok(&Token::Delim('*')) => {
592          // At least one of the operands must be a number.
593          let rhs = Self::parse_value(input, parse_ident)?;
594          if let Calc::Number(val) = rhs {
595            node = node * val;
596          } else if let Calc::Number(val) = node {
597            node = rhs;
598            node = node * val;
599          } else {
600            return Err(input.new_unexpected_token_error(Token::Delim('*')));
601          }
602        }
603        Ok(&Token::Delim('/')) => {
604          let rhs = Self::parse_value(input, parse_ident)?;
605          if let Calc::Number(val) = rhs {
606            if val != 0.0 {
607              node = node * (1.0 / val);
608              continue;
609            }
610          }
611          return Err(input.new_custom_error(ParserError::InvalidValue));
612        }
613        _ => {
614          input.reset(&start);
615          break;
616        }
617      }
618    }
619    Ok(node)
620  }
621
622  fn parse_value<'t>(
623    input: &mut Parser<'i, 't>,
624    parse_ident: &dyn Fn(&str) -> Option<Calc<V>>,
625  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
626    // Parse nested calc() and other math functions.
627    if let Ok(calc) = input.try_parse(Self::parse) {
628      match calc {
629        Calc::Function(f) => {
630          return Ok(match *f {
631            MathFunction::Calc(c) => c,
632            _ => Calc::Function(f),
633          })
634        }
635        c => return Ok(c),
636      }
637    }
638
639    if input.try_parse(|input| input.expect_parenthesis_block()).is_ok() {
640      return input.parse_nested_block(|input| Calc::parse_sum(input, parse_ident));
641    }
642
643    if let Ok(num) = input.try_parse(|input| input.expect_number()) {
644      return Ok(Calc::Number(num));
645    }
646
647    if let Ok(constant) = input.try_parse(Constant::parse) {
648      return Ok(Calc::Number(constant.into()));
649    }
650
651    let location = input.current_source_location();
652    if let Ok(ident) = input.try_parse(|input| input.expect_ident_cloned()) {
653      if let Some(v) = parse_ident(ident.as_ref()) {
654        return Ok(v);
655      }
656
657      return Err(location.new_unexpected_token_error(Token::Ident(ident.clone())));
658    }
659
660    let value = input.try_parse(V::parse)?;
661    Ok(Calc::Value(Box::new(value)))
662  }
663
664  fn reduce_args(args: &mut Vec<Calc<V>>, cmp: std::cmp::Ordering) -> Vec<Calc<V>> {
665    // Reduces the arguments of a min() or max() expression, combining compatible values.
666    // e.g. min(1px, 1em, 2px, 3in) => min(1px, 1em)
667    // Also handles plain numbers: min(1, 2, 3) => min(1, 2)
668    let mut reduced: Vec<Calc<V>> = vec![];
669    for arg in args.drain(..) {
670      let mut found = None;
671      match &arg {
672        Calc::Value(val) => {
673          for b in reduced.iter_mut() {
674            if let Calc::Value(v) = b {
675              match val.partial_cmp(v) {
676                Some(ord) if ord == cmp => {
677                  found = Some(Some(b));
678                  break;
679                }
680                Some(_) => {
681                  found = Some(None);
682                  break;
683                }
684                None => {}
685              }
686            }
687          }
688        }
689        Calc::Number(val) => {
690          for b in reduced.iter_mut() {
691            if let Calc::Number(v) = b {
692              match val.partial_cmp(v) {
693                Some(ord) if ord == cmp => {
694                  found = Some(Some(b));
695                  break;
696                }
697                Some(_) => {
698                  found = Some(None);
699                  break;
700                }
701                None => {}
702              }
703            }
704          }
705        }
706        _ => {}
707      }
708      if let Some(r) = found {
709        if let Some(r) = r {
710          *r = arg
711        }
712      } else {
713        reduced.push(arg)
714      }
715    }
716    reduced
717  }
718
719  fn parse_math_fn<'t, O: FnOnce(f32, f32) -> f32, F: FnOnce(Calc<V>, Calc<V>) -> MathFunction<V>>(
720    input: &mut Parser<'i, 't>,
721    op: O,
722    fallback: F,
723    parse_ident: &dyn Fn(&str) -> Option<Calc<V>>,
724  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
725    let a: Calc<V> = Calc::parse_sum(input, parse_ident)?;
726    input.expect_comma()?;
727    let b: Calc<V> = Calc::parse_sum(input, parse_ident)?;
728
729    Ok(Self::apply_op(&a, &b, op).unwrap_or_else(|| Calc::Function(Box::new(fallback(a, b)))))
730  }
731
732  fn apply_op<'t, O: FnOnce(f32, f32) -> f32>(a: &Calc<V>, b: &Calc<V>, op: O) -> Option<Self> {
733    match (a, b) {
734      (Calc::Value(a), Calc::Value(b)) => {
735        if let Some(v) = a.try_op(&**b, op) {
736          return Some(Calc::Value(Box::new(v)));
737        }
738      }
739      (Calc::Number(a), Calc::Number(b)) => return Some(Calc::Number(op(*a, *b))),
740      _ => {}
741    }
742
743    None
744  }
745
746  fn apply_map<'t, O: FnOnce(f32) -> f32>(v: &Calc<V>, op: O) -> Option<Self> {
747    match v {
748      Calc::Number(n) => return Some(Calc::Number(op(*n))),
749      Calc::Value(v) => {
750        if let Some(v) = v.try_map(op) {
751          return Some(Calc::Value(Box::new(v)));
752        }
753      }
754      _ => {}
755    }
756
757    None
758  }
759
760  fn parse_trig<'t, F: FnOnce(f32) -> f32>(
761    input: &mut Parser<'i, 't>,
762    f: F,
763    to_angle: bool,
764    parse_ident: &dyn Fn(&str) -> Option<Calc<V>>,
765  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
766    input.parse_nested_block(|input| {
767      let v: Calc<Angle> = Calc::parse_sum(input, &|v| {
768        parse_ident(v).and_then(|v| -> Option<Calc<Angle>> {
769          match v {
770            Calc::Number(v) => Some(Calc::Number(v)),
771            Calc::Value(v) => (*v).try_into().ok().map(|v| Calc::Value(Box::new(v))),
772            _ => None,
773          }
774        })
775      })?;
776      let rad = match v {
777        Calc::Value(angle) if !to_angle => f(angle.to_radians()),
778        Calc::Number(v) => f(v),
779        _ => return Err(input.new_custom_error(ParserError::InvalidValue)),
780      };
781
782      if to_angle && !rad.is_nan() {
783        if let Ok(v) = V::try_from(Angle::Rad(rad)) {
784          return Ok(Calc::Value(Box::new(v)));
785        } else {
786          return Err(input.new_custom_error(ParserError::InvalidValue));
787        }
788      } else {
789        Ok(Calc::Number(rad))
790      }
791    })
792  }
793
794  fn parse_numeric<'t>(
795    input: &mut Parser<'i, 't>,
796    parse_ident: &dyn Fn(&str) -> Option<Calc<V>>,
797  ) -> Result<f32, ParseError<'i, ParserError<'i>>> {
798    let v: Calc<CSSNumber> = Calc::parse_sum(input, &|v| {
799      parse_ident(v).and_then(|v| match v {
800        Calc::Number(v) => Some(Calc::Number(v)),
801        _ => None,
802      })
803    })?;
804    match v {
805      Calc::Number(n) => Ok(n),
806      Calc::Value(v) => Ok(*v),
807      _ => Err(input.new_custom_error(ParserError::InvalidValue)),
808    }
809  }
810
811  fn parse_numeric_fn<'t, F: FnOnce(f32) -> f32>(
812    input: &mut Parser<'i, 't>,
813    f: F,
814    parse_ident: &dyn Fn(&str) -> Option<Calc<V>>,
815  ) -> Result<Self, ParseError<'i, ParserError<'i>>> {
816    input.parse_nested_block(|input| {
817      let v = Self::parse_numeric(input, parse_ident)?;
818      Ok(Calc::Number(f(v)))
819    })
820  }
821
822  fn parse_atan2<'t>(
823    input: &mut Parser<'i, 't>,
824    parse_ident: &dyn Fn(&str) -> Option<Calc<V>>,
825  ) -> Result<Angle, ParseError<'i, ParserError<'i>>> {
826    // atan2 supports arguments of any <number>, <dimension>, or <percentage>, even ones that wouldn't
827    // normally be supported by V. The only requirement is that the arguments be of the same type.
828    // Try parsing with each type, and return the first one that parses successfully.
829    if let Ok(v) = input.try_parse(|input| Calc::<Length>::parse_atan2_args(input, &|_| None)) {
830      return Ok(v);
831    }
832
833    if let Ok(v) = input.try_parse(|input| Calc::<Percentage>::parse_atan2_args(input, &|_| None)) {
834      return Ok(v);
835    }
836
837    if let Ok(v) = input.try_parse(|input| Calc::<Angle>::parse_atan2_args(input, &|_| None)) {
838      return Ok(v);
839    }
840
841    if let Ok(v) = input.try_parse(|input| Calc::<Time>::parse_atan2_args(input, &|_| None)) {
842      return Ok(v);
843    }
844
845    Calc::<CSSNumber>::parse_atan2_args(input, &|v| {
846      parse_ident(v).and_then(|v| match v {
847        Calc::Number(v) => Some(Calc::Number(v)),
848        _ => None,
849      })
850    })
851  }
852
853  fn parse_atan2_args<'t>(
854    input: &mut Parser<'i, 't>,
855    parse_ident: &dyn Fn(&str) -> Option<Calc<V>>,
856  ) -> Result<Angle, ParseError<'i, ParserError<'i>>> {
857    let a = Calc::<V>::parse_sum(input, parse_ident)?;
858    input.expect_comma()?;
859    let b = Calc::<V>::parse_sum(input, parse_ident)?;
860
861    match (&a, &b) {
862      (Calc::Value(a), Calc::Value(b)) => {
863        if let Some(v) = a.try_op_to(&**b, |a, b| Angle::Rad(a.atan2(b))) {
864          return Ok(v);
865        }
866      }
867      (Calc::Number(a), Calc::Number(b)) => return Ok(Angle::Rad(a.atan2(*b))),
868      _ => {}
869    }
870
871    // We don't have a way to represent arguments that aren't angles, so just error.
872    // This will fall back to an unparsed property, leaving the atan2() function intact.
873    Err(input.new_custom_error(ParserError::InvalidValue))
874  }
875
876  fn parse_hypot<'t>(args: &Vec<Self>) -> Result<Option<Self>, ParseError<'i, ParserError<'i>>> {
877    if args.len() == 1 {
878      return Ok(Some(args[0].clone()));
879    }
880
881    if args.len() == 2 {
882      return Ok(Self::apply_op(&args[0], &args[1], f32::hypot));
883    }
884
885    let mut iter = args.iter();
886    let first = match Self::apply_map(&iter.next().unwrap(), |v| v.powi(2)) {
887      Some(v) => v,
888      None => return Ok(None),
889    };
890    let sum = iter.try_fold(first, |acc, arg| {
891      Self::apply_op(&acc, &arg, |a, b| a + b.powi(2)).map_or_else(|| Err(()), |v| Ok(v))
892    });
893
894    let sum = match sum {
895      Ok(s) => s,
896      Err(_) => return Ok(None),
897    };
898
899    Ok(Self::apply_map(&sum, f32::sqrt))
900  }
901}
902
903impl<V: std::ops::Mul<f32, Output = V>> std::ops::Mul<f32> for Calc<V> {
904  type Output = Self;
905
906  fn mul(self, other: f32) -> Self {
907    if other == 1.0 {
908      return self;
909    }
910
911    match self {
912      Calc::Value(v) => Calc::Value(Box::new(*v * other)),
913      Calc::Number(n) => Calc::Number(n * other),
914      Calc::Sum(a, b) => Calc::Sum(Box::new(*a * other), Box::new(*b * other)),
915      Calc::Product(num, calc) => {
916        let num = num * other;
917        if num == 1.0 {
918          return *calc;
919        }
920        Calc::Product(num, calc)
921      }
922      Calc::Function(f) => match *f {
923        MathFunction::Calc(c) => Calc::Function(Box::new(MathFunction::Calc(c * other))),
924        _ => Calc::Product(other, Box::new(Calc::Function(f))),
925      },
926    }
927  }
928}
929
930impl<V: AddInternal + std::convert::Into<Calc<V>> + std::convert::TryFrom<Calc<V>> + std::fmt::Debug> Calc<V> {
931  pub(crate) fn add(self, other: Calc<V>) -> Result<Calc<V>, <V as TryFrom<Calc<V>>>::Error> {
932    Ok(match (self, other) {
933      (Calc::Value(a), Calc::Value(b)) => (a.add(*b)).into(),
934      (Calc::Number(a), Calc::Number(b)) => Calc::Number(a + b),
935      (Calc::Sum(a, b), Calc::Number(c)) => {
936        if let Calc::Number(a) = *a {
937          Calc::Sum(Box::new(Calc::Number(a + c)), b)
938        } else if let Calc::Number(b) = *b {
939          Calc::Sum(a, Box::new(Calc::Number(b + c)))
940        } else {
941          Calc::Sum(Box::new(Calc::Sum(a, b)), Box::new(Calc::Number(c)))
942        }
943      }
944      (Calc::Number(a), Calc::Sum(b, c)) => {
945        if let Calc::Number(b) = *b {
946          Calc::Sum(Box::new(Calc::Number(a + b)), c)
947        } else if let Calc::Number(c) = *c {
948          Calc::Sum(Box::new(Calc::Number(a + c)), b)
949        } else {
950          Calc::Sum(Box::new(Calc::Number(a)), Box::new(Calc::Sum(b, c)))
951        }
952      }
953      (a @ Calc::Number(_), b)
954      | (a, b @ Calc::Number(_))
955      | (a @ Calc::Product(..), b)
956      | (a, b @ Calc::Product(..)) => Calc::Sum(Box::new(a), Box::new(b)),
957      (Calc::Function(a), b) => Calc::Sum(Box::new(Calc::Function(a)), Box::new(b)),
958      (a, Calc::Function(b)) => Calc::Sum(Box::new(a), Box::new(Calc::Function(b))),
959      (Calc::Value(a), b) => (a.add(V::try_from(b)?)).into(),
960      (a, Calc::Value(b)) => (V::try_from(a)?.add(*b)).into(),
961      (a @ Calc::Sum(..), b @ Calc::Sum(..)) => V::try_from(a)?.add(V::try_from(b)?).into(),
962    })
963  }
964}
965
966impl<V: ToCss + std::ops::Mul<f32, Output = V> + TrySign + Clone + std::fmt::Debug> ToCss for Calc<V> {
967  fn to_css<PrinterT: crate::printer::PrinterTrait>(&self, dest: &mut PrinterT) -> Result<(), PrinterError> {
968    let old_in_calc = dest.in_calc();
969    dest.set_in_calc(true);
970    let res = match self {
971      Calc::Value(v) => v.to_css(dest),
972      Calc::Number(n) => n.to_css(dest),
973      Calc::Sum(a, b) => {
974        a.to_css(dest)?;
975        // Whitespace is always required.
976        let b = &**b;
977        if b.is_sign_negative() {
978          dest.write_str(" - ")?;
979          let b = b.clone() * -1.0;
980          b.to_css(dest)
981        } else {
982          dest.write_str(" + ")?;
983          b.to_css(dest)
984        }
985      }
986      Calc::Product(num, calc) => {
987        if num.abs() < 1.0 {
988          let div = 1.0 / num;
989          calc.to_css(dest)?;
990          dest.delim('/', true)?;
991          div.to_css(dest)
992        } else {
993          num.to_css(dest)?;
994          dest.delim('*', true)?;
995          calc.to_css(dest)
996        }
997      }
998      Calc::Function(f) => f.to_css(dest),
999    };
1000    dest.set_in_calc(old_in_calc);
1001    res
1002  }
1003}
1004
1005impl<V: TrySign> TrySign for Calc<V> {
1006  fn try_sign(&self) -> Option<f32> {
1007    match self {
1008      Calc::Number(v) => v.try_sign(),
1009      Calc::Value(v) => v.try_sign(),
1010      Calc::Product(c, v) => v.try_sign().map(|s| s * c.sign()),
1011      Calc::Function(f) => f.try_sign(),
1012      _ => None,
1013    }
1014  }
1015}
1016
1017impl<V: TrySign> TrySign for MathFunction<V> {
1018  fn try_sign(&self) -> Option<f32> {
1019    match self {
1020      MathFunction::Abs(_) => Some(1.0),
1021      MathFunction::Max(values) | MathFunction::Min(values) => {
1022        let mut iter = values.iter();
1023        if let Some(sign) = iter.next().and_then(|f| f.try_sign()) {
1024          for value in iter {
1025            if let Some(s) = value.try_sign() {
1026              if s != sign {
1027                return None;
1028              }
1029            } else {
1030              return None;
1031            }
1032          }
1033          return Some(sign);
1034        } else {
1035          return None;
1036        }
1037      }
1038      MathFunction::Clamp(a, b, c) => {
1039        if let (Some(a), Some(b), Some(c)) = (a.try_sign(), b.try_sign(), c.try_sign()) {
1040          if a == b && b == c {
1041            return Some(a);
1042          }
1043        }
1044        return None;
1045      }
1046      MathFunction::Round(_, a, b) => {
1047        if let (Some(a), Some(b)) = (a.try_sign(), b.try_sign()) {
1048          if a == b {
1049            return Some(a);
1050          }
1051        }
1052        return None;
1053      }
1054      MathFunction::Sign(v) => v.try_sign(),
1055      MathFunction::Calc(v) => v.try_sign(),
1056      _ => None,
1057    }
1058  }
1059}