nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
//! Functions operate on the same typed values as binary arithmetic.
use super::{DisplayUnit, Parser, Value};
use crate::{Error, re};
use num_traits::Signed;

pub(in crate::plugins) fn has_function(input: &str) -> bool {
    re!(r"\b(?:abs|min|max|mean|sum|square|sqrt|round|real|rational|sin|cos|tan)\(").is_match(input)
}

impl Parser<'_> {
    pub(super) fn function(&mut self, input: &str, depth: usize) -> Option<Result<Value, Error>> {
        let (name, tail) = input.split_once('(')?;
        if !matches!(
            name,
            "abs"
                | "min"
                | "max"
                | "mean"
                | "sum"
                | "square"
                | "sqrt"
                | "round"
                | "real"
                | "rational"
                | "sin"
                | "cos"
                | "tan"
        ) {
            return None;
        }
        if matches!(name, "real" | "rational" | "sin" | "cos" | "tan") && self.standard {
            return None;
        }
        Some((|| {
            let invalid = || Error("invalid_expression".into());
            let arguments = arguments(
                tail.strip_suffix(')').ok_or_else(invalid)?,
                matches!(
                    name,
                    "abs" | "square" | "sqrt" | "real" | "sin" | "cos" | "tan"
                ),
            )?;
            if name == "rational" {
                if arguments.len() != 2 {
                    return Err(invalid());
                }
                // Convert the complete exact ratio once. Its numerator or
                // denominator may exceed binary64 while their quotient is finite.
                use num_traits::{ToPrimitive, Zero};
                let (n, d) = super::super::integer_queries::ratio_value(&format!(
                    "({}) / ({})",
                    arguments[0], arguments[1]
                ))?;
                let nonzero = !n.is_zero();
                let rational = num_rational::BigRational::new(n, d);
                let base = rational
                    .to_f64()
                    .ok_or_else(|| Error("numeric_overflow".into()))?;
                return Ok(Value {
                    base: super::checked_number(base, nonzero)?,
                    exact: (!self.standard)
                        .then(|| super::exact::bounded(rational, None))
                        .flatten(),
                    dimensions: Default::default(),
                    preferred: None,
                    affine_temperature: false,
                });
            }
            let many = matches!(name, "min" | "max" | "mean" | "sum");
            if arguments.is_empty()
                || (!many && arguments.len() != 1 && !(name == "round" && arguments.len() == 2))
            {
                return Err(invalid());
            }
            let mut values = arguments
                .into_iter()
                .map(|s| self.expression(s, depth + 1))
                .collect::<Result<Vec<_>, _>>()?;
            let mut value = values.remove(0);
            if matches!(name, "sin" | "cos" | "tan") {
                let angle = self.unit("rad").ok_or_else(invalid)?;
                if value.affine_temperature
                    || (!value.dimensions.is_empty() && value.dimensions != angle.dimensions)
                {
                    return Err(Error("incompatible_units".into()));
                }
                // Typed angles are already in base radians; scalars retain the
                // existing Arithmetic convention of scalar radian arguments.
                let base = super::super::arithmetic::trig(name, value.base).ok_or_else(invalid)?;
                return Ok(Value {
                    base: super::checked_number(base, false)?,
                    exact: None,
                    dimensions: Default::default(),
                    preferred: None,
                    affine_temperature: false,
                });
            }
            let display = value.preferred.clone().or_else(|| {
                self.seen
                    .iter()
                    .find(|u| u.dimensions == value.dimensions)
                    .cloned()
            });
            let precision =
                name == "round" && values.first().is_some_and(|v| v.dimensions.is_empty());
            if !precision && values.iter().any(|v| v.dimensions != value.dimensions) {
                return Err(Error("incompatible_units".into()));
            }
            if (value.affine_temperature || values.iter().any(|v| v.affine_temperature))
                && !matches!(name, "min" | "max" | "mean" | "abs" | "round")
            {
                return Err(Error("affine_unit_in_rate".into()));
            }
            let exact_abs = (name == "abs" && display.as_ref().is_none_or(|u| u.offset == 0.0))
                .then(|| value.exact.clone())
                .flatten();
            match name {
                "real" => {
                    if !value.dimensions.is_empty() {
                        return Err(Error("incompatible_units".into()));
                    }
                }
                "min" => value.base = values.iter().fold(value.base, |a, b| a.min(b.base)),
                "max" => value.base = values.iter().fold(value.base, |a, b| a.max(b.base)),
                "mean" if !self.standard => {
                    let count = (values.len() + 1) as f64;
                    let bases = std::iter::once(value.base).chain(values.iter().map(|v| v.base));
                    // Use the same compensated accumulation as Probability's weighted
                    // mean. A finite total is divided last, preserving tiny equal inputs.
                    let total = compensated_sum(bases.clone());
                    value.base = if total.is_finite() {
                        super::checked_number(total / count, total != 0.0)?
                    } else {
                        // Dividing before adding bounds finite same-sign extremes.
                        // Aggregate tiny terms before dividing: their combined mean
                        // may be representable even when each divided term is zero.
                        let lost = compensated_sum(
                            bases
                                .clone()
                                .filter(|base| *base != 0.0 && *base / count == 0.0),
                        );
                        let residual = lost / count;
                        let mean = compensated_sum(bases.map(|base| base / count)) + residual;
                        super::checked_number(
                            mean,
                            mean != 0.0 || (lost != 0.0 && residual == 0.0),
                        )?
                    };
                }
                "mean" | "sum" => {
                    // Standard mode retains its operation order.
                    value.base += values.iter().map(|v| v.base).sum::<f64>();
                    if name == "mean" {
                        value.base = super::checked_number(
                            value.base / (values.len() + 1) as f64,
                            value.base != 0.0,
                        )?;
                    }
                }
                "abs" => {
                    let offset = display.as_ref().map_or(0.0, |u| u.offset);
                    value.base = (value.base - offset).abs() + offset;
                }
                "round" => {
                    let scale = display.as_ref().map_or(1.0, |u| u.scale);
                    let offset = if precision || values.is_empty() {
                        display.as_ref().map_or(0.0, |u| u.offset)
                    } else {
                        0.0
                    };
                    if !precision && values.iter().any(|v| v.affine_temperature) {
                        return Err(Error("affine_unit_in_rate".into()));
                    }
                    let increment = if precision {
                        let places = values[0].base;
                        if places.fract() != 0.0 || !(0.0..=15.0).contains(&places) {
                            return Err(Error("invalid_rounding_precision".into()));
                        }
                        scale * 10.0_f64.powi(-(places as i32))
                    } else {
                        values.first().map_or(scale, |v| v.base)
                    };
                    if increment <= 0.0 || !increment.is_finite() {
                        return Err(Error("invalid_rounding_increment".into()));
                    }
                    let ratio = (value.base - offset) / increment;
                    // Decimal unit scales can put an exact half one ulp below the tie.
                    let magnitude = ratio.abs();
                    let tolerance = 8.0 * f64::EPSILON * magnitude.clamp(1.0, 1e6);
                    let rounded = if (magnitude.fract() - 0.5).abs() <= tolerance {
                        (magnitude.floor() + 1.0).copysign(ratio)
                    } else {
                        ratio.round()
                    };
                    value.base = rounded * increment + offset;
                }
                "square" | "sqrt" => {
                    let square = name == "square";
                    if !square
                        && (value.base < 0.0 || value.dimensions.values().any(|p| p % 2 != 0))
                    {
                        return Err(Error("incompatible_units".into()));
                    }
                    value.base = if square {
                        super::checked_number(value.base * value.base, value.base != 0.0)?
                    } else {
                        value.base.sqrt()
                    };
                    for exponent in value.dimensions.values_mut() {
                        *exponent = if square {
                            exponent.checked_mul(2).ok_or_else(invalid)?
                        } else {
                            *exponent / 2
                        };
                    }
                    value.preferred = display.as_ref().and_then(|unit| {
                        if square {
                            if unit.name.contains(['/', '·', '⋅', '*']) {
                                return None;
                            }
                            let name = self
                                .units
                                .unit(&format!("square {}", unit.name))
                                .filter(|u| super::physical(u) == value.dimensions)
                                .map_or_else(|| format!("({})^2", unit.name), |u| u.symbol);
                            Some(DisplayUnit {
                                name,
                                scale: unit.scale * unit.scale,
                                dimensions: value.dimensions.clone(),
                                currency: false,
                                offset: 0.0,
                            })
                        } else {
                            // Prefer the source unit's root; otherwise use the registry's base unit.
                            unit.name
                                .strip_suffix('²')
                                .and_then(|name| self.unit(name))
                                .or_else(|| {
                                    unit.name
                                        .strip_prefix('(')?
                                        .strip_suffix(")^2")
                                        .and_then(|name| self.unit(name))
                                })
                                .or_else(|| {
                                    self.units
                                        .units
                                        .iter()
                                        .find(|u| {
                                            super::physical(u) == value.dimensions
                                                && u.scale == 1.0
                                                && u.offset == 0.0
                                        })
                                        .and_then(|u| self.unit(&u.symbol))
                                })
                        }
                    });
                }
                _ => unreachable!(),
            }
            value.exact = if name == "abs" {
                exact_abs.and_then(|mut exact| {
                    exact.amount = exact.amount.abs();
                    super::exact::bounded(exact.amount, exact.currency)
                })
            } else {
                None
            };
            if !matches!(name, "square" | "sqrt") {
                value.preferred = display;
            }
            if !value.base.is_finite() {
                return Err(Error("numeric_overflow".into()));
            }
            Ok(value)
        })())
    }
}

