Skip to main content

style/values/generics/
calc.rs

1/* This Source Code Form is subject to the terms of the Mozilla Public
2 * License, v. 2.0. If a copy of the MPL was not distributed with this
3 * file, You can obtain one at https://mozilla.org/MPL/2.0/. */
4
5//! [Calc expressions][calc].
6//!
7//! [calc]: https://drafts.csswg.org/css-values/#calc-notation
8
9use crate::derives::*;
10use crate::typed_om::{
11    MathClamp, MathInvert, MathMax, MathMin, MathNegate, MathProduct, MathSum, MathValue,
12    NumericBaseType, NumericType, NumericValue, ToTyped, TypedValue,
13};
14use crate::values::calc_random;
15use crate::values::specified::NoCalcPercentage;
16use crate::values::generics::Optional;
17use crate::values::generics::length::GenericAnchorSizeFunction;
18use crate::values::generics::position::{GenericAnchorFunction, GenericAnchorSide};
19use num_traits::Zero;
20use smallvec::SmallVec;
21use std::convert::AsRef;
22use std::fmt::{self, Write};
23use std::ops::{Add, Mul, Rem, Sub};
24use std::{cmp, mem};
25use strum_macros::AsRefStr;
26use style_traits::{CssWriter, ToCss};
27
28use thin_vec::ThinVec;
29
30/// Whether we're a `min` or `max` function.
31#[derive(
32    Clone,
33    Copy,
34    Debug,
35    Deserialize,
36    MallocSizeOf,
37    PartialEq,
38    Serialize,
39    ToAnimatedZero,
40    ToResolvedValue,
41    ToShmem,
42)]
43#[repr(u8)]
44pub enum MinMaxOp {
45    /// `min()`
46    Min,
47    /// `max()`
48    Max,
49}
50
51/// Whether we're a `mod` or `rem` function.
52#[derive(
53    Clone,
54    Copy,
55    Debug,
56    Deserialize,
57    MallocSizeOf,
58    PartialEq,
59    Serialize,
60    ToAnimatedZero,
61    ToResolvedValue,
62    ToShmem,
63)]
64#[repr(u8)]
65pub enum ModRemOp {
66    /// `mod()`
67    Mod,
68    /// `rem()`
69    Rem,
70}
71
72impl ModRemOp {
73    fn apply(self, dividend: f32, divisor: f32) -> f32 {
74        // In mod(A, B) only, if B is infinite and A has opposite sign to B
75        // (including an oppositely-signed zero), the result is NaN.
76        // https://drafts.csswg.org/css-values/#round-infinities
77        if matches!(self, Self::Mod)
78            && divisor.is_infinite()
79            && dividend.is_sign_negative() != divisor.is_sign_negative()
80        {
81            return f32::NAN;
82        }
83
84        let (r, same_sign_as) = match self {
85            Self::Mod => (dividend - divisor * (dividend / divisor).floor(), divisor),
86            Self::Rem => (dividend - divisor * (dividend / divisor).trunc(), dividend),
87        };
88        if r == 0.0 && same_sign_as.is_sign_negative() {
89            -0.0
90        } else {
91            r
92        }
93    }
94}
95
96/// The strategy used in `round()`
97#[derive(
98    Clone,
99    Copy,
100    Debug,
101    Deserialize,
102    MallocSizeOf,
103    PartialEq,
104    Serialize,
105    ToAnimatedZero,
106    ToResolvedValue,
107    ToShmem,
108)]
109#[repr(u8)]
110pub enum RoundingStrategy {
111    /// `round(nearest, a, b)`
112    /// round a to the nearest multiple of b
113    Nearest,
114    /// `round(up, a, b)`
115    /// round a up to the nearest multiple of b
116    Up,
117    /// `round(down, a, b)`
118    /// round a down to the nearest multiple of b
119    Down,
120    /// `round(to-zero, a, b)`
121    /// round a to the nearest multiple of b that is towards zero
122    ToZero,
123}
124
125/// The clamping mode used in `progress()`
126#[derive(
127    Clone,
128    Copy,
129    Debug,
130    Deserialize,
131    MallocSizeOf,
132    Parse,
133    PartialEq,
134    Serialize,
135    ToAnimatedZero,
136    ToCss,
137    ToResolvedValue,
138    ToShmem,
139)]
140#[repr(u8)]
141pub enum ProgressClampingMode {
142    /// `progress(value, start, end)`
143    /// Progress result is clamped to the range [0, 1}.
144    #[css(skip)]
145    Clamp,
146    /// `progress(no-clamp value, start, end)`
147    /// Progress result can be any number.
148    NoClamp,
149}
150
151impl ProgressClampingMode {
152    fn evaluate(self, value: f32, start: f32, end: f32) -> f32 {
153        if start == end && self == Self::Clamp {
154            return 0.;
155        }
156        let progress = crate::values::normalize((value - start) / (end - start));
157        match self {
158            Self::Clamp => progress.max(0.).min(1.),
159            Self::NoClamp => progress,
160        }
161    }
162}
163
164/// This determines the order in which we serialize members of a calc() sum.
165///
166/// See https://drafts.csswg.org/css-values-4/#sort-a-calculations-children
167#[derive(
168    AsRefStr, Clone, Copy, Debug, Eq, Ord, Parse, PartialEq, PartialOrd, MallocSizeOf, ToShmem,
169)]
170#[strum(serialize_all = "lowercase")]
171#[allow(missing_docs)]
172pub enum SortKey {
173    #[strum(serialize = "")]
174    Number,
175    #[css(skip)]
176    #[strum(serialize = "%")]
177    Percentage,
178    Cap,
179    Ch,
180    Cqb,
181    Cqh,
182    Cqi,
183    Cqmax,
184    Cqmin,
185    Cqw,
186    Deg,
187    Dppx,
188    Dvb,
189    Dvh,
190    Dvi,
191    Dvmax,
192    Dvmin,
193    Dvw,
194    Em,
195    Ex,
196    Ic,
197    Lh,
198    Lvb,
199    Lvh,
200    Lvi,
201    Lvmax,
202    Lvmin,
203    Lvw,
204    Ms,
205    Px,
206    Rcap,
207    Rch,
208    Rem,
209    Rex,
210    Ric,
211    Rlh,
212    S, // Sec
213    Svb,
214    Svh,
215    Svi,
216    Svmax,
217    Svmin,
218    Svw,
219    Vb,
220    Vh,
221    Vi,
222    Vmax,
223    Vmin,
224    Vw,
225    #[css(skip)]
226    ColorComponent,
227    #[css(skip)]
228    Other,
229}
230
231/// Fallback type for anchor functions within `calc()`.
232/// Ideally, the fallback type is initial type of the property (e.g.
233/// `GenericInset` for `left`), but that causes circular reference.
234/// TODO(dshin, bug 2034100): Investigate ways to not require this.
235/// This handles the parsing of unitless zeros, as well as ensuring
236/// that e.g. `calc(anchor(--foo left, 1px) + 10%)` round trips
237/// (sorting aside), instead of becoming
238/// `calc(anchor(--foo left, calc(1px)) + 10%)`.
239#[repr(C)]
240#[derive(
241    Clone,
242    Debug,
243    Deserialize,
244    MallocSizeOf,
245    PartialEq,
246    Serialize,
247    ToAnimatedZero,
248    ToResolvedValue,
249    ToShmem,
250)]
251pub struct GenericAnchorFunctionFallback<L> {
252    /// Was this node parsed as a calc node?
253    #[animation(constant)]
254    is_calc_node: bool,
255    /// The parsed fallback value. Stored as a calc node to break
256    /// the circular reference.
257    pub node: GenericCalcNode<L>,
258}
259
260impl<L> GenericAnchorFunctionFallback<L> {
261    /// Create a new anchor function fallback value.
262    pub fn new(is_calc_node: bool, node: GenericCalcNode<L>) -> Self {
263        Self { is_calc_node, node }
264    }
265}
266
267impl<L: CalcNodeLeaf> ToCss for GenericAnchorFunctionFallback<L> {
268    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
269    where
270        W: Write,
271    {
272        self.node.to_css_impl(
273            dest,
274            if self.is_calc_node {
275                ArgumentLevel::CalculationRoot
276            } else {
277                ArgumentLevel::ArgumentRoot
278            },
279        )
280    }
281}
282
283/// `anchor()` function used in math functions.
284pub type GenericCalcAnchorFunction<L> =
285    GenericAnchorFunction<Box<GenericCalcNode<L>>, Box<GenericAnchorFunctionFallback<L>>>;
286/// `anchor-size()` function used in math functions.
287pub type GenericCalcAnchorSizeFunction<L> =
288    GenericAnchorSizeFunction<Box<GenericAnchorFunctionFallback<L>>>;
289
290/// A `random()` function.
291/// https://drafts.csswg.org/css-values-5/#funcdef-random
292#[repr(C)]
293#[derive(
294    Clone,
295    Debug,
296    Deserialize,
297    MallocSizeOf,
298    PartialEq,
299    Serialize,
300    ToAnimatedZero,
301    ToResolvedValue,
302    ToShmem,
303)]
304pub struct GenericRandomFunction<L> {
305    /// The `<random-key>`, resolving to the random base value.
306    pub key: GenericCalcNode<L>,
307    /// The minimum value the function can resolve to, inclusive.
308    pub min: GenericCalcNode<L>,
309    /// The maximum value the function can resolve to, inclusive.
310    pub max: GenericCalcNode<L>,
311    /// The optional step value.
312    pub step: Optional<GenericCalcNode<L>>,
313}
314
315/// A generic node in a calc expression.
316///
317/// FIXME: This would be much more elegant if we used `Self` in the types below,
318/// but we can't because of https://github.com/serde-rs/serde/issues/1565.
319///
320/// FIXME: The following annotations are to workaround an LLVM inlining bug, see
321/// bug 1631929.
322///
323/// cbindgen:destructor-attributes=MOZ_NEVER_INLINE
324/// cbindgen:copy-constructor-attributes=MOZ_NEVER_INLINE
325/// cbindgen:eq-attributes=MOZ_NEVER_INLINE
326#[repr(u8)]
327#[derive(
328    Clone,
329    Debug,
330    Deserialize,
331    MallocSizeOf,
332    PartialEq,
333    Serialize,
334    ToAnimatedZero,
335    ToResolvedValue,
336    ToShmem,
337)]
338pub enum GenericCalcNode<L> {
339    /// A leaf node.
340    Leaf(L),
341    /// A node that negates its child, e.g. Negate(1) == -1.
342    Negate(Box<Self>),
343    /// A node that inverts its child, e.g. Invert(10) == 1 / 10 == 0.1. The child must always
344    /// resolve to a number unit.
345    Invert(Box<Self>),
346    /// A sum node, representing `a + b + c` where a, b, and c are the
347    /// arguments.
348    Sum(crate::OwnedSlice<Self>),
349    /// A product node, representing `a * b * c` where a, b, and c are the
350    /// arguments.
351    Product(crate::OwnedSlice<Self>),
352    /// A `min` or `max` function.
353    MinMax(crate::OwnedSlice<Self>, MinMaxOp),
354    /// A `clamp()` function.
355    Clamp {
356        /// The minimum value.
357        min: Box<Self>,
358        /// The central value.
359        center: Box<Self>,
360        /// The maximum value.
361        max: Box<Self>,
362    },
363    /// A `round()` function.
364    Round {
365        /// The rounding strategy.
366        strategy: RoundingStrategy,
367        /// The value to round.
368        value: Box<Self>,
369        /// The step value.
370        step: Box<Self>,
371    },
372    /// A `mod()` or `rem()` function.
373    ModRem {
374        /// The dividend calculation.
375        dividend: Box<Self>,
376        /// The divisor calculation.
377        divisor: Box<Self>,
378        /// Is the function mod or rem?
379        op: ModRemOp,
380    },
381    /// A `sin()` function.
382    Sin(Box<Self>),
383    /// A `cos()` function.
384    Cos(Box<Self>),
385    /// A `tan()` function.
386    Tan(Box<Self>),
387    /// An `asin()` function.
388    Asin(Box<Self>),
389    /// An `acos()` function.
390    Acos(Box<Self>),
391    /// An `atan()` function.
392    Atan(Box<Self>),
393    /// An `atan2()` function.
394    Atan2(Box<Self>, Box<Self>),
395    /// A `pow()` function.
396    Pow(Box<Self>, Box<Self>),
397    /// A `sqrt()` function.
398    Sqrt(Box<Self>),
399    /// A `hypot()` function
400    Hypot(crate::OwnedSlice<Self>),
401    /// A `log()` function.
402    Log(Box<Self>, Optional<Box<Self>>),
403    /// An `exp()` function.
404    Exp(Box<Self>),
405    /// An `abs()` function.
406    Abs(Box<Self>),
407    /// A `sign()` function.
408    Sign(Box<Self>),
409    /// A `progress()` function.
410    Progress {
411        /// Clamping mode for the result.
412        clamping_mode: ProgressClampingMode,
413        /// The progress value calculation.
414        value: Box<Self>,
415        /// The progress start calculation.
416        start: Box<Self>,
417        /// The progress end calculation.
418        end: Box<Self>,
419    },
420    /// A `random()` function.
421    Random(Box<GenericRandomFunction<L>>),
422    /// An `anchor()` function.
423    Anchor(Box<GenericCalcAnchorFunction<L>>),
424    /// An `anchor-size()` function.
425    AnchorSize(Box<GenericCalcAnchorSizeFunction<L>>),
426}
427
428pub use self::GenericCalcNode as CalcNode;
429
430fn typed_arithmetic_enabled() -> bool {
431    crate::pref!("layout.css.calc-typed-arithmetic.enabled")
432}
433
434/// The non-mixed types that a math function can return. Note that
435/// <integer> is not represented in this list as a separate type from
436/// <number>, as "math functions that resolve to <number> can be used
437/// in any place that only accepts <integer>". CSS Typed OM also does
438/// not distinguish between numbers and integers.
439///
440/// https://drafts.csswg.org/css-values-4/#math-function
441/// https://drafts.csswg.org/css-values-4/#calc-type-checking
442///
443/// TODO(Bug 1866236) - Add the <flex> type.
444#[derive(Clone, Copy, PartialEq, Eq)]
445#[repr(u8)]
446pub enum CalcType {
447    /// <length>
448    Length,
449    /// <percentage>
450    Percentage,
451    /// <angle>
452    Angle,
453    /// <time>
454    Time,
455    /// <resolution>
456    Resolution,
457    /// <number>
458    Number,
459}
460
461/// The value of a percentage leaf node that contains an associated percent hint.
462#[derive(
463    Clone,
464    Copy,
465    Debug,
466    Deserialize,
467    MallocSizeOf,
468    PartialEq,
469    Serialize,
470    ToAnimatedZero,
471    ToCss,
472    ToResolvedValue,
473    ToShmem,
474    ToTyped,
475)]
476#[repr(C)]
477pub struct CalcPercentageLeaf {
478    /// The percentage value.
479    pub value: NoCalcPercentage,
480    /// The base type the percentage resolves against, or None if there is
481    /// no specific percent hint (this is used by CSS Typed OM when parsing
482    /// an expression without the context of a property).
483    #[css(skip)]
484    pub hint: Optional<NumericBaseType>,
485}
486
487impl CalcPercentageLeaf {
488    /// Builds a percentage leaf with the given percent hint.
489    pub fn new(value: f32, hint: Optional<NumericBaseType>) -> Self {
490        Self {
491            value: NoCalcPercentage::new(value),
492            hint,
493        }
494    }
495
496    /// Returns the percentage value as a float.
497    pub fn get(&self) -> f32 {
498        self.value.get()
499    }
500
501    /// Returns the numeric type of this percentage.
502    pub fn numeric_type(&self) -> NumericType {
503        match self.hint {
504            Optional::Some(hint) => NumericType::percent().with_percent_hint(hint),
505            Optional::None => NumericType::percent(),
506        }
507    }
508
509    /// Returns the percent hint to use when merging two percentages with an arithmetic
510    /// operation. Mismatched hints should be impossible after type checking.
511    pub fn combined_hint(&self, other: &Self) -> Optional<NumericBaseType> {
512        debug_assert_eq!(
513            self.hint, other.hint,
514            "Merging percentages with mismatched hints"
515        );
516        self.hint
517    }
518}
519
520macro_rules! compare_helpers {
521    () => {
522        /// Return whether a leaf is greater than another.
523        #[allow(unused)]
524        fn gt(&self, other: &Self) -> bool {
525            self.compare(other) == Some(cmp::Ordering::Greater)
526        }
527
528        /// Return whether a leaf is less than another.
529        fn lt(&self, other: &Self) -> bool {
530            self.compare(other) == Some(cmp::Ordering::Less)
531        }
532
533        /// Return whether a leaf is smaller or equal than another.
534        fn lte(&self, other: &Self) -> bool {
535            match self.compare(other) {
536                Some(cmp::Ordering::Less) => true,
537                Some(cmp::Ordering::Equal) => true,
538                Some(cmp::Ordering::Greater) => false,
539                None => false,
540            }
541        }
542    };
543}
544
545/// A trait that represents all the stuff a valid leaf of a calc expression.
546pub trait CalcNodeLeaf: Clone + Sized + PartialEq + ToCss + ToTyped + fmt::Debug {
547    /// Returns the type of the leaf.
548    fn numeric_type(&self) -> NumericType;
549
550    /// Returns the unitless value of this leaf if one is available.
551    fn unitless_value(&self) -> Option<f32>;
552
553    /// Returns the value and percent hint if this leaf is a percentage.
554    fn as_percentage(&self) -> Option<(f32, Optional<NumericBaseType>)>;
555
556    /// Returns the canonical value of this leaf in the type's canonical unit,
557    /// if there is enough information to determine its numeric value.
558    /// https://drafts.csswg.org/css-values-4/#simplify-a-calculation-tree
559    fn canonical_value(&self) -> Option<f32>;
560
561    /// Returns the angle value in radians if this leaf is an angle.
562    fn as_angle_radians(&self) -> Option<f32>;
563
564    /// Creates a new angle leaf from a value in radians.
565    fn new_angle_from_radians(radians: f32) -> Self;
566
567    /// Return true if the units of both leaves are equal. (NOTE: Does not take
568    /// the values into account)
569    fn is_same_unit_as(&self, other: &Self) -> bool {
570        std::mem::discriminant(self) == std::mem::discriminant(other)
571    }
572
573    /// Do a partial comparison of these values.
574    fn compare(&self, other: &Self) -> Option<cmp::Ordering>;
575    compare_helpers!();
576
577    /// Create a new leaf with a number value.
578    fn new_number(value: f32) -> Self;
579
580    /// Returns a float value if the leaf is a number.
581    fn as_number(&self) -> Option<f32>;
582
583    /// Returns a number or angle radians if the leaf is a number or angle.
584    fn as_number_or_angle_radians(&self) -> Option<f32> {
585        self.as_number().or_else(|| self.as_angle_radians())
586    }
587
588    /// Create a new leaf with `value` in the canonical unit of the given type.
589    /// Returns Err(()) if the type cannot be constructed as a leaf.
590    fn new_from_typed_value(value: f32, numeric_type: NumericType) -> Result<Self, ()>;
591
592    /// Whether this value is known-negative.
593    fn is_negative(&self) -> Result<bool, ()> {
594        self.unitless_value()
595            .map(|v| Ok(v.is_sign_negative()))
596            .unwrap_or_else(|| Err(()))
597    }
598
599    /// Whether this value is infinite.
600    fn is_infinite(&self) -> Result<bool, ()> {
601        self.unitless_value()
602            .map(|v| Ok(v.is_infinite()))
603            .unwrap_or_else(|| Err(()))
604    }
605
606    /// Whether this value is zero.
607    fn is_zero(&self) -> Result<bool, ()> {
608        self.unitless_value()
609            .map(|v| Ok(v.is_zero()))
610            .unwrap_or_else(|| Err(()))
611    }
612
613    /// Whether this value is NaN.
614    fn is_nan(&self) -> Result<bool, ()> {
615        self.unitless_value()
616            .map(|v| Ok(v.is_nan()))
617            .unwrap_or_else(|| Err(()))
618    }
619
620    /// Tries to merge one leaf into another using the sum, that is, perform `x` + `y`.
621    fn try_sum_in_place(&mut self, other: &Self) -> Result<(), ()>;
622
623    /// Try to merge the right leaf into the left by using a multiplication. Return true if the
624    /// merge was successful, otherwise false.
625    fn try_product_in_place(&mut self, other: &mut Self) -> bool;
626
627    /// Tries a generic arithmetic operation.
628    fn try_op<O>(&self, other: &Self, op: O) -> Result<Self, ()>
629    where
630        O: Fn(f32, f32) -> f32;
631
632    /// Map the value of this node with the given operation.
633    fn map(&mut self, op: impl FnMut(f32) -> f32) -> Result<(), ()>;
634
635    /// Canonicalizes the expression if necessary.
636    fn simplify(&mut self) -> SimplificationResult;
637
638    /// Returns the sort key for simplification.
639    fn sort_key(&self) -> SortKey;
640
641    /// Create a new leaf containing the sign() result of the given leaf.
642    fn sign_from(leaf: &impl CalcNodeLeaf) -> Result<Self, ()> {
643        let Some(value) = leaf.canonical_value() else {
644            return Err(());
645        };
646
647        Ok(Self::new_number(crate::values::calc_sign(value)))
648    }
649
650    /// Whether this leaf node should serialize with a `calc()` wrapper
651    /// if this node is the root of the calculation tree.
652    fn should_serialize_with_root_calc_wrapper(&self) -> bool {
653        true
654    }
655}
656
657/// The level of any argument being serialized in `to_css_impl`.
658#[derive(Clone)]
659enum ArgumentLevel {
660    /// The root of a calculation tree.
661    CalculationRoot,
662    /// The root of an operand node's argument, e.g. `min(10, 20)`, `10` and `20` will have this
663    /// level, but min in this case will have `TopMost`.
664    ArgumentRoot,
665    /// Any other values serialized in the tree.
666    Nested,
667}
668
669/// The result of simplify_and_sort_direct_children
670#[derive(Clone, Copy)]
671pub enum SimplificationResult {
672    /// This node (Or some of its descendants, if any) was simplified.
673    Simplified,
674    /// The children was unchanged.
675    Unchanged,
676}
677
678impl<L: CalcNodeLeaf> CalcNode<L> {
679    /// Create a dummy CalcNode that can be used to do replacements of other nodes.
680    fn dummy() -> Self {
681        Self::MinMax(Default::default(), MinMaxOp::Max)
682    }
683
684    /// Change all the leaf nodes to have the given value. This is useful when
685    /// you have `calc(1px * nan)` and you want to replace the product node with
686    /// `calc(nan)`, in which case the unit will be retained.
687    fn coerce_to_value(&mut self, value: f32) -> Result<(), ()> {
688        self.map(|_| value)
689    }
690
691    /// Return true if a product is distributive over this node.
692    /// Is distributive: (2 + 3) * 4 = 8 + 12
693    /// Not distributive: sign(2 + 3) * 4 != sign(8 + 12)
694    #[inline]
695    pub fn is_product_distributive(&self) -> bool {
696        match self {
697            // If there's no value, we can't distribute the product.
698            Self::Leaf(l) => l.unitless_value().is_some(),
699            Self::Sum(children) => children.iter().all(|c| c.is_product_distributive()),
700            _ => false,
701        }
702    }
703
704    /// If the node has a valid type outcome, then return it, otherwise fail. Note that this
705    /// type may not represent a valid CSS production and it is the responsibility of the caller
706    /// to determine whether this type is acceptable (see NumericType::as_calc_type).
707    pub fn numeric_type(&self) -> Result<NumericType, ()> {
708        Ok(match self {
709            CalcNode::Leaf(l) => l.numeric_type(),
710            CalcNode::Negate(child) | CalcNode::Abs(child) => child.numeric_type()?,
711            CalcNode::Sum(children) => {
712                let mut ty = children.first().unwrap().numeric_type()?;
713                for child in children.iter().skip(1) {
714                    let child_ty = child.numeric_type()?;
715                    ty = NumericType::add_two_types(&ty, &child_ty)?;
716                }
717                ty
718            },
719            CalcNode::Product(children) => {
720                let mut ty = children.first().unwrap().numeric_type()?;
721
722                for child in children.iter().skip(1) {
723                    let child_ty = child.numeric_type()?;
724
725                    // When typed arithmetic is not enabled, at most one side of the multiplication
726                    // operation can have a non-number type.
727                    if !typed_arithmetic_enabled() && !ty.is_number() && !child_ty.is_number() {
728                        return Err(());
729                    }
730
731                    ty = NumericType::multiply_two_types(&ty, &child_ty)?;
732                }
733
734                ty
735            },
736            CalcNode::MinMax(children, _) | CalcNode::Hypot(children) => {
737                let mut ty = children.first().unwrap().numeric_type()?;
738                for child in children.iter().skip(1) {
739                    let child_ty = child.numeric_type()?;
740                    ty = NumericType::add_two_types(&ty, &child_ty)?;
741                }
742                ty
743            },
744            CalcNode::Clamp { min, center, max } => {
745                let min_ty = min.numeric_type()?;
746                let center_ty = center.numeric_type()?;
747                let max_ty = max.numeric_type()?;
748
749                let mut ty = NumericType::add_two_types(&min_ty, &center_ty)?;
750                ty = NumericType::add_two_types(&ty, &max_ty)?;
751                ty
752            },
753            CalcNode::Round { value, step, .. } => {
754                let value_ty = value.numeric_type()?;
755                let step_ty = step.numeric_type()?;
756                NumericType::add_two_types(&value_ty, &step_ty)?
757            },
758            CalcNode::ModRem {
759                dividend, divisor, ..
760            } => {
761                let dividend_ty = dividend.numeric_type()?;
762                let divisor_ty = divisor.numeric_type()?;
763                NumericType::add_two_types(&dividend_ty, &divisor_ty)?
764            },
765            CalcNode::Sign(child) => {
766                // sign() always resolves to a number, but we still need to make sure that the
767                // child units make sense.
768                let _ = child.numeric_type()?;
769                NumericType::number()
770            },
771            CalcNode::Anchor(..) | CalcNode::AnchorSize(..) => {
772                NumericType::length().with_percent_hint(NumericBaseType::Length)
773            },
774            CalcNode::Sin(child) | CalcNode::Cos(child) | CalcNode::Tan(child) => {
775                let child_ty = child.numeric_type_as_calc_type()?;
776                if child_ty != CalcType::Number && child_ty != CalcType::Angle {
777                    return Err(());
778                }
779                NumericType::number()
780            },
781            CalcNode::Asin(child) | CalcNode::Acos(child) | CalcNode::Atan(child) => {
782                if child.numeric_type_as_calc_type()? != CalcType::Number {
783                    return Err(());
784                }
785                NumericType::angle()
786            },
787            CalcNode::Atan2(a, b) => {
788                // Ensure that the types of a and b can be made consistent
789                let a_ty = a.numeric_type()?;
790                let b_ty = b.numeric_type()?;
791                let _ = NumericType::add_two_types(&a_ty, &b_ty)?;
792                NumericType::angle()
793            },
794            CalcNode::Pow(a, b) => {
795                let a_ty = a.numeric_type_as_calc_type()?;
796                let b_ty = b.numeric_type_as_calc_type()?;
797                if a_ty != CalcType::Number || b_ty != CalcType::Number {
798                    return Err(());
799                }
800                NumericType::number()
801            },
802            CalcNode::Invert(c) => {
803                if typed_arithmetic_enabled() {
804                    let mut ty = c.numeric_type()?;
805                    ty.invert();
806                    ty
807                } else {
808                    if c.numeric_type_as_calc_type()? != CalcType::Number {
809                        return Err(());
810                    }
811                    NumericType::number()
812                }
813            },
814            CalcNode::Sqrt(c) | CalcNode::Exp(c) => {
815                if c.numeric_type_as_calc_type()? != CalcType::Number {
816                    return Err(());
817                }
818                NumericType::number()
819            },
820            CalcNode::Log(a, b) => {
821                let a_ty = a.numeric_type_as_calc_type()?;
822                let b_ty = match b {
823                    Optional::Some(b) => b.numeric_type_as_calc_type()?,
824                    Optional::None => CalcType::Number,
825                };
826                if a_ty != CalcType::Number || b_ty != CalcType::Number {
827                    return Err(());
828                }
829                NumericType::number()
830            },
831            CalcNode::Progress {
832                value, start, end, ..
833            } => {
834                let value_ty = value.numeric_type()?;
835                let start_ty = start.numeric_type()?;
836                let end_ty = end.numeric_type()?;
837
838                // Ensure that the types of the arguments are consistent.
839                let _ = NumericType::add_two_types(&value_ty, &start_ty)?;
840                let _ = NumericType::add_two_types(&value_ty, &end_ty)?;
841                NumericType::number()
842            },
843            CalcNode::Random(random) => {
844                let min_ty = random.min.numeric_type()?;
845                let max_ty = random.max.numeric_type()?;
846                let mut ty = NumericType::add_two_types(&min_ty, &max_ty)?;
847                if let Some(step) = random.step.as_ref() {
848                    let step_ty = step.numeric_type()?;
849                    ty = NumericType::add_two_types(&ty, &step_ty)?;
850                }
851                ty
852            },
853        })
854    }
855
856    /// If the node has a valid type outcome that matches one of the types that a calculation
857    /// can produce, then return it, otherwise fail.
858    pub fn numeric_type_as_calc_type(&self) -> Result<CalcType, ()> {
859        self.numeric_type()?.as_calc_type()
860    }
861
862    /// Negate the node inline.  If the node is distributive, it is replaced by the result,
863    /// otherwise the node is wrapped in a [`Negate`] node.
864    pub fn negate(&mut self) {
865        /// Node(params) -> Negate(Node(params))
866        fn wrap_self_in_negate<L: CalcNodeLeaf>(s: &mut CalcNode<L>) {
867            let result = mem::replace(s, CalcNode::dummy());
868            *s = CalcNode::Negate(Box::new(result));
869        }
870
871        match *self {
872            CalcNode::Leaf(ref mut leaf) => {
873                if leaf.map(std::ops::Neg::neg).is_err() {
874                    wrap_self_in_negate(self)
875                }
876            },
877            CalcNode::Negate(ref mut value) => {
878                // Don't negate the value here.  Replace `self` with it's child.
879                let result = mem::replace(value.as_mut(), Self::dummy());
880                *self = result;
881            },
882            CalcNode::Invert(_) => {
883                // -(1 / -10) == -(-0.1) == 0.1
884                wrap_self_in_negate(self)
885            },
886            CalcNode::Sum(ref mut children) => {
887                for child in children.iter_mut() {
888                    child.negate();
889                }
890            },
891            CalcNode::Product(_) => {
892                // -(2 * 3 / 4) == -(1.5)
893                wrap_self_in_negate(self);
894            },
895            CalcNode::MinMax(ref mut children, ref mut op) => {
896                for child in children.iter_mut() {
897                    child.negate();
898                }
899
900                // Negating min-max means the operation is swapped.
901                *op = match *op {
902                    MinMaxOp::Min => MinMaxOp::Max,
903                    MinMaxOp::Max => MinMaxOp::Min,
904                };
905            },
906            CalcNode::Clamp {
907                ref mut min,
908                ref mut center,
909                ref mut max,
910            } => {
911                if min.lte(max) {
912                    min.negate();
913                    center.negate();
914                    max.negate();
915
916                    mem::swap(min, max);
917                } else {
918                    wrap_self_in_negate(self);
919                }
920            },
921            CalcNode::Round {
922                ref mut strategy,
923                ref mut value,
924                ref mut step,
925            } => {
926                match *strategy {
927                    RoundingStrategy::Nearest => {
928                        // Nearest is tricky because we'd have to swap the
929                        // behavior at the half-way point from using the upper
930                        // to lower bound.
931                        // Simpler to just wrap self in a negate node.
932                        wrap_self_in_negate(self);
933                        return;
934                    },
935                    RoundingStrategy::Up => *strategy = RoundingStrategy::Down,
936                    RoundingStrategy::Down => *strategy = RoundingStrategy::Up,
937                    RoundingStrategy::ToZero => (),
938                }
939                value.negate();
940                step.negate();
941            },
942            CalcNode::ModRem {
943                ref mut dividend,
944                ref mut divisor,
945                ..
946            } => {
947                dividend.negate();
948                divisor.negate();
949            },
950            CalcNode::Sign(ref mut child) => {
951                child.negate();
952            },
953            CalcNode::Sin(..)
954            | CalcNode::Cos(..)
955            | CalcNode::Tan(..)
956            | CalcNode::Asin(..)
957            | CalcNode::Acos(..)
958            | CalcNode::Atan(..)
959            | CalcNode::Atan2(..)
960            | CalcNode::Pow(..)
961            | CalcNode::Sqrt(..)
962            | CalcNode::Log(..)
963            | CalcNode::Exp(..)
964            | CalcNode::Abs(..)
965            | CalcNode::Hypot(..)
966            | CalcNode::Progress { .. }
967            | CalcNode::Random(..)
968            | CalcNode::Anchor(..)
969            | CalcNode::AnchorSize(..) => {
970                wrap_self_in_negate(self);
971            },
972        }
973    }
974
975    fn sort_key(&self) -> SortKey {
976        match *self {
977            Self::Leaf(ref l) => l.sort_key(),
978            Self::Anchor(..) | Self::AnchorSize(..) => SortKey::Px,
979            _ => SortKey::Other,
980        }
981    }
982
983    /// Returns the leaf if we can (if simplification has allowed it).
984    pub fn as_leaf(&self) -> Option<&L> {
985        match *self {
986            Self::Leaf(ref l) => Some(l),
987            _ => None,
988        }
989    }
990
991    /// Tries to merge one node into another using the sum, that is, perform `x` + `y`.
992    pub fn try_sum_in_place(&mut self, other: &Self) -> Result<(), ()> {
993        match (self, other) {
994            (&mut CalcNode::Leaf(ref mut one), CalcNode::Leaf(other)) => {
995                one.try_sum_in_place(other)
996            },
997            _ => Err(()),
998        }
999    }
1000
1001    /// Tries to merge one node into another using the product, that is, perform `x` * `y`.
1002    pub fn try_product_in_place(&mut self, other: &mut Self) -> bool {
1003        if let Ok(resolved) = other.resolve()
1004            && let Some(number) = resolved.as_number()
1005        {
1006            if number == 1.0 {
1007                return true;
1008            }
1009
1010            if self.is_product_distributive() {
1011                if self.map(|v| v * number).is_err() {
1012                    return false;
1013                }
1014                return true;
1015            }
1016        }
1017
1018        if let Ok(resolved) = self.resolve()
1019            && let Some(number) = resolved.as_number()
1020        {
1021            if number == 1.0 {
1022                std::mem::swap(self, other);
1023                return true;
1024            }
1025
1026            if other.is_product_distributive() {
1027                if other.map(|v| v * number).is_err() {
1028                    return false;
1029                }
1030                std::mem::swap(self, other);
1031                return true;
1032            }
1033        }
1034
1035        false
1036    }
1037
1038    /// Tries to apply a generic arithmetic operator
1039    fn try_op<O>(&self, other: &Self, op: O) -> Result<Self, ()>
1040    where
1041        O: Fn(f32, f32) -> f32,
1042    {
1043        match (self, other) {
1044            (CalcNode::Leaf(one), CalcNode::Leaf(other)) => {
1045                Ok(CalcNode::Leaf(one.try_op(other, op)?))
1046            },
1047            _ => Err(()),
1048        }
1049    }
1050
1051    /// Map the value of this node with the given operation.
1052    pub fn map(&mut self, mut op: impl FnMut(f32) -> f32) -> Result<(), ()> {
1053        fn map_internal<L: CalcNodeLeaf>(
1054            node: &mut CalcNode<L>,
1055            op: &mut impl FnMut(f32) -> f32,
1056        ) -> Result<(), ()> {
1057            match node {
1058                CalcNode::Leaf(l) => l.map(op),
1059                CalcNode::Negate(v) | CalcNode::Invert(v) => map_internal(v, op),
1060                CalcNode::Sum(children) | CalcNode::Product(children) => {
1061                    for node in &mut **children {
1062                        map_internal(node, op)?;
1063                    }
1064                    Ok(())
1065                },
1066                CalcNode::MinMax(children, _) => {
1067                    for node in &mut **children {
1068                        map_internal(node, op)?;
1069                    }
1070                    Ok(())
1071                },
1072                CalcNode::Clamp { min, center, max } => {
1073                    map_internal(min, op)?;
1074                    map_internal(center, op)?;
1075                    map_internal(max, op)
1076                },
1077                CalcNode::Round { value, step, .. } => {
1078                    map_internal(value, op)?;
1079                    map_internal(step, op)
1080                },
1081                CalcNode::ModRem {
1082                    dividend, divisor, ..
1083                } => {
1084                    map_internal(dividend, op)?;
1085                    map_internal(divisor, op)
1086                },
1087                CalcNode::Hypot(children) => {
1088                    for node in &mut **children {
1089                        map_internal(node, op)?;
1090                    }
1091                    Ok(())
1092                },
1093                CalcNode::Abs(child) | CalcNode::Sign(child) => map_internal(child, op),
1094                // It is invalid to treat inner `CalcNode`s here - `anchor(--foo 50%) / 2` != `anchor(--foo 25%)`.
1095                // Same applies to fallback, as we don't know if it will be used. Similar reasoning applies to `anchor-size()`.
1096                CalcNode::Anchor(_) | CalcNode::AnchorSize(_) => Err(()),
1097                // Trig functions are nonlinear: 2 * sin(x) != sin(2*x).
1098                // Similarly for pow/sqrt/log/exp.
1099                CalcNode::Sin(_)
1100                | CalcNode::Cos(_)
1101                | CalcNode::Tan(_)
1102                | CalcNode::Asin(_)
1103                | CalcNode::Acos(_)
1104                | CalcNode::Atan(_)
1105                | CalcNode::Atan2(..)
1106                | CalcNode::Pow(..)
1107                | CalcNode::Sqrt(_)
1108                | CalcNode::Log(..)
1109                | CalcNode::Exp(_)
1110                | CalcNode::Progress { .. }
1111                | CalcNode::Random(_) => Err(()),
1112            }
1113        }
1114
1115        map_internal(self, &mut op)
1116    }
1117
1118    /// Convert this `CalcNode` into a `CalcNode` with a different leaf kind.
1119    pub fn map_leaves<O, F>(&self, mut map: F) -> CalcNode<O>
1120    where
1121        O: CalcNodeLeaf,
1122        F: FnMut(&L) -> O,
1123    {
1124        self.map_leaves_internal(&mut map)
1125    }
1126
1127    fn map_leaves_internal<O, F>(&self, map: &mut F) -> CalcNode<O>
1128    where
1129        O: CalcNodeLeaf,
1130        F: FnMut(&L) -> O,
1131    {
1132        fn map_children<L, O, F>(
1133            children: &[CalcNode<L>],
1134            map: &mut F,
1135        ) -> crate::OwnedSlice<CalcNode<O>>
1136        where
1137            L: CalcNodeLeaf,
1138            O: CalcNodeLeaf,
1139            F: FnMut(&L) -> O,
1140        {
1141            children
1142                .iter()
1143                .map(|c| c.map_leaves_internal(map))
1144                .collect()
1145        }
1146
1147        match *self {
1148            Self::Leaf(ref l) => CalcNode::Leaf(map(l)),
1149            Self::Negate(ref c) => CalcNode::Negate(Box::new(c.map_leaves_internal(map))),
1150            Self::Invert(ref c) => CalcNode::Invert(Box::new(c.map_leaves_internal(map))),
1151            Self::Sum(ref c) => CalcNode::Sum(map_children(c, map)),
1152            Self::Product(ref c) => CalcNode::Product(map_children(c, map)),
1153            Self::MinMax(ref c, op) => CalcNode::MinMax(map_children(c, map), op),
1154            Self::Clamp {
1155                ref min,
1156                ref center,
1157                ref max,
1158            } => {
1159                let min = Box::new(min.map_leaves_internal(map));
1160                let center = Box::new(center.map_leaves_internal(map));
1161                let max = Box::new(max.map_leaves_internal(map));
1162                CalcNode::Clamp { min, center, max }
1163            },
1164            Self::Round {
1165                strategy,
1166                ref value,
1167                ref step,
1168            } => {
1169                let value = Box::new(value.map_leaves_internal(map));
1170                let step = Box::new(step.map_leaves_internal(map));
1171                CalcNode::Round {
1172                    strategy,
1173                    value,
1174                    step,
1175                }
1176            },
1177            Self::ModRem {
1178                ref dividend,
1179                ref divisor,
1180                op,
1181            } => {
1182                let dividend = Box::new(dividend.map_leaves_internal(map));
1183                let divisor = Box::new(divisor.map_leaves_internal(map));
1184                CalcNode::ModRem {
1185                    dividend,
1186                    divisor,
1187                    op,
1188                }
1189            },
1190            Self::Sin(ref c) => CalcNode::Sin(Box::new(c.map_leaves_internal(map))),
1191            Self::Cos(ref c) => CalcNode::Cos(Box::new(c.map_leaves_internal(map))),
1192            Self::Tan(ref c) => CalcNode::Tan(Box::new(c.map_leaves_internal(map))),
1193            Self::Asin(ref c) => CalcNode::Asin(Box::new(c.map_leaves_internal(map))),
1194            Self::Acos(ref c) => CalcNode::Acos(Box::new(c.map_leaves_internal(map))),
1195            Self::Atan(ref c) => CalcNode::Atan(Box::new(c.map_leaves_internal(map))),
1196            Self::Atan2(ref a, ref b) => CalcNode::Atan2(
1197                Box::new(a.map_leaves_internal(map)),
1198                Box::new(b.map_leaves_internal(map)),
1199            ),
1200            Self::Pow(ref a, ref b) => CalcNode::Pow(
1201                Box::new(a.map_leaves_internal(map)),
1202                Box::new(b.map_leaves_internal(map)),
1203            ),
1204            Self::Sqrt(ref c) => CalcNode::Sqrt(Box::new(c.map_leaves_internal(map))),
1205            Self::Hypot(ref c) => CalcNode::Hypot(map_children(c, map)),
1206            Self::Log(ref a, ref b) => CalcNode::Log(
1207                Box::new(a.map_leaves_internal(map)),
1208                b.as_ref()
1209                    .map(|b| Box::new(b.map_leaves_internal(map)))
1210                    .into(),
1211            ),
1212            Self::Exp(ref c) => CalcNode::Exp(Box::new(c.map_leaves_internal(map))),
1213            Self::Abs(ref c) => CalcNode::Abs(Box::new(c.map_leaves_internal(map))),
1214            Self::Sign(ref c) => CalcNode::Sign(Box::new(c.map_leaves_internal(map))),
1215            Self::Progress {
1216                clamping_mode,
1217                ref value,
1218                ref start,
1219                ref end,
1220            } => {
1221                let value = Box::new(value.map_leaves_internal(map));
1222                let start = Box::new(start.map_leaves_internal(map));
1223                let end = Box::new(end.map_leaves_internal(map));
1224                CalcNode::Progress {
1225                    clamping_mode,
1226                    value,
1227                    start,
1228                    end,
1229                }
1230            },
1231            Self::Random(ref r) => CalcNode::Random(Box::new(GenericRandomFunction {
1232                key: r.key.map_leaves_internal(map),
1233                min: r.min.map_leaves_internal(map),
1234                max: r.max.map_leaves_internal(map),
1235                step: r
1236                    .step
1237                    .as_ref()
1238                    .map(|step| step.map_leaves_internal(map))
1239                    .into(),
1240            })),
1241            Self::Anchor(ref f) => CalcNode::Anchor(Box::new(GenericAnchorFunction {
1242                target_element: f.target_element.clone(),
1243                side: match &f.side {
1244                    GenericAnchorSide::Keyword(k) => GenericAnchorSide::Keyword(*k),
1245                    GenericAnchorSide::Percentage(p) => {
1246                        GenericAnchorSide::Percentage(Box::new(p.map_leaves_internal(map)))
1247                    },
1248                },
1249                fallback: f
1250                    .fallback
1251                    .as_ref()
1252                    .map(|fb| {
1253                        Box::new(GenericAnchorFunctionFallback::new(
1254                            fb.is_calc_node,
1255                            fb.node.map_leaves_internal(map),
1256                        ))
1257                    })
1258                    .into(),
1259            })),
1260            Self::AnchorSize(ref f) => CalcNode::AnchorSize(Box::new(GenericAnchorSizeFunction {
1261                target_element: f.target_element.clone(),
1262                size: f.size,
1263                fallback: f
1264                    .fallback
1265                    .as_ref()
1266                    .map(|fb| {
1267                        Box::new(GenericAnchorFunctionFallback::new(
1268                            fb.is_calc_node,
1269                            fb.node.map_leaves_internal(map),
1270                        ))
1271                    })
1272                    .into(),
1273            })),
1274        }
1275    }
1276
1277    /// Resolve this node into a value.
1278    pub fn resolve(&self) -> Result<L, ()> {
1279        self.resolve_map(|l| Ok(l.clone()))
1280    }
1281
1282    /// Resolve this node into a value, given a function that maps the leaf values.
1283    pub fn resolve_map<F>(&self, mut leaf_to_output_fn: F) -> Result<L, ()>
1284    where
1285        F: FnMut(&L) -> Result<L, ()>,
1286    {
1287        let (value, ty) = self.resolve_internal(&mut leaf_to_output_fn)?;
1288        L::new_from_typed_value(value, ty)
1289    }
1290
1291    fn resolve_internal<F>(&self, leaf_to_output_fn: &mut F) -> Result<(f32, NumericType), ()>
1292    where
1293        F: FnMut(&L) -> Result<L, ()>,
1294    {
1295        match self {
1296            Self::Leaf(l) => {
1297                let result = leaf_to_output_fn(l)?;
1298                let value = result.canonical_value().ok_or(())?;
1299                let ty = result.numeric_type();
1300                Ok((value, ty))
1301            },
1302            Self::Negate(child) => {
1303                let (value, ty) = child.resolve_internal(leaf_to_output_fn)?;
1304                Ok((-value, ty))
1305            },
1306            Self::Invert(child) => {
1307                let (value, mut ty) = child.resolve_internal(leaf_to_output_fn)?;
1308                if !typed_arithmetic_enabled() && !ty.is_number() {
1309                    return Err(());
1310                }
1311                ty.invert();
1312                Ok((1.0 / value, ty))
1313            },
1314            Self::Sum(children) => {
1315                let (mut value, mut ty) = children[0].resolve_internal(leaf_to_output_fn)?;
1316
1317                for child in children.iter().skip(1) {
1318                    let (right, right_ty) = child.resolve_internal(leaf_to_output_fn)?;
1319                    value += right;
1320                    ty = NumericType::add_two_types(&ty, &right_ty)?;
1321                }
1322
1323                Ok((value, ty))
1324            },
1325            Self::Product(children) => {
1326                let (mut value, mut ty) = children[0].resolve_internal(leaf_to_output_fn)?;
1327
1328                for child in children.iter().skip(1) {
1329                    let (leaf, leaf_ty) = child.resolve_internal(leaf_to_output_fn)?;
1330
1331                    // When typed arithmetic is not enabled, at most one side of the multiplication
1332                    // operation can have a non-number type.
1333                    if !typed_arithmetic_enabled() && !ty.is_number() && !leaf_ty.is_number() {
1334                        return Err(());
1335                    }
1336
1337                    value *= leaf;
1338                    ty = NumericType::multiply_two_types(&ty, &leaf_ty)?;
1339                }
1340
1341                Ok((value, ty))
1342            },
1343            Self::MinMax(children, op) => {
1344                let (mut value, mut ty) = children[0].resolve_internal(leaf_to_output_fn)?;
1345
1346                if value.is_nan() {
1347                    return Ok((value, ty));
1348                }
1349
1350                for child in children.iter().skip(1) {
1351                    let (candidate, candidate_ty) = child.resolve_internal(leaf_to_output_fn)?;
1352
1353                    // Determine the consistent type (bailing out if the types are not consistent).
1354                    ty = NumericType::add_two_types(&ty, &candidate_ty)?;
1355
1356                    if candidate.is_nan() {
1357                        value = candidate;
1358                        break;
1359                    }
1360
1361                    value = match op {
1362                        MinMaxOp::Min => crate::values::calc_min(value, candidate),
1363                        MinMaxOp::Max => crate::values::calc_max(value, candidate),
1364                    };
1365                }
1366
1367                Ok((value, ty))
1368            },
1369            Self::Clamp { min, center, max } => {
1370                let (min, min_ty) = min.resolve_internal(leaf_to_output_fn)?;
1371                let (center, center_ty) = center.resolve_internal(leaf_to_output_fn)?;
1372                let (max, max_ty) = max.resolve_internal(leaf_to_output_fn)?;
1373
1374                let mut ty = NumericType::add_two_types(&min_ty, &center_ty)?;
1375                ty = NumericType::add_two_types(&ty, &max_ty)?;
1376
1377                if min.is_nan() {
1378                    return Ok((min, ty));
1379                }
1380
1381                if center.is_nan() {
1382                    return Ok((center, ty));
1383                }
1384
1385                if max.is_nan() {
1386                    return Ok((max, ty));
1387                }
1388
1389                // NOTE: clamp is max(min, min(center, max))
1390                let value = crate::values::calc_max(min, crate::values::calc_min(center, max));
1391                Ok((value, ty))
1392            },
1393            Self::Round {
1394                strategy,
1395                value,
1396                step,
1397            } => {
1398                let (mut value, value_ty) = value.resolve_internal(leaf_to_output_fn)?;
1399                let (step, step_ty) = step.resolve_internal(leaf_to_output_fn)?;
1400                let ty = NumericType::add_two_types(&value_ty, &step_ty)?;
1401
1402                let step = step.abs();
1403
1404                // TODO(emilio): Seems like at least a few of these
1405                // special-cases could be removed if we do the math in a
1406                // particular order.
1407                if step.is_zero() {
1408                    value = f32::NAN;
1409                } else if value.is_infinite() {
1410                    if step.is_infinite() {
1411                        value = f32::NAN
1412                    }
1413                } else if step.is_infinite() {
1414                    value = match strategy {
1415                        RoundingStrategy::Nearest | RoundingStrategy::ToZero => {
1416                            if value.is_sign_negative() { -0.0 } else { 0.0 }
1417                        },
1418                        RoundingStrategy::Up => {
1419                            if !value.is_sign_negative() && !value.is_zero() {
1420                                f32::INFINITY
1421                            } else if !value.is_sign_negative() && value.is_zero() {
1422                                value
1423                            } else {
1424                                -0.0
1425                            }
1426                        },
1427                        RoundingStrategy::Down => {
1428                            if value.is_sign_negative() && !value.is_zero() {
1429                                -f32::INFINITY
1430                            } else if value.is_sign_negative() && value.is_zero() {
1431                                value
1432                            } else {
1433                                0.0
1434                            }
1435                        },
1436                    };
1437                } else {
1438                    let div = value / step;
1439                    let lower_bound = div.floor() * step;
1440                    let upper_bound = div.ceil() * step;
1441
1442                    value = match strategy {
1443                        RoundingStrategy::Nearest => {
1444                            // In case of a tie, use the upper bound
1445                            if value - lower_bound < upper_bound - value {
1446                                lower_bound
1447                            } else {
1448                                upper_bound
1449                            }
1450                        },
1451                        RoundingStrategy::Up => upper_bound,
1452                        RoundingStrategy::Down => lower_bound,
1453                        RoundingStrategy::ToZero => {
1454                            // In case of a tie, use the upper bound
1455                            if lower_bound.abs() < upper_bound.abs() {
1456                                lower_bound
1457                            } else {
1458                                upper_bound
1459                            }
1460                        },
1461                    }
1462                }
1463
1464                Ok((value, ty))
1465            },
1466            Self::ModRem {
1467                dividend,
1468                divisor,
1469                op,
1470            } => {
1471                let (dividend, dividend_ty) = dividend.resolve_internal(leaf_to_output_fn)?;
1472                let (divisor, divisor_ty) = divisor.resolve_internal(leaf_to_output_fn)?;
1473                let ty = NumericType::add_two_types(&dividend_ty, &divisor_ty)?;
1474                let value = op.apply(dividend, divisor);
1475                Ok((value, ty))
1476            },
1477            Self::Sin(c) => {
1478                let (value, ty) = c.resolve_internal(leaf_to_output_fn)?;
1479                let radians = match ty.as_calc_type()? {
1480                    CalcType::Number => value,
1481                    CalcType::Angle => value.to_radians(),
1482                    _ => return Err(()),
1483                };
1484                Ok((radians.sin(), NumericType::number()))
1485            },
1486            Self::Cos(c) => {
1487                let (value, ty) = c.resolve_internal(leaf_to_output_fn)?;
1488                let radians = match ty.as_calc_type()? {
1489                    CalcType::Number => value,
1490                    CalcType::Angle => value.to_radians(),
1491                    _ => return Err(()),
1492                };
1493                Ok((radians.cos(), NumericType::number()))
1494            },
1495            Self::Tan(c) => {
1496                let (value, ty) = c.resolve_internal(leaf_to_output_fn)?;
1497                let radians = match ty.as_calc_type()? {
1498                    CalcType::Number => value,
1499                    CalcType::Angle => value.to_radians(),
1500                    _ => return Err(()),
1501                };
1502                Ok((radians.tan(), NumericType::number()))
1503            },
1504            Self::Asin(c) => {
1505                let (value, ty) = c.resolve_internal(leaf_to_output_fn)?;
1506                if !ty.is_number() {
1507                    return Err(());
1508                }
1509                Ok((value.asin().to_degrees(), NumericType::angle()))
1510            },
1511            Self::Acos(c) => {
1512                let (value, ty) = c.resolve_internal(leaf_to_output_fn)?;
1513                if !ty.is_number() {
1514                    return Err(());
1515                }
1516                Ok((value.acos().to_degrees(), NumericType::angle()))
1517            },
1518            Self::Atan(c) => {
1519                let (value, ty) = c.resolve_internal(leaf_to_output_fn)?;
1520                if !ty.is_number() {
1521                    return Err(());
1522                }
1523                Ok((value.atan().to_degrees(), NumericType::angle()))
1524            },
1525            Self::Atan2(a, b) => {
1526                let (a, a_ty) = a.resolve_internal(leaf_to_output_fn)?;
1527                let (b, b_ty) = b.resolve_internal(leaf_to_output_fn)?;
1528                let _ = NumericType::add_two_types(&a_ty, &b_ty)?;
1529                Ok((a.atan2(b).to_degrees(), NumericType::angle()))
1530            },
1531            Self::Pow(a, b) => {
1532                let (a, a_ty) = a.resolve_internal(leaf_to_output_fn)?;
1533                let (b, b_ty) = b.resolve_internal(leaf_to_output_fn)?;
1534                if !a_ty.is_number() || !b_ty.is_number() {
1535                    return Err(());
1536                }
1537                Ok((a.powf(b), NumericType::number()))
1538            },
1539            Self::Sqrt(c) => {
1540                let (value, ty) = c.resolve_internal(leaf_to_output_fn)?;
1541                if !ty.is_number() {
1542                    return Err(());
1543                }
1544                Ok((value.sqrt(), NumericType::number()))
1545            },
1546            Self::Hypot(children) => {
1547                let (mut value, mut ty) = children[0].resolve_internal(leaf_to_output_fn)?;
1548                value = value.powi(2);
1549
1550                for child in children.iter().skip(1) {
1551                    let (child_value, child_ty) = child.resolve_internal(leaf_to_output_fn)?;
1552                    ty = NumericType::add_two_types(&ty, &child_ty)?;
1553                    value += child_value.powi(2);
1554                }
1555
1556                Ok((value.sqrt(), ty))
1557            },
1558            Self::Log(a, b) => {
1559                let (a, a_ty) = a.resolve_internal(leaf_to_output_fn)?;
1560                if !a_ty.is_number() {
1561                    return Err(());
1562                }
1563                let value = match b {
1564                    Optional::Some(b) => {
1565                        let (b, b_ty) = b.resolve_internal(leaf_to_output_fn)?;
1566                        if !b_ty.is_number() {
1567                            return Err(());
1568                        }
1569                        a.log(b)
1570                    },
1571                    Optional::None => a.ln(),
1572                };
1573                Ok((value, NumericType::number()))
1574            },
1575            Self::Exp(c) => {
1576                let (value, ty) = c.resolve_internal(leaf_to_output_fn)?;
1577                if !ty.is_number() {
1578                    return Err(());
1579                }
1580                Ok((value.exp(), NumericType::number()))
1581            },
1582            Self::Abs(c) => {
1583                let (value, ty) = c.resolve_internal(leaf_to_output_fn)?;
1584                Ok((value.abs(), ty))
1585            },
1586            Self::Sign(c) => {
1587                let (value, _) = c.resolve_internal(leaf_to_output_fn)?;
1588                let sign = crate::values::calc_sign(value);
1589                Ok((sign, NumericType::number()))
1590            },
1591            Self::Progress {
1592                clamping_mode,
1593                value,
1594                start,
1595                end,
1596            } => {
1597                let (value, value_ty) = value.resolve_internal(leaf_to_output_fn)?;
1598                let (start, start_ty) = start.resolve_internal(leaf_to_output_fn)?;
1599                let (end, end_ty) = end.resolve_internal(leaf_to_output_fn)?;
1600
1601                let _ = NumericType::add_two_types(&value_ty, &start_ty)?;
1602                let _ = NumericType::add_two_types(&value_ty, &end_ty)?;
1603                let _ = NumericType::add_two_types(&start_ty, &end_ty)?;
1604
1605                let progress = clamping_mode.evaluate(value, start, end);
1606                Ok((progress, NumericType::number()))
1607            },
1608            Self::Random(r) => {
1609                let (base, base_ty) = r.key.resolve_internal(leaf_to_output_fn)?;
1610                if !base_ty.is_number() {
1611                    return Err(());
1612                }
1613
1614                let (min, min_ty) = r.min.resolve_internal(leaf_to_output_fn)?;
1615                let (max, max_ty) = r.max.resolve_internal(leaf_to_output_fn)?;
1616                let mut ty = NumericType::add_two_types(&min_ty, &max_ty)?;
1617
1618                let step = match r.step.as_ref() {
1619                    Some(step) => {
1620                        let (step, step_ty) = step.resolve_internal(leaf_to_output_fn)?;
1621                        ty = NumericType::add_two_types(&ty, &step_ty)?;
1622                        Some(step)
1623                    },
1624                    None => None,
1625                };
1626
1627                let value = calc_random(base, min, max, step);
1628                Ok((value, ty))
1629            },
1630            Self::Anchor(_) | Self::AnchorSize(_) => Err(()),
1631        }
1632    }
1633
1634    /// Mutate nodes within this calc node tree using given the mapping function.
1635    pub fn map_node<F>(&mut self, mut mapping_fn: F) -> Result<(), ()>
1636    where
1637        F: FnMut(&CalcNode<L>) -> Result<Option<CalcNode<L>>, ()>,
1638    {
1639        self.map_node_internal(&mut mapping_fn)
1640    }
1641
1642    fn map_node_internal<F>(&mut self, mapping_fn: &mut F) -> Result<(), ()>
1643    where
1644        F: FnMut(&CalcNode<L>) -> Result<Option<CalcNode<L>>, ()>,
1645    {
1646        if let Some(node) = mapping_fn(self)? {
1647            *self = node;
1648            // Assume that any sub-nodes don't need to be mutated.
1649            return Ok(());
1650        }
1651        match self {
1652            Self::Leaf(_) | Self::Anchor(_) | Self::AnchorSize(_) => (),
1653            Self::Negate(child)
1654            | Self::Invert(child)
1655            | Self::Abs(child)
1656            | Self::Sign(child)
1657            | Self::Sin(child)
1658            | Self::Cos(child)
1659            | Self::Tan(child)
1660            | Self::Asin(child)
1661            | Self::Acos(child)
1662            | Self::Atan(child)
1663            | Self::Sqrt(child)
1664            | Self::Exp(child) => {
1665                child.map_node_internal(mapping_fn)?;
1666            },
1667            Self::Atan2(a, b) => {
1668                a.map_node_internal(mapping_fn)?;
1669                b.map_node_internal(mapping_fn)?;
1670            },
1671            Self::Pow(a, b) => {
1672                a.map_node_internal(mapping_fn)?;
1673                b.map_node_internal(mapping_fn)?;
1674            },
1675            Self::Log(a, b) => {
1676                a.map_node_internal(mapping_fn)?;
1677                if let Optional::Some(b) = b {
1678                    b.map_node_internal(mapping_fn)?;
1679                }
1680            },
1681            Self::Sum(children)
1682            | Self::Product(children)
1683            | Self::Hypot(children)
1684            | Self::MinMax(children, _) => {
1685                for child in children.iter_mut() {
1686                    child.map_node_internal(mapping_fn)?;
1687                }
1688            },
1689            Self::Clamp { min, center, max } => {
1690                min.map_node_internal(mapping_fn)?;
1691                center.map_node_internal(mapping_fn)?;
1692                max.map_node_internal(mapping_fn)?;
1693            },
1694            Self::Round { value, step, .. } => {
1695                value.map_node_internal(mapping_fn)?;
1696                step.map_node_internal(mapping_fn)?;
1697            },
1698            Self::ModRem {
1699                dividend, divisor, ..
1700            } => {
1701                dividend.map_node_internal(mapping_fn)?;
1702                divisor.map_node_internal(mapping_fn)?;
1703            },
1704            Self::Progress {
1705                value, start, end, ..
1706            } => {
1707                value.map_node_internal(mapping_fn)?;
1708                start.map_node_internal(mapping_fn)?;
1709                end.map_node_internal(mapping_fn)?;
1710            },
1711            Self::Random(random) => {
1712                random.key.map_node_internal(mapping_fn)?;
1713                random.min.map_node_internal(mapping_fn)?;
1714                random.max.map_node_internal(mapping_fn)?;
1715                if let Some(step) = random.step.as_mut() {
1716                    step.map_node_internal(mapping_fn)?;
1717                }
1718            },
1719        };
1720        Ok(())
1721    }
1722
1723    fn is_negative_leaf(&self) -> Result<bool, ()> {
1724        Ok(match *self {
1725            Self::Leaf(ref l) => l.is_negative()?,
1726            _ => false,
1727        })
1728    }
1729
1730    fn is_zero_leaf(&self) -> Result<bool, ()> {
1731        Ok(match *self {
1732            Self::Leaf(ref l) => l.is_zero()?,
1733            _ => false,
1734        })
1735    }
1736
1737    fn is_infinite_leaf(&self) -> Result<bool, ()> {
1738        Ok(match *self {
1739            Self::Leaf(ref l) => l.is_infinite()?,
1740            _ => false,
1741        })
1742    }
1743
1744    fn is_nan_leaf(&self) -> Result<bool, ()> {
1745        Ok(match *self {
1746            Self::Leaf(ref l) => l.is_nan()?,
1747            _ => false,
1748        })
1749    }
1750
1751    /// Visits all the nodes in this calculation tree recursively, starting by
1752    /// the leaves and bubbling all the way up.
1753    ///
1754    /// This is useful for simplification, but can also be used for validation
1755    /// and such.
1756    pub fn visit_depth_first(&mut self, mut f: impl FnMut(&mut Self)) {
1757        self.visit_depth_first_internal(&mut f)
1758    }
1759
1760    fn visit_depth_first_internal(&mut self, f: &mut impl FnMut(&mut Self)) {
1761        match *self {
1762            Self::Clamp {
1763                ref mut min,
1764                ref mut center,
1765                ref mut max,
1766            } => {
1767                min.visit_depth_first_internal(f);
1768                center.visit_depth_first_internal(f);
1769                max.visit_depth_first_internal(f);
1770            },
1771            Self::Round {
1772                ref mut value,
1773                ref mut step,
1774                ..
1775            } => {
1776                value.visit_depth_first_internal(f);
1777                step.visit_depth_first_internal(f);
1778            },
1779            Self::ModRem {
1780                ref mut dividend,
1781                ref mut divisor,
1782                ..
1783            } => {
1784                dividend.visit_depth_first_internal(f);
1785                divisor.visit_depth_first_internal(f);
1786            },
1787            Self::Sum(ref mut children)
1788            | Self::Product(ref mut children)
1789            | Self::MinMax(ref mut children, _)
1790            | Self::Hypot(ref mut children) => {
1791                for child in &mut **children {
1792                    child.visit_depth_first_internal(f);
1793                }
1794            },
1795            Self::Negate(ref mut value) | Self::Invert(ref mut value) => {
1796                value.visit_depth_first_internal(f);
1797            },
1798            Self::Sin(ref mut value)
1799            | Self::Cos(ref mut value)
1800            | Self::Tan(ref mut value)
1801            | Self::Asin(ref mut value)
1802            | Self::Acos(ref mut value)
1803            | Self::Atan(ref mut value)
1804            | Self::Sqrt(ref mut value)
1805            | Self::Exp(ref mut value) => {
1806                value.visit_depth_first_internal(f);
1807            },
1808            Self::Atan2(ref mut a, ref mut b) => {
1809                a.visit_depth_first_internal(f);
1810                b.visit_depth_first_internal(f);
1811            },
1812            Self::Pow(ref mut a, ref mut b) => {
1813                a.visit_depth_first_internal(f);
1814                b.visit_depth_first_internal(f);
1815            },
1816            Self::Log(ref mut a, ref mut b) => {
1817                a.visit_depth_first_internal(f);
1818                if let Optional::Some(b) = b {
1819                    b.visit_depth_first_internal(f);
1820                }
1821            },
1822            Self::Abs(ref mut value) | Self::Sign(ref mut value) => {
1823                value.visit_depth_first_internal(f);
1824            },
1825            Self::Progress {
1826                ref mut value,
1827                ref mut start,
1828                ref mut end,
1829                ..
1830            } => {
1831                value.visit_depth_first_internal(f);
1832                start.visit_depth_first_internal(f);
1833                end.visit_depth_first_internal(f);
1834            },
1835            Self::Random(ref mut random) => {
1836                random.key.visit_depth_first_internal(f);
1837                random.min.visit_depth_first_internal(f);
1838                random.max.visit_depth_first_internal(f);
1839                if let Some(step) = random.step.as_mut() {
1840                    step.visit_depth_first_internal(f);
1841                }
1842            },
1843            Self::Leaf(..) | Self::Anchor(..) | Self::AnchorSize(..) => {},
1844        }
1845        f(self);
1846    }
1847
1848    /// This function simplifies and sorts the calculation of the specified node. It simplifies
1849    /// directly nested nodes while assuming that all nodes below it have already been simplified.
1850    /// It is recommended to use this function in combination with `visit_depth_first()`.
1851    ///
1852    /// This function is necessary only if the node needs to be preserved after parsing,
1853    /// specifically for `<length-percentage>` cases where the calculation contains percentages or
1854    /// relative units. Otherwise, the node can be evaluated using `resolve()`, which will
1855    /// automatically provide a simplified value.
1856    ///
1857    /// <https://drafts.csswg.org/css-values-4/#calc-simplification>
1858    pub fn simplify_and_sort_direct_children(&mut self) -> SimplificationResult {
1859        macro_rules! replace_self_with {
1860            ($slot:expr) => {{
1861                let result = mem::replace($slot, Self::dummy());
1862                *self = result;
1863            }};
1864        }
1865
1866        macro_rules! value_or_stop {
1867            ($op:expr) => {{
1868                match $op {
1869                    Ok(value) => value,
1870                    Err(_) => return SimplificationResult::Unchanged,
1871                }
1872            }};
1873        }
1874
1875        match *self {
1876            Self::Clamp {
1877                ref mut min,
1878                ref mut center,
1879                ref mut max,
1880            } => {
1881                // NOTE: clamp() is max(min, min(center, max))
1882                let min_cmp_center = match min.compare(center) {
1883                    Some(o) => o,
1884                    None => return SimplificationResult::Unchanged,
1885                };
1886
1887                // So if we can prove that min is more than center, then we won,
1888                // as that's what we should always return.
1889                if matches!(min_cmp_center, cmp::Ordering::Greater) {
1890                    replace_self_with!(&mut **min);
1891                    return SimplificationResult::Simplified;
1892                }
1893
1894                // Otherwise try with max.
1895                let max_cmp_center = match max.compare(center) {
1896                    Some(o) => o,
1897                    None => return SimplificationResult::Unchanged,
1898                };
1899
1900                if matches!(max_cmp_center, cmp::Ordering::Less) {
1901                    // max is less than center, so we need to return effectively
1902                    // `max(min, max)`.
1903                    let max_cmp_min = match max.compare(min) {
1904                        Some(o) => o,
1905                        None => return SimplificationResult::Unchanged,
1906                    };
1907
1908                    if matches!(max_cmp_min, cmp::Ordering::Less) {
1909                        replace_self_with!(&mut **min);
1910                        return SimplificationResult::Simplified;
1911                    }
1912
1913                    replace_self_with!(&mut **max);
1914                    return SimplificationResult::Simplified;
1915                }
1916
1917                // Otherwise we're the center node.
1918                replace_self_with!(&mut **center);
1919                SimplificationResult::Simplified
1920            },
1921            Self::Round {
1922                strategy,
1923                ref mut value,
1924                ref mut step,
1925            } => {
1926                if value_or_stop!(step.is_zero_leaf()) {
1927                    value_or_stop!(value.coerce_to_value(f32::NAN));
1928                    replace_self_with!(&mut **value);
1929                    return SimplificationResult::Simplified;
1930                }
1931
1932                if value_or_stop!(value.is_infinite_leaf())
1933                    && value_or_stop!(step.is_infinite_leaf())
1934                {
1935                    value_or_stop!(value.coerce_to_value(f32::NAN));
1936                    replace_self_with!(&mut **value);
1937                    return SimplificationResult::Simplified;
1938                }
1939
1940                if value_or_stop!(value.is_infinite_leaf()) {
1941                    replace_self_with!(&mut **value);
1942                    return SimplificationResult::Simplified;
1943                }
1944
1945                if value_or_stop!(step.is_infinite_leaf()) {
1946                    match strategy {
1947                        RoundingStrategy::Nearest | RoundingStrategy::ToZero => {
1948                            value_or_stop!(value.coerce_to_value(0.0));
1949                            replace_self_with!(&mut **value);
1950                            return SimplificationResult::Simplified;
1951                        },
1952                        RoundingStrategy::Up => {
1953                            if !value_or_stop!(value.is_negative_leaf())
1954                                && !value_or_stop!(value.is_zero_leaf())
1955                            {
1956                                value_or_stop!(value.coerce_to_value(f32::INFINITY));
1957                                replace_self_with!(&mut **value);
1958                                return SimplificationResult::Simplified;
1959                            } else if !value_or_stop!(value.is_negative_leaf())
1960                                && value_or_stop!(value.is_zero_leaf())
1961                            {
1962                                replace_self_with!(&mut **value);
1963                                return SimplificationResult::Simplified;
1964                            } else {
1965                                value_or_stop!(value.coerce_to_value(0.0));
1966                                replace_self_with!(&mut **value);
1967                                return SimplificationResult::Simplified;
1968                            }
1969                        },
1970                        RoundingStrategy::Down => {
1971                            if value_or_stop!(value.is_negative_leaf())
1972                                && !value_or_stop!(value.is_zero_leaf())
1973                            {
1974                                value_or_stop!(value.coerce_to_value(-f32::INFINITY));
1975                                replace_self_with!(&mut **value);
1976                                return SimplificationResult::Simplified;
1977                            } else if value_or_stop!(value.is_negative_leaf())
1978                                && value_or_stop!(value.is_zero_leaf())
1979                            {
1980                                replace_self_with!(&mut **value);
1981                                return SimplificationResult::Simplified;
1982                            } else {
1983                                value_or_stop!(value.coerce_to_value(0.0));
1984                                replace_self_with!(&mut **value);
1985                                return SimplificationResult::Simplified;
1986                            }
1987                        },
1988                    }
1989                }
1990
1991                if value_or_stop!(step.is_negative_leaf()) {
1992                    step.negate();
1993                }
1994
1995                let remainder = value_or_stop!(value.try_op(step, Rem::rem));
1996                if value_or_stop!(remainder.is_zero_leaf()) {
1997                    replace_self_with!(&mut **value);
1998                    return SimplificationResult::Simplified;
1999                }
2000
2001                let (mut lower_bound, mut upper_bound) = if value_or_stop!(value.is_negative_leaf())
2002                {
2003                    let upper_bound = value_or_stop!(value.try_op(&remainder, Sub::sub));
2004                    let lower_bound = value_or_stop!(upper_bound.try_op(step, Sub::sub));
2005
2006                    (lower_bound, upper_bound)
2007                } else {
2008                    let lower_bound = value_or_stop!(value.try_op(&remainder, Sub::sub));
2009                    let upper_bound = value_or_stop!(lower_bound.try_op(step, Add::add));
2010
2011                    (lower_bound, upper_bound)
2012                };
2013
2014                match strategy {
2015                    RoundingStrategy::Nearest => {
2016                        let lower_diff = value_or_stop!(value.try_op(&lower_bound, Sub::sub));
2017                        let upper_diff = value_or_stop!(upper_bound.try_op(value, Sub::sub));
2018                        // In case of a tie, use the upper bound
2019                        if lower_diff.lt(&upper_diff) {
2020                            replace_self_with!(&mut lower_bound);
2021                        } else {
2022                            replace_self_with!(&mut upper_bound);
2023                        }
2024                    },
2025                    RoundingStrategy::Up => {
2026                        replace_self_with!(&mut upper_bound);
2027                    },
2028                    RoundingStrategy::Down => {
2029                        replace_self_with!(&mut lower_bound);
2030                    },
2031                    RoundingStrategy::ToZero => {
2032                        let mut lower_diff = lower_bound.clone();
2033                        let mut upper_diff = upper_bound.clone();
2034
2035                        if value_or_stop!(lower_diff.is_negative_leaf()) {
2036                            lower_diff.negate();
2037                        }
2038
2039                        if value_or_stop!(upper_diff.is_negative_leaf()) {
2040                            upper_diff.negate();
2041                        }
2042
2043                        // In case of a tie, use the upper bound
2044                        if lower_diff.lt(&upper_diff) {
2045                            replace_self_with!(&mut lower_bound);
2046                        } else {
2047                            replace_self_with!(&mut upper_bound);
2048                        }
2049                    },
2050                };
2051                SimplificationResult::Simplified
2052            },
2053            Self::ModRem {
2054                ref dividend,
2055                ref divisor,
2056                op,
2057            } => {
2058                let mut result = value_or_stop!(dividend.try_op(divisor, |a, b| op.apply(a, b)));
2059                replace_self_with!(&mut result);
2060                SimplificationResult::Simplified
2061            },
2062            Self::MinMax(ref mut children, op) => {
2063                let winning_order = match op {
2064                    MinMaxOp::Min => cmp::Ordering::Less,
2065                    MinMaxOp::Max => cmp::Ordering::Greater,
2066                };
2067
2068                if value_or_stop!(children[0].is_nan_leaf()) {
2069                    replace_self_with!(&mut children[0]);
2070                    return SimplificationResult::Simplified;
2071                }
2072
2073                let mut result = 0;
2074                for i in 1..children.len() {
2075                    if value_or_stop!(children[i].is_nan_leaf()) {
2076                        replace_self_with!(&mut children[i]);
2077                        return SimplificationResult::Simplified;
2078                    }
2079                    let o = match children[i].compare(&children[result]) {
2080                        // We can't compare all the children, so we can't
2081                        // know which one will actually win. Bail out and
2082                        // keep ourselves as a min / max function.
2083                        //
2084                        // TODO: Maybe we could simplify compatible children,
2085                        // see https://github.com/w3c/csswg-drafts/issues/4756
2086                        None => return SimplificationResult::Unchanged,
2087                        Some(o) => o,
2088                    };
2089
2090                    if o == winning_order {
2091                        result = i;
2092                    }
2093                }
2094
2095                replace_self_with!(&mut children[result]);
2096                SimplificationResult::Simplified
2097            },
2098            Self::Sum(ref mut children_slot) => {
2099                let mut sums_to_merge = SmallVec::<[_; 3]>::new();
2100                let mut extra_kids = 0;
2101                for (i, child) in children_slot.iter().enumerate() {
2102                    if let Self::Sum(ref children) = *child {
2103                        extra_kids += children.len();
2104                        sums_to_merge.push(i);
2105                    }
2106                }
2107
2108                // If we only have one kid, we've already simplified it, and it
2109                // doesn't really matter whether it's a sum already or not, so
2110                // lift it up and continue.
2111                if children_slot.len() == 1 {
2112                    replace_self_with!(&mut children_slot[0]);
2113                    return SimplificationResult::Simplified;
2114                }
2115
2116                let mut children = mem::take(children_slot).into_vec();
2117
2118                if !sums_to_merge.is_empty() {
2119                    children.reserve(extra_kids - sums_to_merge.len());
2120                    // Merge all our nested sums, in reverse order so that the
2121                    // list indices are not invalidated.
2122                    for i in sums_to_merge.drain(..).rev() {
2123                        let kid_children = match children.swap_remove(i) {
2124                            Self::Sum(c) => c,
2125                            _ => unreachable!(),
2126                        };
2127
2128                        // This would be nicer with
2129                        // https://github.com/rust-lang/rust/issues/59878 fixed.
2130                        children.extend(kid_children.into_vec());
2131                    }
2132                }
2133
2134                let children_len = children.len();
2135                debug_assert!(children_len >= 2, "Should still have multiple kids!");
2136
2137                // Sort by spec order.
2138                children.sort_unstable_by_key(|c| c.sort_key());
2139
2140                // NOTE: if the function returns true, by the docs of dedup_by,
2141                // a is removed.
2142                children.dedup_by(|a, b| b.try_sum_in_place(a).is_ok());
2143
2144                let updated_children_len = children.len();
2145                if updated_children_len == 1 {
2146                    // If only one children remains, lift it up, and carry on.
2147                    replace_self_with!(&mut children[0]);
2148                } else {
2149                    // Else put our simplified children back.
2150                    *children_slot = children.into_boxed_slice().into();
2151                }
2152
2153                if updated_children_len != children_len {
2154                    SimplificationResult::Simplified
2155                } else {
2156                    SimplificationResult::Unchanged
2157                }
2158            },
2159            Self::Product(ref mut children_slot) => {
2160                let mut products_to_merge = SmallVec::<[_; 3]>::new();
2161                let mut extra_kids = 0;
2162                for (i, child) in children_slot.iter().enumerate() {
2163                    if let Self::Product(ref children) = *child {
2164                        extra_kids += children.len();
2165                        products_to_merge.push(i);
2166                    }
2167                }
2168
2169                // If we only have one kid, we've already simplified it, and it
2170                // doesn't really matter whether it's a product already or not,
2171                // so lift it up and continue.
2172                if children_slot.len() == 1 {
2173                    replace_self_with!(&mut children_slot[0]);
2174                    return SimplificationResult::Unchanged;
2175                }
2176
2177                let mut children = mem::take(children_slot).into_vec();
2178                if !products_to_merge.is_empty() {
2179                    children.reserve(extra_kids - products_to_merge.len());
2180                    // Merge all our nested sums, in reverse order so that the
2181                    // list indices are not invalidated.
2182                    for i in products_to_merge.drain(..).rev() {
2183                        let kid_children = match children.swap_remove(i) {
2184                            Self::Product(c) => c,
2185                            _ => unreachable!(),
2186                        };
2187
2188                        // This would be nicer with
2189                        // https://github.com/rust-lang/rust/issues/59878 fixed.
2190                        children.extend(kid_children.into_vec());
2191                    }
2192                }
2193
2194                debug_assert!(children.len() >= 2, "Should still have multiple kids!");
2195
2196                // Sort by spec order.
2197                children.sort_unstable_by_key(|c| c.sort_key());
2198
2199                // NOTE: if the function returns true, by the docs of dedup_by,
2200                // a is removed.
2201                children.dedup_by(|right, left| left.try_product_in_place(right));
2202
2203                if children.len() == 1 {
2204                    // If only one children remains, lift it up, and carry on.
2205                    replace_self_with!(&mut children[0]);
2206                    return SimplificationResult::Simplified;
2207                }
2208
2209                if typed_arithmetic_enabled() {
2210                    // "If root contains only numeric values and/or Invert nodes containing numeric values,
2211                    // and multiplying the types of all the children (noting that the type of an Invert
2212                    // node is the inverse of its child’s type) results in a type that matches any of the
2213                    // types that a math function can resolve to, return the result of multiplying all the
2214                    // values of the children (noting that the value of an Invert node is the reciprocal of
2215                    // its child’s value), expressed in the result’s canonical unit."
2216                    //
2217                    // https://drafts.csswg.org/css-values-4/#simplify-a-calculation-tree
2218                    let mut result = 1.0;
2219                    let mut ty = Ok(NumericType::number());
2220
2221                    for child in children.iter() {
2222                        let (leaf, is_inverted) = match child {
2223                            Self::Leaf(leaf) => (leaf, false),
2224                            Self::Invert(inner) if inner.as_leaf().is_some() => {
2225                                (inner.as_leaf().unwrap(), true)
2226                            },
2227                            _ => {
2228                                ty = Err(());
2229                                break;
2230                            },
2231                        };
2232
2233                        // Only multiply values that are in that type's canonical unit.
2234                        let Some(value) = leaf.canonical_value() else {
2235                            ty = Err(());
2236                            break;
2237                        };
2238                        let (multiplicand, child_ty) = if is_inverted {
2239                            let mut ty = leaf.numeric_type();
2240                            ty.invert();
2241                            (1.0 / value, ty)
2242                        } else {
2243                            (value, leaf.numeric_type())
2244                        };
2245
2246                        result *= multiplicand;
2247                        ty = ty.and_then(|ty| NumericType::multiply_two_types(&ty, &child_ty));
2248                    }
2249
2250                    if let Ok(leaf) = ty.and_then(|ty| L::new_from_typed_value(result, ty)) {
2251                        let mut result = Self::Leaf(leaf);
2252                        replace_self_with!(&mut result);
2253                        return SimplificationResult::Simplified;
2254                    }
2255                }
2256
2257                // Else put our simplified children back.
2258                *children_slot = children.into_boxed_slice().into();
2259                SimplificationResult::Unchanged
2260            },
2261            Self::Sin(ref mut child) => {
2262                if let CalcNode::Leaf(ref leaf) = **child
2263                    && let Some(radians) = leaf.as_number_or_angle_radians()
2264                {
2265                    let mut result = Self::Leaf(L::new_number(radians.sin()));
2266                    replace_self_with!(&mut result);
2267                    return SimplificationResult::Simplified;
2268                }
2269                SimplificationResult::Unchanged
2270            },
2271            Self::Cos(ref mut child) => {
2272                if let CalcNode::Leaf(ref leaf) = **child
2273                    && let Some(radians) = leaf.as_number_or_angle_radians()
2274                {
2275                    let mut result = Self::Leaf(L::new_number(radians.cos()));
2276                    replace_self_with!(&mut result);
2277                    return SimplificationResult::Simplified;
2278                }
2279                SimplificationResult::Unchanged
2280            },
2281            Self::Tan(ref mut child) => {
2282                if let CalcNode::Leaf(ref leaf) = **child
2283                    && let Some(radians) = leaf.as_number_or_angle_radians()
2284                {
2285                    let mut result = Self::Leaf(L::new_number(radians.tan()));
2286                    replace_self_with!(&mut result);
2287                    return SimplificationResult::Simplified;
2288                }
2289                SimplificationResult::Unchanged
2290            },
2291            Self::Asin(ref mut child) => {
2292                if let CalcNode::Leaf(ref leaf) = **child
2293                    && let Some(value) = leaf.as_number()
2294                {
2295                    let mut result = Self::Leaf(L::new_angle_from_radians(value.asin()));
2296                    replace_self_with!(&mut result);
2297                    return SimplificationResult::Simplified;
2298                }
2299                SimplificationResult::Unchanged
2300            },
2301            Self::Acos(ref mut child) => {
2302                if let CalcNode::Leaf(ref leaf) = **child
2303                    && let Some(value) = leaf.as_number()
2304                {
2305                    let mut result = Self::Leaf(L::new_angle_from_radians(value.acos()));
2306                    replace_self_with!(&mut result);
2307                    return SimplificationResult::Simplified;
2308                }
2309                SimplificationResult::Unchanged
2310            },
2311            Self::Atan(ref mut child) => {
2312                if let CalcNode::Leaf(ref leaf) = **child
2313                    && let Some(value) = leaf.as_number()
2314                {
2315                    let mut result = Self::Leaf(L::new_angle_from_radians(value.atan()));
2316                    replace_self_with!(&mut result);
2317                    return SimplificationResult::Simplified;
2318                }
2319                SimplificationResult::Unchanged
2320            },
2321            Self::Atan2(ref mut a, ref mut b) => {
2322                if let (CalcNode::Leaf(la), CalcNode::Leaf(lb)) = (&**a, &**b)
2323                    && la.is_same_unit_as(lb)
2324                    && let (Some(a_val), Some(b_val)) = (la.unitless_value(), lb.unitless_value())
2325                {
2326                    let mut result = Self::Leaf(L::new_angle_from_radians(a_val.atan2(b_val)));
2327                    replace_self_with!(&mut result);
2328                    return SimplificationResult::Simplified;
2329                }
2330                SimplificationResult::Unchanged
2331            },
2332            Self::Pow(ref mut a, ref mut b) => {
2333                if let (CalcNode::Leaf(la), CalcNode::Leaf(lb)) = (&**a, &**b)
2334                    && let (Some(a_val), Some(b_val)) = (la.as_number(), lb.as_number())
2335                {
2336                    let mut result = Self::Leaf(L::new_number(a_val.powf(b_val)));
2337                    replace_self_with!(&mut result);
2338                    return SimplificationResult::Simplified;
2339                }
2340                SimplificationResult::Unchanged
2341            },
2342            Self::Sqrt(ref mut child) => {
2343                if let CalcNode::Leaf(ref leaf) = **child
2344                    && let Some(value) = leaf.as_number()
2345                {
2346                    let mut result = Self::Leaf(L::new_number(value.sqrt()));
2347                    replace_self_with!(&mut result);
2348                    return SimplificationResult::Simplified;
2349                }
2350                SimplificationResult::Unchanged
2351            },
2352            Self::Hypot(ref children) => {
2353                let mut result = value_or_stop!(children[0].try_op(&children[0], Mul::mul));
2354
2355                for child in children.iter().skip(1) {
2356                    let square = value_or_stop!(child.try_op(child, Mul::mul));
2357                    result = value_or_stop!(result.try_op(&square, Add::add));
2358                }
2359
2360                result = value_or_stop!(result.try_op(&result, |a, _| a.sqrt()));
2361
2362                replace_self_with!(&mut result);
2363                SimplificationResult::Simplified
2364            },
2365            Self::Log(ref mut a, ref mut b) => {
2366                if let CalcNode::Leaf(ref la) = **a
2367                    && let Some(a_val) = la.as_number()
2368                {
2369                    let folded = match b {
2370                        &mut Optional::Some(ref b) => {
2371                            if let CalcNode::Leaf(ref lb) = **b {
2372                                lb.as_number().map(|b_val| a_val.log(b_val))
2373                            } else {
2374                                None
2375                            }
2376                        },
2377                        Optional::None => Some(a_val.ln()),
2378                    };
2379                    if let Some(number) = folded {
2380                        let mut result = Self::Leaf(L::new_number(number));
2381                        replace_self_with!(&mut result);
2382                        return SimplificationResult::Simplified;
2383                    }
2384                }
2385                SimplificationResult::Unchanged
2386            },
2387            Self::Exp(ref mut child) => {
2388                if let CalcNode::Leaf(ref leaf) = **child
2389                    && let Some(value) = leaf.as_number()
2390                {
2391                    let mut result = Self::Leaf(L::new_number(value.exp()));
2392                    replace_self_with!(&mut result);
2393                    return SimplificationResult::Simplified;
2394                }
2395                SimplificationResult::Unchanged
2396            },
2397            Self::Abs(ref mut child) => {
2398                if let CalcNode::Leaf(leaf) = child.as_mut() {
2399                    value_or_stop!(leaf.map(|v| v.abs()));
2400                    replace_self_with!(&mut **child);
2401                    return SimplificationResult::Simplified;
2402                }
2403                SimplificationResult::Unchanged
2404            },
2405            Self::Sign(ref mut child) => {
2406                if let CalcNode::Leaf(leaf) = child.as_mut() {
2407                    let mut result = Self::Leaf(value_or_stop!(L::sign_from(leaf)));
2408                    replace_self_with!(&mut result);
2409                    return SimplificationResult::Simplified;
2410                }
2411                SimplificationResult::Unchanged
2412            },
2413            Self::Negate(ref mut child) => {
2414                // Step 6.
2415                match &mut **child {
2416                    CalcNode::Leaf(_) => {
2417                        // 1. If root’s child is a numeric value, return an equivalent numeric value, but
2418                        // with the value negated (0 - value).
2419                        child.negate();
2420                        replace_self_with!(&mut **child);
2421                        SimplificationResult::Simplified
2422                    },
2423                    CalcNode::Negate(value) => {
2424                        // 2. If root’s child is a Negate node, return the child’s child.
2425                        replace_self_with!(&mut **value);
2426                        SimplificationResult::Simplified
2427                    },
2428                    _ => {
2429                        // 3. Return root.
2430                        SimplificationResult::Unchanged
2431                    },
2432                }
2433            },
2434            Self::Invert(ref mut child) => {
2435                // Step 7.
2436                match &mut **child {
2437                    CalcNode::Leaf(leaf) => {
2438                        // 1. If root’s child is a number (not a percentage or dimension) return the
2439                        // reciprocal of the child’s value.
2440                        if leaf.numeric_type().is_number() {
2441                            value_or_stop!(child.map(|v| 1.0 / v));
2442                            replace_self_with!(&mut **child);
2443                            return SimplificationResult::Simplified;
2444                        }
2445                        SimplificationResult::Unchanged
2446                    },
2447                    CalcNode::Invert(value) => {
2448                        // 2. If root’s child is an Invert node, return the child’s child.
2449                        replace_self_with!(&mut **value);
2450                        SimplificationResult::Simplified
2451                    },
2452                    _ => {
2453                        // 3. Return root.
2454                        SimplificationResult::Unchanged
2455                    },
2456                }
2457            },
2458            Self::Progress {
2459                clamping_mode,
2460                ref mut value,
2461                ref mut start,
2462                ref mut end,
2463            } => {
2464                if let (CalcNode::Leaf(value), CalcNode::Leaf(start), CalcNode::Leaf(end)) =
2465                    (&**value, &**start, &**end)
2466                    && value.is_same_unit_as(start)
2467                    && value.is_same_unit_as(end)
2468                    && let (Some(value), Some(start), Some(end)) = (
2469                        value.unitless_value(),
2470                        start.unitless_value(),
2471                        end.unitless_value(),
2472                    )
2473                {
2474                    let mut result =
2475                        Self::Leaf(L::new_number(clamping_mode.evaluate(value, start, end)));
2476                    replace_self_with!(&mut result);
2477                    return SimplificationResult::Simplified;
2478                }
2479                SimplificationResult::Unchanged
2480            },
2481            Self::Random(ref mut r) => {
2482                let (
2483                    CalcNode::Leaf(key_leaf),
2484                    CalcNode::Leaf(min_leaf),
2485                    CalcNode::Leaf(max_leaf),
2486                ) = (&r.key, &r.min, &r.max)
2487                else {
2488                    return SimplificationResult::Unchanged;
2489                };
2490
2491                if !min_leaf.is_same_unit_as(max_leaf) {
2492                    return SimplificationResult::Unchanged;
2493                }
2494
2495                let (Some(base), Some(min), Some(max)) = (
2496                    key_leaf.canonical_value(),
2497                    min_leaf.canonical_value(),
2498                    max_leaf.canonical_value(),
2499                ) else {
2500                    return SimplificationResult::Unchanged;
2501                };
2502
2503                let step = match &r.step {
2504                    Optional::Some(step) => {
2505                        let CalcNode::Leaf(step_leaf) = step else {
2506                            return SimplificationResult::Unchanged;
2507                        };
2508                        if !min_leaf.is_same_unit_as(step_leaf) {
2509                            return SimplificationResult::Unchanged;
2510                        }
2511                        let Some(step) = step_leaf.unitless_value() else {
2512                            return SimplificationResult::Unchanged;
2513                        };
2514                        Some(step)
2515                    },
2516                    Optional::None => None,
2517                };
2518
2519                let result = calc_random(base, min, max, step);
2520                if r.min.coerce_to_value(result).is_err() {
2521                    return SimplificationResult::Unchanged;
2522                }
2523                replace_self_with!(&mut r.min);
2524                SimplificationResult::Simplified
2525            },
2526            Self::Leaf(ref mut l) => l.simplify(),
2527            Self::Anchor(ref mut f) => {
2528                if let GenericAnchorSide::Percentage(ref mut n) = f.side {
2529                    n.simplify_and_sort();
2530                    return SimplificationResult::Simplified;
2531                }
2532                if let Some(fallback) = f.fallback.as_mut() {
2533                    return fallback.node.simplify_and_sort();
2534                }
2535                SimplificationResult::Unchanged
2536            },
2537            Self::AnchorSize(ref mut f) => {
2538                if let Some(fallback) = f.fallback.as_mut() {
2539                    return fallback.node.simplify_and_sort();
2540                }
2541                SimplificationResult::Unchanged
2542            },
2543        }
2544    }
2545
2546    /// Simplifies and sorts the kids in the whole calculation subtree.
2547    pub fn simplify_and_sort(&mut self) -> SimplificationResult {
2548        let mut res = SimplificationResult::Unchanged;
2549        self.visit_depth_first(|node| {
2550            if let SimplificationResult::Simplified = node.simplify_and_sort_direct_children() {
2551                res = SimplificationResult::Simplified;
2552            }
2553        });
2554        res
2555    }
2556
2557    fn to_css_impl<W>(&self, dest: &mut CssWriter<W>, level: ArgumentLevel) -> fmt::Result
2558    where
2559        W: Write,
2560    {
2561        let write_closing_paren = match self {
2562            Self::MinMax(_, op) => {
2563                dest.write_str(match op {
2564                    MinMaxOp::Max => "max(",
2565                    MinMaxOp::Min => "min(",
2566                })?;
2567                true
2568            },
2569            Self::Clamp { .. } => {
2570                dest.write_str("clamp(")?;
2571                true
2572            },
2573            Self::Round { strategy, .. } => {
2574                match strategy {
2575                    RoundingStrategy::Nearest => dest.write_str("round("),
2576                    RoundingStrategy::Up => dest.write_str("round(up, "),
2577                    RoundingStrategy::Down => dest.write_str("round(down, "),
2578                    RoundingStrategy::ToZero => dest.write_str("round(to-zero, "),
2579                }?;
2580
2581                true
2582            },
2583            Self::ModRem { op, .. } => {
2584                dest.write_str(match op {
2585                    ModRemOp::Mod => "mod(",
2586                    ModRemOp::Rem => "rem(",
2587                })?;
2588
2589                true
2590            },
2591            Self::Sin(_) => {
2592                dest.write_str("sin(")?;
2593                true
2594            },
2595            Self::Cos(_) => {
2596                dest.write_str("cos(")?;
2597                true
2598            },
2599            Self::Tan(_) => {
2600                dest.write_str("tan(")?;
2601                true
2602            },
2603            Self::Asin(_) => {
2604                dest.write_str("asin(")?;
2605                true
2606            },
2607            Self::Acos(_) => {
2608                dest.write_str("acos(")?;
2609                true
2610            },
2611            Self::Atan(_) => {
2612                dest.write_str("atan(")?;
2613                true
2614            },
2615            Self::Atan2(..) => {
2616                dest.write_str("atan2(")?;
2617                true
2618            },
2619            Self::Pow(..) => {
2620                dest.write_str("pow(")?;
2621                true
2622            },
2623            Self::Sqrt(_) => {
2624                dest.write_str("sqrt(")?;
2625                true
2626            },
2627            Self::Hypot(_) => {
2628                dest.write_str("hypot(")?;
2629                true
2630            },
2631            Self::Log(..) => {
2632                dest.write_str("log(")?;
2633                true
2634            },
2635            Self::Exp(_) => {
2636                dest.write_str("exp(")?;
2637                true
2638            },
2639            Self::Abs(_) => {
2640                dest.write_str("abs(")?;
2641                true
2642            },
2643            Self::Sign(_) => {
2644                dest.write_str("sign(")?;
2645                true
2646            },
2647            Self::Progress { .. } => {
2648                dest.write_str("progress(")?;
2649                true
2650            },
2651            Self::Random(_) => {
2652                dest.write_str("random(")?;
2653                true
2654            },
2655            Self::Negate(_) => {
2656                // We never generate a [`Negate`] node as the root of a calculation, only inside
2657                // [`Sum`] nodes as a child. Because negate nodes are handled by the [`Sum`] node
2658                // directly (see below), this node will never be serialized.
2659                debug_assert!(
2660                    false,
2661                    "We never serialize Negate nodes as they are handled inside Sum nodes."
2662                );
2663                dest.write_str("(-1 * ")?;
2664                true
2665            },
2666            Self::Invert(_) => {
2667                if matches!(level, ArgumentLevel::CalculationRoot) {
2668                    dest.write_str("calc")?;
2669                }
2670                dest.write_str("(1 / ")?;
2671                true
2672            },
2673            Self::Sum(_) | Self::Product(_) => match level {
2674                ArgumentLevel::CalculationRoot => {
2675                    dest.write_str("calc(")?;
2676                    true
2677                },
2678                ArgumentLevel::ArgumentRoot => false,
2679                ArgumentLevel::Nested => {
2680                    dest.write_str("(")?;
2681                    true
2682                },
2683            },
2684            Self::Leaf(leaf) => match level {
2685                ArgumentLevel::CalculationRoot => {
2686                    if leaf.should_serialize_with_root_calc_wrapper() {
2687                        dest.write_str("calc(")?;
2688                        true
2689                    } else {
2690                        false
2691                    }
2692                },
2693                ArgumentLevel::ArgumentRoot | ArgumentLevel::Nested => false,
2694            },
2695            Self::Anchor(_) | Self::AnchorSize(_) => false,
2696        };
2697
2698        match *self {
2699            Self::MinMax(ref children, _) | Self::Hypot(ref children) => {
2700                let mut first = true;
2701                for child in &**children {
2702                    if !first {
2703                        dest.write_str(", ")?;
2704                    }
2705                    first = false;
2706                    child.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?;
2707                }
2708            },
2709            Self::Negate(ref value) | Self::Invert(ref value) => {
2710                value.to_css_impl(dest, ArgumentLevel::Nested)?
2711            },
2712            Self::Sum(ref children) => {
2713                let mut first = true;
2714                for child in &**children {
2715                    if !first {
2716                        match child {
2717                            Self::Leaf(l) => {
2718                                if let Ok(true) = l.is_negative() {
2719                                    dest.write_str(" - ")?;
2720                                    let mut negated = l.clone();
2721                                    // We can unwrap here, because we already
2722                                    // checked if the value inside is negative.
2723                                    negated.map(std::ops::Neg::neg).unwrap();
2724                                    negated.to_css(dest)?;
2725                                } else {
2726                                    dest.write_str(" + ")?;
2727                                    l.to_css(dest)?;
2728                                }
2729                            },
2730                            Self::Negate(n) => {
2731                                dest.write_str(" - ")?;
2732                                n.to_css_impl(dest, ArgumentLevel::Nested)?;
2733                            },
2734                            _ => {
2735                                dest.write_str(" + ")?;
2736                                child.to_css_impl(dest, ArgumentLevel::Nested)?;
2737                            },
2738                        }
2739                    } else {
2740                        first = false;
2741                        child.to_css_impl(dest, ArgumentLevel::Nested)?;
2742                    }
2743                }
2744            },
2745            Self::Product(ref children) => {
2746                let mut first = true;
2747                for child in &**children {
2748                    if !first {
2749                        match child {
2750                            Self::Invert(n) => {
2751                                dest.write_str(" / ")?;
2752                                n.to_css_impl(dest, ArgumentLevel::Nested)?;
2753                            },
2754                            _ => {
2755                                dest.write_str(" * ")?;
2756                                child.to_css_impl(dest, ArgumentLevel::Nested)?;
2757                            },
2758                        }
2759                    } else {
2760                        first = false;
2761                        child.to_css_impl(dest, ArgumentLevel::Nested)?;
2762                    }
2763                }
2764            },
2765            Self::Clamp {
2766                ref min,
2767                ref center,
2768                ref max,
2769            } => {
2770                min.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?;
2771                dest.write_str(", ")?;
2772                center.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?;
2773                dest.write_str(", ")?;
2774                max.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?;
2775            },
2776            Self::Round {
2777                ref value,
2778                ref step,
2779                ..
2780            } => {
2781                value.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?;
2782                dest.write_str(", ")?;
2783                step.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?;
2784            },
2785            Self::ModRem {
2786                ref dividend,
2787                ref divisor,
2788                ..
2789            } => {
2790                dividend.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?;
2791                dest.write_str(", ")?;
2792                divisor.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?;
2793            },
2794            Self::Sin(ref v)
2795            | Self::Cos(ref v)
2796            | Self::Tan(ref v)
2797            | Self::Asin(ref v)
2798            | Self::Acos(ref v)
2799            | Self::Atan(ref v) => v.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?,
2800            Self::Atan2(ref a, ref b) => {
2801                a.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?;
2802                dest.write_str(", ")?;
2803                b.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?;
2804            },
2805            Self::Pow(ref a, ref b) => {
2806                a.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?;
2807                dest.write_str(", ")?;
2808                b.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?;
2809            },
2810            Self::Sqrt(ref v) | Self::Exp(ref v) => {
2811                v.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?
2812            },
2813            Self::Log(ref a, ref b) => {
2814                a.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?;
2815                if let Optional::Some(b) = b {
2816                    dest.write_str(", ")?;
2817                    b.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?;
2818                }
2819            },
2820            Self::Abs(ref v) | Self::Sign(ref v) => {
2821                v.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?
2822            },
2823            Self::Progress {
2824                clamping_mode,
2825                ref value,
2826                ref start,
2827                ref end,
2828            } => {
2829                if clamping_mode == ProgressClampingMode::NoClamp {
2830                    clamping_mode.to_css(dest)?;
2831                    dest.write_char(' ')?;
2832                }
2833                value.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?;
2834                dest.write_str(", ")?;
2835                start.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?;
2836                dest.write_str(", ")?;
2837                end.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?;
2838            },
2839            Self::Random(ref r) => {
2840                // If the random key was computed to a number, serialized into the "fixed" form.
2841                if r.key.as_leaf().and_then(|l| l.as_number()).is_some() {
2842                    dest.write_str("fixed ")?;
2843                }
2844                r.key.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?;
2845                dest.write_str(", ")?;
2846                r.min.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?;
2847                dest.write_str(", ")?;
2848                r.max.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?;
2849                if let Some(step) = r.step.as_ref() {
2850                    dest.write_str(", ")?;
2851                    step.to_css_impl(dest, ArgumentLevel::ArgumentRoot)?;
2852                }
2853            },
2854            Self::Leaf(ref l) => l.to_css(dest)?,
2855            Self::Anchor(ref f) => f.to_css(dest)?,
2856            Self::AnchorSize(ref f) => f.to_css(dest)?,
2857        }
2858
2859        if write_closing_paren {
2860            dest.write_char(')')?;
2861        }
2862        Ok(())
2863    }
2864
2865    fn to_typed_impl(
2866        &self,
2867        dest: &mut ThinVec<TypedValue>,
2868        level: ArgumentLevel,
2869    ) -> Result<(), ()> {
2870        // Note: Naturally, only nodes that can be reified into CSSUnitValue
2871        // and CSSMathValue objects are supported here:
2872        // Leaf, Negate, Invert, Sum, Product, MinMax, and Clamp.
2873        match *self {
2874            Self::Leaf(ref l) => match l.to_typed_value() {
2875                Some(TypedValue::Numeric(inner)) => {
2876                    match level {
2877                        ArgumentLevel::CalculationRoot => {
2878                            dest.push(TypedValue::Numeric(NumericValue::Math(MathValue::Sum(
2879                                MathSum::try_from_numeric_values(ThinVec::from([inner]))?,
2880                            ))));
2881                        },
2882                        ArgumentLevel::ArgumentRoot | ArgumentLevel::Nested => {
2883                            dest.push(TypedValue::Numeric(inner));
2884                        },
2885                    }
2886                    Ok(())
2887                },
2888                _ => Err(()),
2889            },
2890            Self::Negate(_) => {
2891                // We never generate a [`Negate`] node as the root of a calculation, only inside
2892                // [`Sum`] nodes as a child. Because negate nodes are handled by the [`Sum`] node
2893                // directly (see below), this node will never be reified.
2894                debug_assert!(
2895                    false,
2896                    "We never reify Negate nodes as they are handled inside Sum nodes."
2897                );
2898
2899                Err(())
2900            },
2901            Self::Invert(ref value) => {
2902                let inner = CalcNodeWithLevel::nested(value)
2903                    .to_numeric_value()
2904                    .ok_or(())?;
2905
2906                dest.push(TypedValue::Numeric(NumericValue::Math(MathValue::Invert(
2907                    MathInvert::from_numeric_value(inner),
2908                ))));
2909                Ok(())
2910            },
2911            Self::Sum(ref children) => {
2912                let mut values = ThinVec::new();
2913                let mut first = true;
2914
2915                for child in &**children {
2916                    if !first {
2917                        match child {
2918                            Self::Leaf(l) => {
2919                                if let Ok(true) = l.is_negative() {
2920                                    let mut negated = l.clone();
2921
2922                                    // We can unwrap here, because we already
2923                                    // checked if the value inside is negative.
2924                                    negated.map(std::ops::Neg::neg).unwrap();
2925
2926                                    let inner = negated.to_numeric_value().ok_or(())?;
2927
2928                                    values.push(NumericValue::Math(MathValue::Negate(
2929                                        MathNegate::from_numeric_value(inner),
2930                                    )));
2931                                } else {
2932                                    let inner = l.to_numeric_value().ok_or(())?;
2933
2934                                    values.push(inner);
2935                                }
2936                            },
2937                            Self::Negate(n) => {
2938                                let inner = CalcNodeWithLevel::nested(n.as_ref())
2939                                    .to_numeric_value()
2940                                    .ok_or(())?;
2941
2942                                values.push(NumericValue::Math(MathValue::Negate(
2943                                    MathNegate::from_numeric_value(inner),
2944                                )));
2945                            },
2946                            _ => {
2947                                let inner = CalcNodeWithLevel::nested(child)
2948                                    .to_numeric_value()
2949                                    .ok_or(())?;
2950
2951                                values.push(inner);
2952                            },
2953                        }
2954                    } else {
2955                        first = false;
2956
2957                        let inner = CalcNodeWithLevel::nested(child)
2958                            .to_numeric_value()
2959                            .ok_or(())?;
2960
2961                        values.push(inner);
2962                    }
2963                }
2964
2965                dest.push(TypedValue::Numeric(NumericValue::Math(MathValue::Sum(
2966                    MathSum::try_from_numeric_values(values)?,
2967                ))));
2968                Ok(())
2969            },
2970            Self::Product(ref children) => {
2971                let mut values = ThinVec::new();
2972                let mut first = true;
2973
2974                for child in &**children {
2975                    if !first {
2976                        match child {
2977                            Self::Invert(n) => {
2978                                let inner = CalcNodeWithLevel::nested(n.as_ref())
2979                                    .to_numeric_value()
2980                                    .ok_or(())?;
2981
2982                                values.push(NumericValue::Math(MathValue::Invert(
2983                                    MathInvert::from_numeric_value(inner),
2984                                )));
2985                            },
2986                            _ => {
2987                                let inner = CalcNodeWithLevel::nested(child)
2988                                    .to_numeric_value()
2989                                    .ok_or(())?;
2990
2991                                values.push(inner);
2992                            },
2993                        }
2994                    } else {
2995                        first = false;
2996
2997                        let inner = CalcNodeWithLevel::nested(child)
2998                            .to_numeric_value()
2999                            .ok_or(())?;
3000
3001                        values.push(inner);
3002                    }
3003                }
3004
3005                dest.push(TypedValue::Numeric(NumericValue::Math(MathValue::Product(
3006                    MathProduct::try_from_numeric_values(values)?,
3007                ))));
3008                Ok(())
3009            },
3010            Self::MinMax(ref children, op) => {
3011                let mut values = ThinVec::new();
3012
3013                for child in &**children {
3014                    let inner = CalcNodeWithLevel::argument_root(child)
3015                        .to_numeric_value()
3016                        .ok_or(())?;
3017
3018                    values.push(inner);
3019                }
3020
3021                let math_value = match op {
3022                    MinMaxOp::Min => MathValue::Min(MathMin::try_from_numeric_values(values)?),
3023                    MinMaxOp::Max => MathValue::Max(MathMax::try_from_numeric_values(values)?),
3024                };
3025
3026                dest.push(TypedValue::Numeric(NumericValue::Math(math_value)));
3027                Ok(())
3028            },
3029            Self::Clamp {
3030                ref min,
3031                ref center,
3032                ref max,
3033            } => {
3034                let lower = CalcNodeWithLevel::argument_root(min)
3035                    .to_numeric_value()
3036                    .ok_or(())?;
3037
3038                let value = CalcNodeWithLevel::argument_root(center)
3039                    .to_numeric_value()
3040                    .ok_or(())?;
3041
3042                let upper = CalcNodeWithLevel::argument_root(max)
3043                    .to_numeric_value()
3044                    .ok_or(())?;
3045
3046                dest.push(TypedValue::Numeric(NumericValue::Math(MathValue::Clamp(
3047                    MathClamp::try_from_numeric_values([lower, value, upper].into())?,
3048                ))));
3049                Ok(())
3050            },
3051            _ => Err(()),
3052        }
3053    }
3054
3055    fn compare(&self, other: &Self) -> Option<cmp::Ordering> {
3056        match (self, other) {
3057            (CalcNode::Leaf(one), CalcNode::Leaf(other)) => one.compare(other),
3058            _ => None,
3059        }
3060    }
3061
3062    compare_helpers!();
3063}
3064
3065impl<L: CalcNodeLeaf> ToCss for CalcNode<L> {
3066    /// <https://drafts.csswg.org/css-values/#calc-serialize>
3067    fn to_css<W>(&self, dest: &mut CssWriter<W>) -> fmt::Result
3068    where
3069        W: Write,
3070    {
3071        self.to_css_impl(dest, ArgumentLevel::CalculationRoot)
3072    }
3073}
3074
3075impl<L: CalcNodeLeaf> ToTyped for CalcNode<L> {
3076    fn to_typed(&self, dest: &mut ThinVec<TypedValue>) -> Result<(), ()> {
3077        CalcNodeWithLevel::calculation_root(self).to_typed(dest)
3078    }
3079}
3080
3081struct CalcNodeWithLevel<'a, L> {
3082    node: &'a CalcNode<L>,
3083    level: ArgumentLevel,
3084}
3085
3086impl<'a, L> CalcNodeWithLevel<'a, L> {
3087    #[inline]
3088    fn new(node: &'a CalcNode<L>, level: ArgumentLevel) -> Self {
3089        Self { node, level }
3090    }
3091
3092    #[inline]
3093    fn calculation_root(node: &'a CalcNode<L>) -> Self {
3094        Self::new(node, ArgumentLevel::CalculationRoot)
3095    }
3096
3097    #[inline]
3098    fn argument_root(node: &'a CalcNode<L>) -> Self {
3099        Self::new(node, ArgumentLevel::ArgumentRoot)
3100    }
3101
3102    #[inline]
3103    fn nested(node: &'a CalcNode<L>) -> Self {
3104        Self::new(node, ArgumentLevel::Nested)
3105    }
3106}
3107
3108impl<'a, L: CalcNodeLeaf> ToTyped for CalcNodeWithLevel<'a, L> {
3109    fn to_typed(&self, dest: &mut ThinVec<TypedValue>) -> Result<(), ()> {
3110        self.node.to_typed_impl(dest, self.level.clone())
3111    }
3112}