nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
//! Bounded supplied conversion clauses; definitions stay local to their request.
use super::PracticalRequest;
use crate::plugins::{
    integer_queries, model_coordinates, model_coordinates::Coordinate, syntax, units::Unit,
};
use crate::{Error, Outcome, re};
use num_rational::BigRational;
use num_traits::{One, Signed, ToPrimitive, Zero};

fn invalid() -> Error {
    Error("invalid_expression".into())
}
fn physical() -> Error {
    Error("invalid_physical_quantity".into())
}

struct Amount {
    value: BigRational,
    authored: bool,
    name: String,
    unit: Option<Unit>,
}
struct Definition {
    left: Amount,
    right: Amount,
}

impl PracticalRequest<'_> {
    pub(super) fn conversion_unit(&self, name: &str) -> Option<Unit> {
        self.engine.units.unit(name).or_else(|| {
            // An abbreviated registered leaf retains an explicit qualifier,
            // e.g. the known gal symbol under the registered US gallon alias.
            let (qualifier, leaf) = name.trim().split_once(' ')?;
            let base = self.engine.units.unit(leaf)?;
            self.engine
                .units
                .units
                .iter()
                .find(|unit| {
                    unit.aliases.split('|').any(|alias| {
                        let Some((prefix, leaf)) = alias.split_once(' ') else {
                            return false;
                        };
                        prefix.eq_ignore_ascii_case(qualifier)
                            && self
                                .engine
                                .units
                                .unit(leaf)
                                .is_some_and(|u| u.symbol == base.symbol)
                    })
                })
                .cloned()
        })
    }
    fn conversion_amount(&self, input: &str) -> Result<Amount, Error> {
        let input = syntax::ungroup(input);
        for (index, _) in input.char_indices().skip(1) {
            let Some(unit) = self.conversion_unit(input[index..].trim()) else {
                continue;
            };
            let scalar = input[..index].trim();
            if integer_queries::ratio_value(scalar).is_err()
                && self
                    .engine
                    .quantity_value(scalar, "1", self.context)
                    .is_err()
            {
                continue;
            }
            let coordinate = model_coordinates::read(scalar, "1", self.engine, self.context)?;
            if unit.offset != 0.0 {
                return Err(invalid());
            }
            return Ok(Amount {
                value: coordinate.value,
                authored: coordinate.authored,
                name: unit.symbol.clone(),
                unit: Some(unit),
            });
        }
        // A declared unknown leaf may acquire a physical dimension locally.
        // Its coefficient still uses the existing exact scalar reader.
        let c = re!(r"^(.+)\s+([A-Za-z][A-Za-z0-9_]{0,31})$")
            .captures(input)
            .ok_or_else(invalid)?;
        let coordinate = model_coordinates::read(&c[1], "1", self.engine, self.context)?;
        Ok(Amount {
            value: coordinate.value,
            authored: coordinate.authored,
            name: c[2]
                .strip_suffix('s')
                .filter(|_| c[2].len() > 3)
                .unwrap_or(&c[2])
                .into(),
            unit: None,
        })
    }

    fn local_conversion(
        &self,
        source: &str,
        target: &str,
        declarations: &str,
    ) -> Result<String, Error> {
        let coordinate = self.local_coordinate(source, target, declarations)?;
        let target = self.conversion_unit(target).ok_or_else(invalid)?;
        let expression = format!("(({}) {})", coordinate_literal(&coordinate)?, target.symbol);
        if expression.len() > 4096 {
            return Err(invalid());
        }
        self.engine
            .quantity_value(&expression, &target.symbol, self.context)?;
        Ok(expression)
    }

    pub(super) fn local_coordinate(
        &self,
        source: &str,
        target: &str,
        declarations: &str,
    ) -> Result<Coordinate, Error> {
        let clauses = re!(r"(?i) and ").split(declarations).collect::<Vec<_>>();
        if !(1..=4).contains(&clauses.len()) {
            return Err(invalid());
        }
        let mut definitions = Vec::new();
        let mut dimension = None;
        for clause in clauses {
            let (left, right) = clause.split_once('=').ok_or_else(invalid)?;
            if right.contains('=') {
                return Err(invalid());
            }
            let left = self.conversion_amount(left.trim())?;
            let right = self.conversion_amount(right.trim())?;
            if !left.value.is_positive() || !right.value.is_positive() {
                return Err(physical());
            }
            let declared_dimension = match (&left.unit, &right.unit) {
                (Some(a), Some(b)) if a.dimension != b.dimension => {
                    return Err(Error("incompatible_units".into()));
                }
                (Some(a), _) | (_, Some(a)) => Some(a.dimension),
                _ => None,
            };
            if dimension
                .zip(declared_dimension)
                .is_some_and(|(a, b)| a != b)
            {
                return Err(Error("incompatible_units".into()));
            }
            dimension = dimension.or(declared_dimension);
            definitions.push(Definition { left, right });
        }
        let target = self.conversion_unit(target).ok_or_else(invalid)?;
        if Some(target.dimension) != dimension || target.offset != 0.0 {
            return Err(Error("incompatible_units".into()));
        }
        let source = self.conversion_amount(source)?;
        if source.value.is_negative() {
            return Err(physical());
        }
        if source
            .unit
            .as_ref()
            .is_some_and(|u| Some(u.dimension) != dimension)
        {
            return Err(Error("incompatible_units".into()));
        }
        // At most four authored equations: propagate one coordinate through
        // their connected component, checking every redundant relation exactly.
        let mut coordinates = vec![(source.name.clone(), BigRational::one(), source.unit.clone())];
        let mut used = vec![false; definitions.len()];
        let mut authored = source.authored;
        for _ in 0..definitions.len() {
            for (index, definition) in definitions.iter().enumerate() {
                let left = coordinates
                    .iter()
                    .find(|(name, _, _)| *name == definition.left.name);
                let right = coordinates
                    .iter()
                    .find(|(name, _, _)| *name == definition.right.name);
                match (left, right) {
                    (Some((_, a, _)), Some((_, b, _))) => {
                        if a * &definition.right.value != b * &definition.left.value {
                            return Err(physical());
                        }
                        used[index] = true;
                    }
                    (Some((_, value, _)), None) => {
                        let value = model_coordinates::bounded(
                            value * &definition.right.value / &definition.left.value,
                        )?;
                        coordinates.push((
                            definition.right.name.clone(),
                            value,
                            definition.right.unit.clone(),
                        ));
                        used[index] = true;
                    }
                    (None, Some((_, value, _))) => {
                        let value = model_coordinates::bounded(
                            value * &definition.left.value / &definition.right.value,
                        )?;
                        coordinates.push((
                            definition.left.name.clone(),
                            value,
                            definition.left.unit.clone(),
                        ));
                        used[index] = true;
                    }
                    (None, None) => {}
                }
            }
        }
        if used.iter().any(|used| !used) {
            return Err(invalid());
        }
        for definition in &definitions {
            authored &= definition.left.authored && definition.right.authored;
        }
        let (_, value, unit) = coordinates
            .iter()
            .find(|(name, _, _)| *name == target.symbol)
            // Prefer a registered base coordinate when the requested prefixed
            // target is outside the declarations, rather than reintroducing
            // a builtin scale for an explicitly redefined endpoint.
            .or_else(|| {
                coordinates
                    .iter()
                    .find(|(_, _, unit)| unit.as_ref().is_some_and(|u| u.scale == 1.0))
            })
            .or_else(|| coordinates.iter().rev().find(|(_, _, unit)| unit.is_some()))
            .ok_or_else(invalid)?;
        let unit = unit.as_ref().ok_or_else(invalid)?;
        let scale = model_coordinates::read(
            &format!("1 {}", unit.symbol),
            &target.symbol,
            self.engine,
            self.context,
        )?;
        let value = model_coordinates::bounded(&source.value * value * scale.value)?;
        Ok(Coordinate {
            value,
            authored: authored && scale.authored,
        })
    }

    pub(super) fn conversions(&self, input: &str) -> Outcome {
        if input.len() > 4096 {
            return None;
        }
        if let Some(result) = self.supplied_conversions(input) {
            return Some(result);
        }
        if let Some(c) = re!(r"(?i)^calculate (.+?)% of (.+?) in (.+?), assuming (.+?) per (.+)$")
            .captures(input)
        {
            return Some((|| {
                let probability = model_coordinates::read(&c[1], "1", self.engine, self.context)?;
                let converted =
                    self.local_conversion(&c[2], &c[3], &format!("1 {} = {}", &c[5], &c[4]))?;
                let percentage = if probability.authored {
                    let value = probability.value / BigRational::from_integer(100.into());
                    format!("rational({},{})", value.numer(), value.denom())
                } else {
                    format!(
                        "real({})/100",
                        probability.value.to_f64().ok_or_else(invalid)?
                    )
                };
                Ok(format!("({percentage})*{converted} in {}", &c[3]))
            })());
        }
        if let Some(c) = re!(r"(?i)^an? [a-z]+ produces (.+?)\. convert this to (.+?) using (.+)$")
            .captures(input)
        {
            return Some(self.local_conversion(&c[1], &c[2], &c[3]));
        }
        if let Some(c) =
            re!(r"(?i)^convert (.+?) to (.+?) using (.+?), then express the result in (.+)$")
                .captures(input)
        {
            return Some((|| {
                let result = self.local_conversion(&c[1], &c[2], &c[3])?;
                self.engine.quantity_value(&result, &c[4], self.context)?;
                Ok(format!("{result} in {}", &c[4]))
            })());
        }
        if let Some(c) =
            re!(r"(?i)^convert a ([a-z]+) of (.+?) to (.+?) using (.+)$").captures(input)
        {
            return Some((|| {
                let reference = role_unit(&c[1]).ok_or_else(invalid)?;
                self.engine
                    .quantity_value(&format!("1 {}", &c[3]), reference, self.context)?;
                self.local_conversion(&c[2], &c[3], &c[4])
            })());
        }
        if let Some(c) =
            re!(r"(?i)^convert (.+?) to (.+?) using (.+ = .+ and .+ = .+)$").captures(input)
        {
            // The physical definition adapter owns registered physical targets.
            // Common-base currency graphs remain with the financial wording owner.
            self.engine.units.unit(&c[2])?;
            return Some(self.local_conversion(&c[1], &c[2], &c[3]));
        }
        if let Some(c) = re!(r"(?i)^convert (.+?) to (.+?) and (.+)$").captures(input) {
            // Only complete unit targets belong to an ordered conversion report.
            // Instruction sequences such as "and give the remainder" retain
            // ownership in Language rather than becoming malformed reports.
            let units = [
                self.engine.units.unit(&c[2])?,
                self.engine.units.unit(&c[3])?,
            ];
            return Some((|| {
                let targets = [&c[2], &c[3]];
                let mut fields = Vec::new();
                let mut dimension = None;
                for (target, unit) in targets.into_iter().zip(units) {
                    if dimension.is_some_and(|d| d != unit.dimension) {
                        return Err(Error("incompatible_units".into()));
                    }
                    dimension = Some(unit.dimension);
                    let label = dimension_label(unit.dimension).ok_or_else(invalid)?;
                    let value = self.engine.quantity_value(&c[1], target, self.context)?;
                    fields.push(format!("{label}|{}|real({value})", unit.symbol));
                }
                Ok(format!("practical_summary({})", fields.join(";")))
            })());
        }
        None
    }
}

