1use std::fmt::{self, Write};
16
17use super::units::{Kind, Unit, write_number};
18use crate::parser::{Bracket, ComponentValue, Function};
19use crate::tokenizer::Token;
20
21const MAX_DEPTH: usize = 32;
24
25#[derive(Clone, Copy, Debug, PartialEq)]
27pub enum Leaf {
28 Number(f64),
29 Percentage(f64),
30 Dimension(f64, Unit),
31}
32
33impl Leaf {
34 pub fn value(self) -> f64 {
35 match self {
36 Leaf::Number(v) | Leaf::Percentage(v) | Leaf::Dimension(v, _) => v,
37 }
38 }
39
40 fn with_value(self, v: f64) -> Leaf {
41 match self {
42 Leaf::Number(_) => Leaf::Number(v),
43 Leaf::Percentage(_) => Leaf::Percentage(v),
44 Leaf::Dimension(_, u) => Leaf::Dimension(v, u),
45 }
46 }
47
48 fn same_unit(self, other: Leaf) -> bool {
50 match (self, other) {
51 (Leaf::Number(_), Leaf::Number(_)) | (Leaf::Percentage(_), Leaf::Percentage(_)) => true,
52 (Leaf::Dimension(_, a), Leaf::Dimension(_, b)) => a == b,
53 _ => false,
54 }
55 }
56
57 fn known(self) -> bool {
61 match self {
62 Leaf::Number(_) => true,
63 Leaf::Percentage(_) => false,
64 Leaf::Dimension(_, u) => u.canonical() == Some(u),
65 }
66 }
67
68 fn rank(self) -> (u8, &'static str) {
70 match self {
71 Leaf::Number(_) => (0, ""),
72 Leaf::Percentage(_) => (1, ""),
73 Leaf::Dimension(_, u) => (2, u.as_str()),
74 }
75 }
76
77 pub fn write(&self, out: &mut impl Write) -> fmt::Result {
79 match *self {
80 Leaf::Number(v) => write_number(out, v),
81 Leaf::Percentage(v) => {
82 write_number(out, v)?;
83 out.write_char('%')
84 }
85 Leaf::Dimension(v, u) if !v.is_finite() => {
86 write_number(out, v)?;
88 write!(out, " * 1{u}")
89 }
90 Leaf::Dimension(v, u) => {
91 write_number(out, v)?;
92 out.write_str(u.as_str())
93 }
94 }
95 }
96}
97
98impl fmt::Display for Leaf {
99 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
100 self.write(f)
101 }
102}
103
104#[derive(Clone, Copy, Debug, PartialEq, Eq)]
106pub enum Rounding {
107 Nearest,
108 Up,
109 Down,
110 ToZero,
111}
112
113#[derive(Clone, Copy, Debug, PartialEq, Eq)]
115pub enum MathFunction {
116 Min,
117 Max,
118 Clamp,
119 Round(Rounding),
120 Mod,
121 Rem,
122 Sin,
123 Cos,
124 Tan,
125 Asin,
126 Acos,
127 Atan,
128 Atan2,
129 Pow,
130 Sqrt,
131 Hypot,
132 Log,
133 Exp,
134 Abs,
135 Sign,
136 SiblingIndex,
139 SiblingCount,
140}
141
142impl MathFunction {
143 pub fn name(self) -> &'static str {
144 use MathFunction::*;
145 match self {
146 Min => "min",
147 Max => "max",
148 Clamp => "clamp",
149 Round(_) => "round",
150 Mod => "mod",
151 Rem => "rem",
152 Sin => "sin",
153 Cos => "cos",
154 Tan => "tan",
155 Asin => "asin",
156 Acos => "acos",
157 Atan => "atan",
158 Atan2 => "atan2",
159 Pow => "pow",
160 Sqrt => "sqrt",
161 Hypot => "hypot",
162 Log => "log",
163 Exp => "exp",
164 Abs => "abs",
165 Sign => "sign",
166 SiblingIndex => "sibling-index",
167 SiblingCount => "sibling-count",
168 }
169 }
170
171 fn from_name(name: &str) -> Option<MathFunction> {
172 use MathFunction::*;
173 let all = [
174 Min,
175 Max,
176 Clamp,
177 Round(Rounding::Nearest),
178 Mod,
179 Rem,
180 Sin,
181 Cos,
182 Tan,
183 Asin,
184 Acos,
185 Atan,
186 Atan2,
187 Pow,
188 Sqrt,
189 Hypot,
190 Log,
191 Exp,
192 Abs,
193 Sign,
194 SiblingIndex,
195 SiblingCount,
196 ];
197 all.into_iter()
198 .find(|f| f.name().eq_ignore_ascii_case(name))
199 }
200
201 fn arity(self) -> (usize, usize) {
203 use MathFunction::*;
204 match self {
205 Min | Max | Hypot => (1, usize::MAX),
206 Clamp => (3, 3),
207 Round(_) => (1, 2),
208 Mod | Rem | Atan2 | Pow => (2, 2),
209 Log => (1, 2),
210 Sin | Cos | Tan | Asin | Acos | Atan | Sqrt | Exp | Abs | Sign => (1, 1),
211 SiblingIndex | SiblingCount => (0, 0),
212 }
213 }
214}
215
216#[derive(Clone, Debug, PartialEq)]
218pub enum Node {
219 Value(Leaf),
220 Sum(Vec<Node>),
221 Product(Vec<Node>),
222 Negate(Box<Node>),
223 Invert(Box<Node>),
224 Function(MathFunction, Vec<Node>),
225 Keyword(&'static str),
228}
229
230type Keywords<'k> = &'k [&'static str];
231
232#[derive(Clone, Debug, PartialEq)]
242pub struct Math {
243 pub root: Node,
244}
245
246#[derive(Clone, Copy, Debug, Default, PartialEq, Eq)]
249struct Type([i8; 7]);
250
251const PERCENT: usize = 6;
252
253fn kind_index(k: Kind) -> usize {
254 match k {
255 Kind::Length => 0,
256 Kind::Angle => 1,
257 Kind::Time => 2,
258 Kind::Frequency => 3,
259 Kind::Resolution => 4,
260 Kind::Flex => 5,
261 }
262}
263
264impl Type {
265 fn one(i: usize) -> Type {
266 let mut t = Type::default();
267 t.0[i] = 1;
268 t
269 }
270
271 fn times(self, o: Type) -> Type {
272 let mut t = self;
273 for (a, b) in t.0.iter_mut().zip(o.0) {
274 *a = a.saturating_add(b);
275 }
276 t
277 }
278
279 fn inverse(self) -> Type {
280 Type(self.0.map(|e| e.saturating_neg()))
281 }
282}
283
284#[derive(Clone, Copy, Debug, PartialEq, Eq)]
286pub enum Expect {
287 Number,
288 Percentage,
289 Dimension(Kind),
290 DimensionPercentage(Kind),
292}
293
294impl Math {
295 pub fn parse(function: &Function<'_>) -> Option<Math> {
298 Math::parse_with(function, &[])
299 }
300
301 pub fn parse_with(function: &Function<'_>, keywords: &[&'static str]) -> Option<Math> {
304 let root = parse_function(function, 0, keywords)?;
305 let root = simplify(root);
306 any_type(&root)?;
308 Some(Math { root })
309 }
310
311 pub fn is_math_function(name: &str) -> bool {
313 name.eq_ignore_ascii_case("calc") || MathFunction::from_name(name).is_some()
314 }
315
316 pub fn fits(&self, expect: Expect) -> bool {
318 let (percent, want) = match expect {
319 Expect::Number => (None, Type::default()),
320 Expect::Percentage => (None, Type::one(PERCENT)),
321 Expect::Dimension(k) => (None, Type::one(kind_index(k))),
322 Expect::DimensionPercentage(k) => (Some(k), Type::one(kind_index(k))),
323 };
324 type_of(&self.root, percent, 0) == Some(want)
325 }
326
327 pub fn map_leaves(&self, f: &impl Fn(Leaf) -> Leaf) -> Math {
331 fn map(n: &Node, f: &impl Fn(Leaf) -> Leaf) -> Node {
332 match n {
333 Node::Value(l) => Node::Value(f(*l)),
334 Node::Keyword(k) => Node::Keyword(k),
335 Node::Sum(c) => Node::Sum(c.iter().map(|x| map(x, f)).collect()),
336 Node::Product(c) => Node::Product(c.iter().map(|x| map(x, f)).collect()),
337 Node::Negate(c) => Node::Negate(Box::new(map(c, f))),
338 Node::Invert(c) => Node::Invert(Box::new(map(c, f))),
339 Node::Function(func, args) => {
340 Node::Function(*func, args.iter().map(|x| map(x, f)).collect())
341 }
342 }
343 }
344 Math {
345 root: simplify(map(&self.root, f)),
346 }
347 }
348
349 pub fn substitute_keywords(&self, f: &impl Fn(&str) -> Option<f64>) -> Math {
352 fn map(n: &Node, f: &impl Fn(&str) -> Option<f64>) -> Node {
353 match n {
354 Node::Keyword(k) => f(k).map_or(Node::Keyword(k), |v| Node::Value(Leaf::Number(v))),
355 Node::Value(l) => Node::Value(*l),
356 Node::Sum(c) => Node::Sum(c.iter().map(|x| map(x, f)).collect()),
357 Node::Product(c) => Node::Product(c.iter().map(|x| map(x, f)).collect()),
358 Node::Negate(c) => Node::Negate(Box::new(map(c, f))),
359 Node::Invert(c) => Node::Invert(Box::new(map(c, f))),
360 Node::Function(func, args) => {
361 Node::Function(*func, args.iter().map(|x| map(x, f)).collect())
362 }
363 }
364 }
365 Math {
366 root: simplify(map(&self.root, f)),
367 }
368 }
369
370 pub fn leaf(&self) -> Option<Leaf> {
372 match self.root {
373 Node::Value(l) => Some(l),
374 _ => None,
375 }
376 }
377}
378
379fn any_type(root: &Node) -> Option<Type> {
381 type_of(root, None, 0).or_else(|| {
382 [
383 Kind::Length,
384 Kind::Angle,
385 Kind::Time,
386 Kind::Frequency,
387 Kind::Resolution,
388 ]
389 .into_iter()
390 .find_map(|k| type_of(root, Some(k), 0))
391 })
392}
393
394fn type_of(node: &Node, percent: Option<Kind>, depth: usize) -> Option<Type> {
395 if depth > MAX_DEPTH * 4 {
396 return None;
397 }
398 let same = |nodes: &[Node]| -> Option<Type> {
399 let first = type_of(&nodes[0], percent, depth + 1)?;
400 nodes[1..]
401 .iter()
402 .all(|n| type_of(n, percent, depth + 1) == Some(first))
403 .then_some(first)
404 };
405 let number = Type::default();
406 Some(match node {
407 Node::Value(Leaf::Number(_)) | Node::Keyword(_) => number,
408 Node::Value(Leaf::Percentage(_)) => match percent {
409 Some(k) => Type::one(kind_index(k)),
410 None => Type::one(PERCENT),
411 },
412 Node::Value(Leaf::Dimension(_, u)) => Type::one(kind_index(u.kind())),
413 Node::Sum(c) => same(c)?,
414 Node::Negate(c) => type_of(c, percent, depth + 1)?,
415 Node::Invert(c) => type_of(c, percent, depth + 1)?.inverse(),
416 Node::Product(c) => {
417 let mut t = number;
418 for n in c {
419 t = t.times(type_of(n, percent, depth + 1)?);
420 }
421 t
422 }
423 Node::Function(f, args) => {
424 use MathFunction::*;
425 match f {
426 Min | Max | Clamp | Hypot | Round(_) | Mod | Rem | Abs => same(args)?,
427 Sign => {
428 type_of(&args[0], percent, depth + 1)?;
429 number
430 }
431 Sin | Cos | Tan => {
432 let t = type_of(&args[0], percent, depth + 1)?;
433 if t != number && t != Type::one(kind_index(Kind::Angle)) {
434 return None;
435 }
436 number
437 }
438 Asin | Acos | Atan => {
439 if type_of(&args[0], percent, depth + 1)? != number {
440 return None;
441 }
442 Type::one(kind_index(Kind::Angle))
443 }
444 Atan2 => {
445 same(args)?;
446 Type::one(kind_index(Kind::Angle))
447 }
448 SiblingIndex | SiblingCount => number,
449 Pow | Sqrt | Log | Exp => {
450 if same(args)? != number {
451 return None;
452 }
453 number
454 }
455 }
456 }
457 })
458}
459
460fn parse_function(f: &Function<'_>, depth: usize, kw: Keywords) -> Option<Node> {
463 if depth > MAX_DEPTH {
464 return None;
465 }
466 if f.name.eq_ignore_ascii_case("calc") {
467 return parse_sum(&f.arguments, depth + 1, kw);
468 }
469 let mut kind = MathFunction::from_name(&f.name)?;
470 let mut groups: Vec<&[ComponentValue<'_>]> = f
471 .arguments
472 .split(|v| matches!(v, ComponentValue::Token(Token::Comma, _)))
473 .collect();
474 if let MathFunction::Round(_) = kind {
475 let words: Vec<_> = groups[0].iter().filter(|v| !v.is_whitespace()).collect();
477 if let [ComponentValue::Token(Token::Ident(w), _)] = words[..] {
478 let r = match w.to_ascii_lowercase().as_str() {
479 "nearest" => Some(Rounding::Nearest),
480 "up" => Some(Rounding::Up),
481 "down" => Some(Rounding::Down),
482 "to-zero" => Some(Rounding::ToZero),
483 _ => None,
484 };
485 if let Some(r) = r {
486 kind = MathFunction::Round(r);
487 groups.remove(0);
488 }
489 }
490 }
491 if groups.len() == 1 && groups[0].iter().all(ComponentValue::is_whitespace) {
492 groups.clear();
493 }
494 let (min, max) = kind.arity();
495 if groups.len() < min || groups.len() > max {
496 return None;
497 }
498 let args = groups
499 .into_iter()
500 .map(|g| parse_sum(g, depth + 1, kw))
501 .collect::<Option<Vec<_>>>()?;
502 Some(Node::Function(kind, args))
503}
504
505fn parse_sum(values: &[ComponentValue<'_>], depth: usize, kw: Keywords) -> Option<Node> {
507 if depth > MAX_DEPTH {
508 return None;
509 }
510 let mut terms = Vec::new();
511 let mut start = 0;
512 let mut negate = false;
513 let mut i = 0;
514 while i < values.len() {
515 let op = match &values[i] {
516 ComponentValue::Token(Token::Delim(c @ ('+' | '-')), _) => *c,
517 _ => {
518 i += 1;
519 continue;
520 }
521 };
522 let spaced = i > 0
523 && values[i - 1].is_whitespace()
524 && values.get(i + 1).is_some_and(ComponentValue::is_whitespace);
525 if !spaced {
526 return None;
527 }
528 let term = parse_product(&values[start..i], depth, kw)?;
529 terms.push(if negate {
530 Node::Negate(Box::new(term))
531 } else {
532 term
533 });
534 negate = op == '-';
535 start = i + 1;
536 i += 1;
537 }
538 let term = parse_product(&values[start..], depth, kw)?;
539 terms.push(if negate {
540 Node::Negate(Box::new(term))
541 } else {
542 term
543 });
544 Some(if terms.len() == 1 {
545 terms.pop().unwrap()
546 } else {
547 Node::Sum(terms)
548 })
549}
550
551fn parse_product(values: &[ComponentValue<'_>], depth: usize, kw: Keywords) -> Option<Node> {
553 let mut factors = Vec::new();
554 let mut invert = false;
555 let mut expect_value = true;
556 for v in values.iter().filter(|v| !v.is_whitespace()) {
557 if expect_value {
558 let node = parse_value(v, depth, kw)?;
559 factors.push(if invert {
560 Node::Invert(Box::new(node))
561 } else {
562 node
563 });
564 expect_value = false;
565 continue;
566 }
567 match v {
568 ComponentValue::Token(Token::Delim('*'), _) => invert = false,
569 ComponentValue::Token(Token::Delim('/'), _) => invert = true,
570 _ => return None,
571 }
572 expect_value = true;
573 }
574 if expect_value {
575 return None;
576 }
577 Some(if factors.len() == 1 {
578 factors.pop().unwrap()
579 } else {
580 Node::Product(factors)
581 })
582}
583
584fn parse_value(v: &ComponentValue<'_>, depth: usize, kw: Keywords) -> Option<Node> {
585 let leaf = match v {
586 ComponentValue::Token(Token::Number(n), _) => Leaf::Number(n.value),
587 ComponentValue::Token(Token::Percentage(n), _) => Leaf::Percentage(n.value),
588 ComponentValue::Token(Token::Dimension { number, unit }, _) => {
589 Leaf::Dimension(number.value, Unit::parse(unit)?)
590 }
591 ComponentValue::Token(Token::Ident(word), _) => {
592 if let Some(k) = kw.iter().find(|k| word.eq_ignore_ascii_case(k)) {
593 return Some(Node::Keyword(k));
594 }
595 Leaf::Number(match word.to_ascii_lowercase().as_str() {
596 "e" => std::f64::consts::E,
597 "pi" => std::f64::consts::PI,
598 "infinity" => f64::INFINITY,
599 "-infinity" => f64::NEG_INFINITY,
600 "nan" => f64::NAN,
601 _ => return None,
602 })
603 }
604 ComponentValue::Block(b) if b.bracket == Bracket::Paren => {
605 return parse_sum(&b.contents, depth + 1, kw);
606 }
607 ComponentValue::Function(f) => return parse_function(f, depth + 1, kw),
608 _ => return None,
609 };
610 Some(Node::Value(leaf))
611}
612
613fn canonical(leaf: Leaf) -> Leaf {
617 match leaf {
618 Leaf::Dimension(v, u) => match (u.canonical(), u.to_canonical()) {
619 (Some(c), Some(f)) => Leaf::Dimension(v * f, c),
620 _ => leaf,
621 },
622 l => l,
623 }
624}
625
626fn simplify(node: Node) -> Node {
627 match node {
628 Node::Value(l) => Node::Value(canonical(l)),
629 Node::Keyword(k) => Node::Keyword(k),
630 Node::Negate(c) => match simplify(*c) {
631 Node::Value(l) => Node::Value(l.with_value(-l.value())),
632 Node::Negate(g) => *g,
633 c => Node::Negate(Box::new(c)),
634 },
635 Node::Invert(c) => match simplify(*c) {
636 Node::Value(Leaf::Number(v)) => Node::Value(Leaf::Number(1.0 / v)),
637 Node::Invert(g) => *g,
638 c => Node::Invert(Box::new(c)),
639 },
640 Node::Sum(children) => simplify_sum(children),
641 Node::Product(children) => simplify_product(children),
642 Node::Function(f, args) => {
643 let args: Vec<Node> = args.into_iter().map(simplify).collect();
644 compute(f, &args).map_or(Node::Function(f, args), Node::Value)
645 }
646 }
647}
648
649fn simplify_sum(children: Vec<Node>) -> Node {
650 let mut flat = Vec::new();
651 for c in children {
652 match simplify(c) {
653 Node::Sum(inner) => flat.extend(inner),
654 c => flat.push(c),
655 }
656 }
657 let mut out: Vec<Node> = Vec::new();
659 for c in flat {
660 if let Node::Value(l) = c
661 && let Some(Node::Value(prev)) = out
662 .iter_mut()
663 .find(|o| matches!(o, Node::Value(p) if p.same_unit(l)))
664 {
665 *prev = prev.with_value(prev.value() + l.value());
666 continue;
667 }
668 out.push(c);
669 }
670 if out.len() == 1 {
671 out.pop().unwrap()
672 } else {
673 Node::Sum(out)
674 }
675}
676
677fn simplify_product(children: Vec<Node>) -> Node {
678 let mut flat = Vec::new();
679 for c in children {
680 match simplify(c) {
681 Node::Product(inner) => flat.extend(inner),
682 c => flat.push(c),
683 }
684 }
685 let mut number: Option<f64> = None;
687 let mut rest = Vec::new();
688 for c in flat {
689 match c {
690 Node::Value(Leaf::Number(v)) => *number.get_or_insert(1.0) *= v,
691 c => rest.push(c),
692 }
693 }
694 let Some(n) = number else {
695 return product_of(rest);
696 };
697 match rest.as_mut_slice() {
698 [] => return Node::Value(Leaf::Number(n)),
699 [Node::Value(l)] => return Node::Value(l.with_value(l.value() * n)),
701 [Node::Sum(terms)] if terms.iter().all(|t| matches!(t, Node::Value(_))) => {
702 for t in terms.iter_mut() {
703 if let Node::Value(l) = t {
704 *l = l.with_value(l.value() * n);
705 }
706 }
707 return rest.pop().unwrap();
708 }
709 _ => {}
710 }
711 rest.insert(0, Node::Value(Leaf::Number(n)));
712 product_of(rest)
713}
714
715fn product_of(mut nodes: Vec<Node>) -> Node {
716 if nodes.len() == 1 {
717 nodes.pop().unwrap()
718 } else {
719 Node::Product(nodes)
720 }
721}
722
723fn compute(f: MathFunction, args: &[Node]) -> Option<Leaf> {
725 use MathFunction::*;
726 if matches!(f, SiblingIndex | SiblingCount) {
727 return None;
728 }
729 let leaves: Vec<Leaf> = args
730 .iter()
731 .map(|a| match a {
732 Node::Value(l) => Some(*l),
733 _ => None,
734 })
735 .collect::<Option<_>>()?;
736 let first = leaves[0];
737 let alike = leaves
739 .iter()
740 .all(|l| l.same_unit(first) && (l.known() || matches!(l, Leaf::Percentage(_))));
741 let v: Vec<f64> = leaves.iter().map(|l| l.value()).collect();
742 let number = |x: f64| Some(Leaf::Number(x));
743 let angle = |x: f64| Some(Leaf::Dimension(x.to_degrees(), Unit::Deg));
744 let radians = |l: Leaf| match l {
745 Leaf::Number(x) => Some(x),
746 Leaf::Dimension(x, Unit::Deg) => Some(x.to_radians()),
747 _ => None,
748 };
749 match f {
750 SiblingIndex | SiblingCount => None,
751 Min | Max | Clamp | Hypot | Round(_) | Mod | Rem | Abs if !alike => None,
752 Min => Some(first.with_value(v.iter().copied().fold(f64::INFINITY, nan_min))),
753 Max => Some(first.with_value(v.iter().copied().fold(f64::NEG_INFINITY, nan_max))),
754 Clamp => Some(first.with_value(nan_max(v[0], nan_min(v[1], v[2])))),
755 Hypot => Some(first.with_value(v.iter().map(|x| x * x).sum::<f64>().sqrt())),
756 Abs => Some(first.with_value(v[0].abs())),
757 Round(r) => {
758 let step = v.get(1).copied().unwrap_or(1.0);
759 Some(first.with_value(round(r, v[0], step)))
760 }
761 Mod | Rem => {
762 let (a, b) = (v[0], v[1]);
763 let mut m = a % b;
764 if f == Mod && m != 0.0 && (m < 0.0) != (b < 0.0) {
765 m += b;
766 }
767 Some(first.with_value(m))
768 }
769 Sign if first.known() => number(if v[0] == 0.0 || v[0].is_nan() {
770 v[0]
771 } else {
772 v[0].signum()
773 }),
774 Sign => None,
775 Sin => number(radians(first)?.sin()),
776 Cos => number(radians(first)?.cos()),
777 Tan => number(radians(first)?.tan()),
778 Asin => angle(radians(first)?.asin()),
779 Acos => angle(radians(first)?.acos()),
780 Atan => angle(radians(first)?.atan()),
781 Atan2 if alike => angle(v[0].atan2(v[1])),
782 Atan2 => None,
783 Pow => number(v[0].powf(v[1])),
784 Sqrt => number(v[0].sqrt()),
785 Exp => number(v[0].exp()),
786 Log => number(match v.get(1) {
787 Some(base) => v[0].ln() / base.ln(),
788 None => v[0].ln(),
789 }),
790 }
791}
792
793fn nan_min(a: f64, b: f64) -> f64 {
795 if a.is_nan() || b.is_nan() {
796 f64::NAN
797 } else {
798 a.min(b)
799 }
800}
801
802fn nan_max(a: f64, b: f64) -> f64 {
803 if a.is_nan() || b.is_nan() {
804 f64::NAN
805 } else {
806 a.max(b)
807 }
808}
809
810fn round(r: Rounding, a: f64, b: f64) -> f64 {
811 if b == 0.0 {
812 return f64::NAN;
813 }
814 if b.is_infinite() {
815 return if a.is_infinite() {
816 f64::NAN
817 } else {
818 a.signum() * 0.0
819 };
820 }
821 let q = a / b;
822 let n = match r {
823 Rounding::Nearest => (q + 0.5).floor(),
824 Rounding::Up => q.ceil(),
825 Rounding::Down => q.floor(),
826 Rounding::ToZero => q.trunc(),
827 };
828 n * b
829}
830
831fn rank(node: &Node) -> (u8, &'static str) {
834 match node {
835 Node::Value(l) => l.rank(),
836 _ => (3, ""),
837 }
838}
839
840fn sorted(nodes: &[Node]) -> Vec<&Node> {
841 let mut v: Vec<&Node> = nodes.iter().collect();
842 v.sort_by(|a, b| rank(a).cmp(&rank(b)));
844 v
845}
846
847fn write_node(out: &mut String, node: &Node) {
848 match node {
849 Node::Value(l) => l.write(out).unwrap(),
850 Node::Keyword(k) => out.push_str(k),
851 Node::Function(f, args) => write_function(out, *f, args),
852 Node::Negate(c) => {
853 out.push_str("(-1 * ");
854 write_node(out, c);
855 out.push(')');
856 }
857 Node::Invert(c) => {
858 out.push_str("(1 / ");
859 write_node(out, c);
860 out.push(')');
861 }
862 Node::Sum(children) => {
863 out.push('(');
864 for (i, c) in sorted(children).into_iter().enumerate() {
865 if i == 0 {
866 write_node(out, c);
867 continue;
868 }
869 match c {
870 Node::Negate(inner) => {
871 out.push_str(" - ");
872 write_node(out, inner);
873 }
874 Node::Value(l) if l.value() < 0.0 => {
875 out.push_str(" - ");
876 l.with_value(-l.value()).write(out).unwrap();
877 }
878 c => {
879 out.push_str(" + ");
880 write_node(out, c);
881 }
882 }
883 }
884 out.push(')');
885 }
886 Node::Product(children) => {
887 out.push('(');
888 for (i, c) in sorted(children).into_iter().enumerate() {
889 match c {
890 Node::Invert(inner) if i > 0 => {
891 out.push_str(" / ");
892 write_node(out, inner);
893 }
894 c => {
895 if i > 0 {
896 out.push_str(" * ");
897 }
898 write_node(out, c);
899 }
900 }
901 }
902 out.push(')');
903 }
904 }
905}
906
907fn write_bare(out: &mut String, node: &Node) {
909 let mut s = String::new();
910 write_node(&mut s, node);
911 let bare = match (s.strip_prefix('('), s.ends_with(')')) {
912 (Some(inner), true) if matches!(node, Node::Sum(_) | Node::Product(_)) => {
913 &inner[..inner.len() - 1]
914 }
915 _ => &s,
916 };
917 out.push_str(bare);
918}
919
920fn write_function(out: &mut String, f: MathFunction, args: &[Node]) {
921 out.push_str(f.name());
922 out.push('(');
923 if let MathFunction::Round(r) = f {
924 let strategy = match r {
925 Rounding::Nearest => "",
926 Rounding::Up => "up, ",
927 Rounding::Down => "down, ",
928 Rounding::ToZero => "to-zero, ",
929 };
930 out.push_str(strategy);
931 }
932 for (i, a) in args.iter().enumerate() {
933 if i > 0 {
934 out.push_str(", ");
935 }
936 write_bare(out, a);
937 }
938 out.push(')');
939}
940
941impl fmt::Display for Math {
942 fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
943 let mut s = String::new();
944 match &self.root {
945 Node::Function(func, args) => write_function(&mut s, *func, args),
946 root => {
947 s.push_str("calc(");
948 write_bare(&mut s, root);
949 s.push(')');
950 }
951 }
952 f.write_str(&s)
953 }
954}
955
956#[cfg(test)]
957mod tests {
958 use super::*;
959
960 fn calc(css: &str) -> Option<String> {
961 let values = crate::parse_component_values(css);
962 let ComponentValue::Function(f) = &values[0] else {
963 return None;
964 };
965 Math::parse(f).map(|m| m.to_string())
966 }
967
968 #[test]
969 fn simplifies_and_serializes() {
970 let cases = [
971 ("calc(1px + 2px)", "calc(3px)"),
972 ("calc(1in)", "calc(96px)"),
973 ("calc(10px + 5%)", "calc(5% + 10px)"),
974 ("calc(1em - 2px)", "calc(1em - 2px)"),
975 ("calc(2 * (1em + 2px))", "calc(2em + 4px)"),
976 (
977 "calc(50% + (sign(1em - 10px) * 10%))",
978 "calc(50% + (10% * sign(1em - 10px)))",
979 ),
980 ("min(1px, 2px)", "calc(1px)"),
981 ("min(1em, 2px)", "min(1em, 2px)"),
982 ("calc(min(1em, 2px))", "min(1em, 2px)"),
983 ("clamp(1px, 5px, 3px)", "calc(3px)"),
984 ("calc(infinity)", "calc(infinity)"),
985 ("calc(0 / 0)", "calc(NaN)"),
986 ("round(up, 2.5, 1)", "calc(3)"),
987 ("mod(-5, 3)", "calc(1)"),
988 ("rem(-5, 3)", "calc(-2)"),
989 ("calc(1px * 2 / 4)", "calc(0.5px)"),
990 ("sin(90deg)", "calc(1)"),
991 ("atan2(1px, 1px)", "calc(45deg)"),
992 ];
993 for (css, want) in cases {
994 assert_eq!(calc(css).as_deref(), Some(want), "{css}");
995 }
996 }
997
998 #[test]
999 fn rejects_bad_syntax_and_types() {
1000 for css in [
1001 "calc(1px+2px)",
1002 "calc(1px + 2)",
1003 "calc()",
1004 "calc(1px 2px)",
1005 "calc(1foo)",
1006 "sin(1px)",
1007 ] {
1008 assert_eq!(calc(css), None, "{css}");
1009 }
1010 let values = crate::parse_component_values("calc(10% + 1px)");
1011 let ComponentValue::Function(f) = &values[0] else {
1012 unreachable!()
1013 };
1014 let m = Math::parse(f).unwrap();
1015 assert!(m.fits(Expect::DimensionPercentage(Kind::Length)));
1016 assert!(!m.fits(Expect::Dimension(Kind::Length)));
1017 }
1018
1019 #[test]
1020 fn deep_nesting_is_invalid_not_a_crash() {
1021 let css = format!("calc({}1{})", "(".repeat(10_000), ")".repeat(10_000));
1022 assert_eq!(calc(&css), None);
1023 }
1024}