/* This Source Code Form is subject to the terms of the Mozilla Public * License, v. 2.0. If a copy of the MPL was not distributed with this * file, You can obtain one at https://mozilla.org/MPL/2.0/. */ //! [Calc expressions][calc]. //! //! [calc]: https://drafts.csswg.org/css-values/#calc-notation use crate::derives::*; use crate::typed_om::{ MathClamp, MathInvert, MathMax, MathMin, MathNegate, MathProduct, MathSum, MathValue, NumericBaseType, NumericType, NumericValue, ToTyped, TypedValue, }; use crate::values::calc_random; use crate::values::specified::NoCalcPercentage; use crate::values::generics::Optional; use crate::values::generics::length::GenericAnchorSizeFunction; use crate::values::generics::position::{GenericAnchorFunction, GenericAnchorSide}; use num_traits::Zero; use smallvec::SmallVec; use std::convert::AsRef; use std::fmt::{self, Write}; use std::ops::{Add, Mul, Rem, Sub}; use std::{cmp, mem}; use strum_macros::AsRefStr; use style_traits::{CssWriter, ToCss}; use thin_vec::ThinVec; /// Whether we're a `min` or `max` function. #[derive( Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize, ToAnimatedZero, ToResolvedValue, ToShmem, )] #[repr(u8)] pub enum MinMaxOp { /// `min()` Min, /// `max()` Max, } /// Whether we're a `mod` or `rem` function. #[derive( Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize, ToAnimatedZero, ToResolvedValue, ToShmem, )] #[repr(u8)] pub enum ModRemOp { /// `mod()` Mod, /// `rem()` Rem, } impl ModRemOp { fn apply(self, dividend: f32, divisor: f32) -> f32 { // In mod(A, B) only, if B is infinite and A has opposite sign to B // (including an oppositely-signed zero), the result is NaN. // https://drafts.csswg.org/css-values/#round-infinities if matches!(self, Self::Mod) && divisor.is_infinite() && dividend.is_sign_negative() != divisor.is_sign_negative() { return f32::NAN; } let (r, same_sign_as) = match self { Self::Mod => (dividend - divisor * (dividend / divisor).floor(), divisor), Self::Rem => (dividend - divisor * (dividend / divisor).trunc(), dividend), }; if r == 0.0 && same_sign_as.is_sign_negative() { -0.0 } else { r } } } /// The strategy used in `round()` #[derive( Clone, Copy, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize, ToAnimatedZero, ToResolvedValue, ToShmem, )] #[repr(u8)] pub enum RoundingStrategy { /// `round(nearest, a, b)` /// round a to the nearest multiple of b Nearest, /// `round(up, a, b)` /// round a up to the nearest multiple of b Up, /// `round(down, a, b)` /// round a down to the nearest multiple of b Down, /// `round(to-zero, a, b)` /// round a to the nearest multiple of b that is towards zero ToZero, } /// The clamping mode used in `progress()` #[derive( Clone, Copy, Debug, Deserialize, MallocSizeOf, Parse, PartialEq, Serialize, ToAnimatedZero, ToCss, ToResolvedValue, ToShmem, )] #[repr(u8)] pub enum ProgressClampingMode { /// `progress(value, start, end)` /// Progress result is clamped to the range [0, 1}. #[css(skip)] Clamp, /// `progress(no-clamp value, start, end)` /// Progress result can be any number. NoClamp, } impl ProgressClampingMode { fn evaluate(self, value: f32, start: f32, end: f32) -> f32 { if start == end && self == Self::Clamp { return 0.; } let progress = crate::values::normalize((value - start) / (end - start)); match self { Self::Clamp => progress.max(0.).min(1.), Self::NoClamp => progress, } } } /// This determines the order in which we serialize members of a calc() sum. /// /// See https://drafts.csswg.org/css-values-4/#sort-a-calculations-children #[derive( AsRefStr, Clone, Copy, Debug, Eq, Ord, Parse, PartialEq, PartialOrd, MallocSizeOf, ToShmem, )] #[strum(serialize_all = "lowercase")] #[allow(missing_docs)] pub enum SortKey { #[strum(serialize = "")] Number, #[css(skip)] #[strum(serialize = "%")] Percentage, Cap, Ch, Cqb, Cqh, Cqi, Cqmax, Cqmin, Cqw, Deg, Dppx, Dvb, Dvh, Dvi, Dvmax, Dvmin, Dvw, Em, Ex, Ic, Lh, Lvb, Lvh, Lvi, Lvmax, Lvmin, Lvw, Ms, Px, Rcap, Rch, Rem, Rex, Ric, Rlh, S, // Sec Svb, Svh, Svi, Svmax, Svmin, Svw, Vb, Vh, Vi, Vmax, Vmin, Vw, #[css(skip)] ColorComponent, #[css(skip)] Other, } /// Fallback type for anchor functions within `calc()`. /// Ideally, the fallback type is initial type of the property (e.g. /// `GenericInset` for `left`), but that causes circular reference. /// TODO(dshin, bug 2034100): Investigate ways to not require this. /// This handles the parsing of unitless zeros, as well as ensuring /// that e.g. `calc(anchor(--foo left, 1px) + 10%)` round trips /// (sorting aside), instead of becoming /// `calc(anchor(--foo left, calc(1px)) + 10%)`. #[repr(C)] #[derive( Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize, ToAnimatedZero, ToResolvedValue, ToShmem, )] pub struct GenericAnchorFunctionFallback { /// Was this node parsed as a calc node? #[animation(constant)] is_calc_node: bool, /// The parsed fallback value. Stored as a calc node to break /// the circular reference. pub node: GenericCalcNode, } impl GenericAnchorFunctionFallback { /// Create a new anchor function fallback value. pub fn new(is_calc_node: bool, node: GenericCalcNode) -> Self { Self { is_calc_node, node } } } impl ToCss for GenericAnchorFunctionFallback { fn to_css(&self, dest: &mut CssWriter) -> fmt::Result where W: Write, { self.node.to_css_impl( dest, if self.is_calc_node { ArgumentLevel::CalculationRoot } else { ArgumentLevel::ArgumentRoot }, ) } } /// `anchor()` function used in math functions. pub type GenericCalcAnchorFunction = GenericAnchorFunction>, Box>>; /// `anchor-size()` function used in math functions. pub type GenericCalcAnchorSizeFunction = GenericAnchorSizeFunction>>; /// A `random()` function. /// https://drafts.csswg.org/css-values-5/#funcdef-random #[repr(C)] #[derive( Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize, ToAnimatedZero, ToResolvedValue, ToShmem, )] pub struct GenericRandomFunction { /// The ``, resolving to the random base value. pub key: GenericCalcNode, /// The minimum value the function can resolve to, inclusive. pub min: GenericCalcNode, /// The maximum value the function can resolve to, inclusive. pub max: GenericCalcNode, /// The optional step value. pub step: Optional>, } /// A generic node in a calc expression. /// /// FIXME: This would be much more elegant if we used `Self` in the types below, /// but we can't because of https://github.com/serde-rs/serde/issues/1565. /// /// FIXME: The following annotations are to workaround an LLVM inlining bug, see /// bug 1631929. /// /// cbindgen:destructor-attributes=MOZ_NEVER_INLINE /// cbindgen:copy-constructor-attributes=MOZ_NEVER_INLINE /// cbindgen:eq-attributes=MOZ_NEVER_INLINE #[repr(u8)] #[derive( Clone, Debug, Deserialize, MallocSizeOf, PartialEq, Serialize, ToAnimatedZero, ToResolvedValue, ToShmem, )] pub enum GenericCalcNode { /// A leaf node. Leaf(L), /// A node that negates its child, e.g. Negate(1) == -1. Negate(Box), /// A node that inverts its child, e.g. Invert(10) == 1 / 10 == 0.1. The child must always /// resolve to a number unit. Invert(Box), /// A sum node, representing `a + b + c` where a, b, and c are the /// arguments. Sum(crate::OwnedSlice), /// A product node, representing `a * b * c` where a, b, and c are the /// arguments. Product(crate::OwnedSlice), /// A `min` or `max` function. MinMax(crate::OwnedSlice, MinMaxOp), /// A `clamp()` function. Clamp { /// The minimum value. min: Box, /// The central value. center: Box, /// The maximum value. max: Box, }, /// A `round()` function. Round { /// The rounding strategy. strategy: RoundingStrategy, /// The value to round. value: Box, /// The step value. step: Box, }, /// A `mod()` or `rem()` function. ModRem { /// The dividend calculation. dividend: Box, /// The divisor calculation. divisor: Box, /// Is the function mod or rem? op: ModRemOp, }, /// A `sin()` function. Sin(Box), /// A `cos()` function. Cos(Box), /// A `tan()` function. Tan(Box), /// An `asin()` function. Asin(Box), /// An `acos()` function. Acos(Box), /// An `atan()` function. Atan(Box), /// An `atan2()` function. Atan2(Box, Box), /// A `pow()` function. Pow(Box, Box), /// A `sqrt()` function. Sqrt(Box), /// A `hypot()` function Hypot(crate::OwnedSlice), /// A `log()` function. Log(Box, Optional>), /// An `exp()` function. Exp(Box), /// An `abs()` function. Abs(Box), /// A `sign()` function. Sign(Box), /// A `progress()` function. Progress { /// Clamping mode for the result. clamping_mode: ProgressClampingMode, /// The progress value calculation. value: Box, /// The progress start calculation. start: Box, /// The progress end calculation. end: Box, }, /// A `random()` function. Random(Box>), /// An `anchor()` function. Anchor(Box>), /// An `anchor-size()` function. AnchorSize(Box>), } pub use self::GenericCalcNode as CalcNode; fn typed_arithmetic_enabled() -> bool { crate::pref!("layout.css.calc-typed-arithmetic.enabled") } /// The non-mixed types that a math function can return. Note that /// is not represented in this list as a separate type from /// , as "math functions that resolve to can be used /// in any place that only accepts ". CSS Typed OM also does /// not distinguish between numbers and integers. /// /// https://drafts.csswg.org/css-values-4/#math-function /// https://drafts.csswg.org/css-values-4/#calc-type-checking /// /// TODO(Bug 1866236) - Add the type. #[derive(Clone, Copy, PartialEq, Eq)] #[repr(u8)] pub enum CalcType { /// Length, /// Percentage, /// Angle, ///