nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
//! Complete measured-rate, repeated-energy, fuel and data-transfer requests.
use super::{PracticalRequest, conversions::coordinate_literal};
use crate::plugins::{model_coordinates, model_coordinates::Coordinate, syntax};
use crate::{Error, Outcome, re};
use num_traits::{Signed, Zero};

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

impl PracticalRequest<'_> {
    fn conversion_role(
        &self,
        input: &str,
        unit: &str,
        positive: bool,
        code: &str,
    ) -> Result<Coordinate, Error> {
        let coordinate = model_coordinates::read(input, unit, self.engine, self.context)?;
        if coordinate.value.is_negative() || positive && coordinate.value.is_zero() {
            return Err(Error(code.into()));
        }
        Ok(coordinate)
    }

    fn conversion_field(
        &self,
        label: &str,
        coordinate: &Coordinate,
        target: &str,
        reference: &str,
    ) -> Result<String, Error> {
        let target = self.conversion_unit(target).ok_or_else(invalid)?;
        self.engine
            .quantity_value(&format!("1 {}", target.symbol), reference, self.context)?;
        let literal = coordinate_literal(coordinate)?;
        self.engine.quantity_value(
            &format!("({literal}) {}", target.symbol),
            &target.symbol,
            self.context,
        )?;
        Ok(format!("{label}|{}|{literal}", target.symbol))
    }

    fn conversion_report(&self, fields: Vec<String>) -> Result<String, Error> {
        if !(2..=4).contains(&fields.len()) {
            return Err(invalid());
        }
        let report = format!("practical_summary({})", fields.join(";"));
        if report.len() > 4096 {
            return Err(invalid());
        }
        Ok(report)
    }

    pub(super) fn supplied_conversions(&self, input: &str) -> Outcome {
        if let Some(c) = re!(r"(?i)^a [a-z]+ [a-z]+ has (.+?) decimal capacity, and files occupy (.+?); how many decimal (gigabytes|GB) remain, using (.+)$").captures(input) {
            return Some((|| {
                // Both definitions participate in the same connected byte graph;
                // they are validated even when one quantity is zero.
                let capacity = self.local_coordinate(&c[1], &c[3], &c[4])?;
                let occupied = self.local_coordinate(&c[2], &c[3], &c[4])?;
                self.conversion_role(&format!("1 {}", &c[3]), "B", true, "incompatible_units")?;
                if occupied.value > capacity.value {
                    return Err(Error("invalid_physical_quantity".into()));
                }
                let remaining = Coordinate {
                    value: model_coordinates::bounded(capacity.value - occupied.value)?,
                    authored: capacity.authored && occupied.authored,
                };
                let target = self.conversion_unit(&c[3]).ok_or_else(invalid)?;
                let expression = format!("(({}) {}) in {}", coordinate_literal(&remaining)?, target.symbol, target.symbol);
                if expression.len() > 4096 { return Err(invalid()); }
                self.engine.quantity_value(&expression, "B", self.context)?;
                Ok(expression)
            })());
        }
        if let Some(c) = re!(r"(?i)^given (.+?), convert (.+?) to (.+)$").captures(input) {
            // Only a physical target and a complete equality declaration belong
            // here; supplied financial bindings retain their financial owner.
            self.conversion_unit(&c[3])?;
            if !c[1].contains('=') {
                return None;
            }
            return Some((|| {
                let coordinate = self.local_coordinate(&c[2], &c[3], &c[1])?;
                let target = self.conversion_unit(&c[3]).ok_or_else(invalid)?;
                let expression = format!(
                    "(({}) {}) in {}",
                    coordinate_literal(&coordinate)?,
                    target.symbol,
                    target.symbol
                );
                if expression.len() > 4096 {
                    return Err(invalid());
                }
                self.engine
                    .quantity_value(&expression, &target.symbol, self.context)?;
                Ok(expression)
            })());
        }
        if let Some(c) =
            re!(r"(?i)^an? [a-z]+ moves (.+?) each (.+?); give its rate in (.+?) using (.+)$")
                .captures(input)
        {
            return Some((|| {
                self.conversion_role(&c[1], "m", false, "invalid_physical_quantity")?;
                self.conversion_role(&c[2], "s", true, "invalid_duration")?;
                let targets = c[3].replace(", and ", ",").replace(" and ", ",");
                let targets = targets.split(',').map(str::trim).collect::<Vec<_>>();
                if !(2..=4).contains(&targets.len()) {
                    return Err(invalid());
                }
                let mut fields = Vec::new();
                for target in targets {
                    let target = target.replace(" per ", "/");
                    self.engine
                        .quantity_value(&format!("1 {target}"), "m/s", self.context)?;
                    let (length, period) =
                        syntax::split_last(&target, &["/"]).ok_or_else(invalid)?;
                    let distance = self.local_coordinate(&c[1], length, &c[4])?;
                    let duration = self.conversion_role(&c[2], period, true, "invalid_duration")?;
                    let speed = Coordinate {
                        value: model_coordinates::bounded(distance.value / duration.value)?,
                        authored: distance.authored && duration.authored,
                    };
                    fields.push(self.conversion_field("speed", &speed, &target, "m/s")?);
                }
                self.conversion_report(fields)
            })());
        }
        if let Some(c) = re!(r"(?i)^a (.+?) [a-z]+ operates (.+?) per (.+?) for (.+?); report energy in (.+?) and (.+?) using (.+)$").captures(input) {
            return Some((|| {
                let power = self.conversion_role(&c[1], "kW", false, "invalid_physical_quantity")?;
                let duration = self.conversion_role(&c[2], "hours", false, "invalid_duration")?;
                let period = self.conversion_role(&format!("1 {}", &c[3]), "s", true, "invalid_duration")?;
                let elapsed = self.conversion_role(&c[4], "s", false, "invalid_duration")?;
                let active_seconds = self.conversion_role(&c[2], "s", false, "invalid_duration")?;
                if active_seconds.value > period.value { return Err(Error("invalid_duration".into())); }
                let energy = Coordinate {
                    value: model_coordinates::bounded(power.value * duration.value * elapsed.value / period.value)?,
                    authored: power.authored && duration.authored && elapsed.authored && period.authored,
                };
                let source = format!("({}) kWh", coordinate_literal(&energy)?);
                let mut fields = Vec::new();
                for target in [&c[5], &c[6]] {
                    let coordinate = self.local_coordinate(&source, target, &c[7])?;
                    fields.push(self.conversion_field("energy", &coordinate, target, "J")?);
                }
                self.conversion_report(fields)
            })());
        }
        if let Some(c) = re!(r"(?i)^an? [a-z]+ averages (.+?); how many (.+?) are needed for (.+?) using (.+?), and what is that volume in (.+?) using (.+)$").captures(input) {
            return Some((|| {
                let (fuel, distance) = syntax::split_last(&c[1], &["/"]).ok_or_else(invalid)?;
                let fuel = self.conversion_role(fuel, "L", false, "invalid_physical_quantity")?;
                let distance = self.conversion_role(distance, "km", true, "invalid_physical_quantity")?;
                let trip = self.local_coordinate(&c[3], "km", &c[4])?;
                let required = Coordinate {
                    value: model_coordinates::bounded(fuel.value * trip.value / distance.value)?,
                    authored: fuel.authored && trip.authored && distance.authored,
                };
                let first_unit = self.conversion_unit(&c[2]).ok_or_else(invalid)?;
                let scale = self.conversion_role("1 L", &first_unit.symbol, true, "invalid_physical_quantity")?;
                let first = Coordinate {
                    value: model_coordinates::bounded(&required.value * scale.value)?,
                    authored: required.authored && scale.authored,
                };
                let source = format!("({}) L", coordinate_literal(&required)?);
                let second = self.local_coordinate(&source, &c[5], &c[6])?;
                self.conversion_report(vec![
                    self.conversion_field("fuel needed", &first, &c[2], "L")?,
                    self.conversion_field("fuel needed", &second, &c[5], "L")?,
                ])
            })());
        }
        if let Some(c) = re!(r"(?i)^a [a-z]+ [a-z]+ contains (.+?) and is transmitted at (.+?), where (.+?); how many seconds does transmission take, ignoring overhead$").captures(input) {
            return Some((|| {
                let declarations = re!(r"(?i) and ").split(&c[3]).collect::<Vec<_>>();
                if declarations.len() != 2 { return Err(invalid()); }
                let (rate, period) = syntax::split_last(&c[2], &["/"]).ok_or_else(invalid)?;
                let size = self.local_coordinate(&c[1], "B", declarations[0])?;
                let rate = self.local_coordinate(rate, "bit", declarations[1])?;
                if !rate.value.is_positive() { return Err(Error("invalid_rate".into())); }
                let period = self.conversion_role(&format!("1 {period}"), "s", true, "invalid_duration")?;
                let bits_per_byte = self.conversion_role("1 B", "bit", true, "incompatible_units")?;
                let duration = Coordinate {
                    value: model_coordinates::bounded(size.value * bits_per_byte.value * period.value / rate.value)?,
                    authored: size.authored && bits_per_byte.authored && period.authored && rate.authored,
                };
                let expression = format!("(({}) s) in s", coordinate_literal(&duration)?);
                if expression.len() > 4096 { return Err(invalid()); }
                self.engine.quantity_value(&expression, "s", self.context)?;
                Ok(expression)
            })());
        }
        None
    }
}