pub(in crate::plugins) fn arguments(input: &str, unary: bool) -> Result<Vec<&str>, Error> {
    let mut values = vec![];
    let (mut depth, mut start) = (0i32, 0);
    for (index, ch) in input.char_indices() {
        match ch {
            '(' => depth += 1,
            ')' => depth -= 1,
            ',' if depth == 0 => {
                // A compact three-digit group inside a numeric literal is a thousands separator.
                let tail = &input[index + 1..];
                let digits = tail.bytes().take_while(u8::is_ascii_digit).count();
                if digits == 3
                    && input[..index]
                        .chars()
                        .next_back()
                        .is_some_and(|c| c.is_ascii_digit())
                    && ((tail.len() == 3 && unary)
                        || tail[3..]
                            .chars()
                            .next()
                            .is_some_and(|c| c.is_alphabetic() || matches!(c, ',' | '.' | ' ')))
                {
                    continue;
                }
                values.push(input[start..index].trim());
                start = index + 1;
            }
            _ => {}
        }
        if depth < 0 {
            return Err(Error("invalid_expression".into()));
        }
    }
    values.push(input[start..].trim());
    if depth != 0 || values.iter().any(|s| s.is_empty()) {
        return Err(Error("invalid_expression".into()));
    }
    Ok(values)
}

/// Neumaier summation retains small contributions between cancelling finite terms.
fn compensated_sum(values: impl Iterator<Item = f64>) -> f64 {
    let (mut sum, mut correction) = (0.0_f64, 0.0_f64);
    for value in values {
        let next = sum + value;
        correction += if sum.abs() >= value.abs() {
            (sum - next) + value
        } else {
            (value - next) + sum
        };
        sum = next;
    }
    sum + correction
}