pub(super) fn coordinate_literal(coordinate: &Coordinate) -> Result<String, Error> {
    let value = model_coordinates::bounded(coordinate.value.clone())?;
    if coordinate.authored {
        return Ok(format!("rational({},{})", value.numer(), value.denom()));
    }
    let float = value
        .to_f64()
        .filter(|v| v.is_finite())
        .ok_or_else(|| Error("numeric_overflow".into()))?;
    if float == 0.0 && !value.is_zero() {
        return Err(Error("numeric_underflow".into()));
    }
    Ok(format!("real({float})"))
}

fn role_unit(label: &str) -> Option<&'static str> {
    Some(match label.to_ascii_lowercase().as_str() {
        "length" => "m",
        "mass" => "kg",
        "duration" => "s",
        "area" => "m²",
        "volume" => "L",
        "energy" => "J",
        "power" => "W",
        "pressure" => "Pa",
        _ => return None,
    })
}
fn dimension_label(dimension: [i8; 8]) -> Option<&'static str> {
    Some(match dimension {
        [1, 0, 0, 0, 0, 0, 0, 0] => "length",
        [0, 1, 0, 0, 0, 0, 0, 0] => "mass",
        [0, 0, 1, 0, 0, 0, 0, 0] => "duration",
        [0, 0, 0, 1, 0, 0, 0, 0] => "temperature",
        [2, 0, 0, 0, 0, 0, 0, 0] => "area",
        [3, 0, 0, 0, 0, 0, 0, 0] => "volume",
        [2, 1, -2, 0, 0, 0, 0, 0] => "energy",
        [2, 1, -3, 0, 0, 0, 0, 0] => "power",
        [-1, 1, -2, 0, 0, 0, 0, 0] => "pressure",
        _ => return None,
    })
}