nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
//! Preserve authored scalar/unit coordinates; computed typed values retain binary64 provenance.
use crate::plugins::{
    compositions::Compositions,
    compound_units, integer_queries, syntax,
    units::{Unit, Units},
};
use crate::{Context, Error};
use num_bigint::BigInt;
use num_rational::BigRational;
use num_traits::{One, Zero};

/// Authored scalar/unit coordinates remain exact; computed roles retain their provenance.
pub(super) struct Coordinate {
    pub value: BigRational,
    pub authored: bool,
}

fn authored(value: BigRational) -> Result<Coordinate, Error> {
    Ok(Coordinate {
        value: bounded(value)?,
        authored: true,
    })
}

fn quantity_value(
    input: &str,
    reference: &str,
    engine: &Compositions,
    context: &Context,
) -> Result<f64, Error> {
    let error = match engine.quantity_value(input, reference, context) {
        Ok(value) => return Ok(value),
        Err(error) if error.0 == "invalid_expression" => error,
        Err(error) => return Err(error),
    };
    // A complete scalar coefficient and a complete unit suffix form one
    // coordinate. Group the whole coefficient, preserving its operator order.
    // Successful typed expressions and other error domains keep their owner.
    for (at, _) in input.char_indices().skip(1) {
        let coefficient = input[..at].trim();
        let unit = input[at..].trim();
        if let Some(factors) = compound_units::factors(&unit.replace(" per ", "/"), |leaf| {
            engine.units.unit(leaf).is_some()
        }) && !factors.is_empty()
            && engine.quantity_value(coefficient, "1", context).is_ok()
        {
            return engine.quantity_value(&format!("({coefficient}) {unit}"), reference, context);
        }
    }
    Err(error)
}

pub(super) fn read(
    input: &str,
    reference: &str,
    engine: &Compositions,
    context: &Context,
) -> Result<Coordinate, Error> {
    // The shared reader owns complete consumption, dimensions and numeric domains.
    let computed = quantity_value(input, reference, engine, context)?;
    let input = syntax::ungroup(input);
    if reference == "1"
        && let Ok((n, d)) = integer_queries::ratio_value(input)
    {
        return authored(BigRational::new(n, d));
    }
    let units = &engine.units;
    let (reference_dimensions, reference_scale) =
        unit_scale(reference, units).ok_or_else(|| Error("incompatible_units".into()))?;
    for (at, _) in input.char_indices().skip(1) {
        let Some((dimensions, scale)) = unit_scale(input[at..].trim(), units) else {
            continue;
        };
        if !scale.has_unit || dimensions != reference_dimensions {
            continue;
        }
        let Ok((n, d)) = integer_queries::ratio_value(input[..at].trim()) else {
            continue;
        };
        if scale.pi_power == reference_scale.pi_power {
            return authored(
                BigRational::new(n, d) * scale.coefficient / &reference_scale.coefficient,
            );
        }
    }
    // Expressions with typed calls or mixed quantities have already been computed
    // by the shared engine. Preserve that actual float, without inventing decimals.
    Ok(Coordinate {
        value: bounded(
            BigRational::from_float(computed).ok_or_else(|| Error("numeric_overflow".into()))?,
        )?,
        authored: false,
    })
}

fn leaf(name: &str, units: &Units) -> Option<Unit> {
    let name = name.trim();
    units
        .units
        .iter()
        .find(|unit| unit.symbol == name)
        .or_else(|| {
            units.units.iter().find(|unit| {
                unit.aliases
                    .split('|')
                    .any(|alias| alias.eq_ignore_ascii_case(name))
            })
        })
        .cloned()
        .or_else(|| {
            // Prefix aliases remain owned by Units. Products/powers must go
            // through the shared factor scanner instead of floating powi scales.
            (!name.contains(['/', '*', '·', '⋅', '^', '²', '³', '(', ')'])
                && !name.ends_with(['2', '3'])
                && !name.starts_with("square ")
                && !name.starts_with("cubic "))
            .then(|| units.unit(name))
            .flatten()
        })
        .filter(|unit| unit.offset == 0.0 && unit.scale.is_finite() && unit.scale > 0.0)
}

struct Scale {
    coefficient: BigRational,
    pi_power: i32,
    has_unit: bool,
}

fn unit_scale(input: &str, units: &Units) -> Option<([i8; 8], Scale)> {
    let input = input.replace(" per ", "/");
    let factors = compound_units::factors(&input, |name| leaf(name, units).is_some())?;
    let has_unit = !factors.is_empty();
    let mut dimensions = [0i8; 8];
    let mut scale = BigRational::one();
    let mut pi_power = 0;
    for (name, exponent) in factors {
        let unit = leaf(&name, units)?;
        // These registry angle symbols share pi. Cancel it symbolically rather
        // than treating separate binary approximations as exact unit relations.
        let (coefficient, pi) = match unit.symbol.as_str() {
            "°" => (BigRational::new(1.into(), 180.into()), 1),
            "′" => (BigRational::new(1.into(), 10_800.into()), 1),
            "rev" => (BigRational::from_integer(2.into()), 1),
            _ => {
                let (n, d) = integer_queries::ratio_value(&unit.scale.to_string()).ok()?;
                (BigRational::new(n, d), 0)
            }
        };
        scale *= coefficient.pow(i32::from(exponent));
        pi_power += pi * i32::from(exponent);
        for (dimension, power) in dimensions.iter_mut().zip(unit.dimension) {
            *dimension = dimension.checked_add(power.checked_mul(exponent)?)?;
        }
    }
    (!scale.is_zero()).then_some((
        dimensions,
        Scale {
            coefficient: scale,
            pi_power,
            has_unit,
        },
    ))
}

/// Scale a bounded exact square before the supplied binary64 sqrt kernel.
/// The returned rational retains that computed kernel's coordinate; callers
/// preserve computed provenance when they render the completed result.
pub(super) fn computed_root(
    squared: BigRational,
    evaluate: impl FnOnce(&str) -> Result<f64, Error>,
) -> Result<BigRational, Error> {
    let squared = bounded(squared)?;
    if squared.is_zero() {
        return Ok(BigRational::zero());
    }
    let exponent = (squared.numer().bits() as i64 - squared.denom().bits() as i64).div_euclid(2);
    let power = BigInt::one() << exponent.unsigned_abs() as usize;
    let scale = if exponent >= 0 {
        BigRational::from_integer(power)
    } else {
        BigRational::new(BigInt::one(), power)
    };
    let coefficient = bounded(squared / scale.pow(2))?;
    let root = evaluate(&format!(
        "sqrt(rational({},{}))",
        coefficient.numer(),
        coefficient.denom()
    ))?;
    bounded(BigRational::from_float(root).ok_or_else(|| Error("numeric_overflow".into()))? * scale)
}

pub(super) fn bounded(value: BigRational) -> Result<BigRational, Error> {
    if value.numer().bits().max(value.denom().bits()) > 65_536 {
        Err(Error("integer_limit".into()))
    } else {
        Ok(value)
    }
}