nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
//! Complete inverse shape and sequential vector goals, using the shared typed formulas.
use super::{Geometry, cross_components, norm, syntax};
use crate::{Context, Error, re};
use num_rational::BigRational;
use num_traits::{Signed, ToPrimitive, Zero};

impl Geometry {
    fn positive_shape_role(
        &self,
        input: &str,
        reference: &str,
        context: &Context,
    ) -> Result<(), Error> {
        let coordinate =
            super::super::model_coordinates::read(input, reference, &self.engine, context)?;
        if !coordinate.value.is_positive() {
            return Err(Error("invalid_geometry".into()));
        }
        Ok(())
    }

    fn triangle_root(&self, squared: BigRational, context: &Context) -> Result<BigRational, Error> {
        super::super::model_coordinates::computed_root(squared, |expression| {
            self.engine.quantity_value(expression, "1", context)
        })
    }

    fn computed_shape(&self, coordinate: &BigRational, unit: &str) -> Result<String, Error> {
        let value = coordinate
            .to_f64()
            .filter(|value| value.is_finite())
            .ok_or_else(|| Error("numeric_overflow".into()))?;
        if value == 0.0 && !coordinate.is_zero() {
            return Err(Error("numeric_underflow".into()));
        }
        // The root used the typed binary64 kernel; emitting real retains that provenance.
        Ok(format!("(real({value:e}) {unit})"))
    }

    fn compatible_vectors(
        &self,
        a: &[String],
        b: &[String],
        context: &Context,
    ) -> Result<(), Error> {
        if a.len() != b.len() {
            return Err(Error("invalid_vector".into()));
        }
        self.engine.quantity_order(&a[0], &b[0], context)?;
        Ok(())
    }

    fn vector_list(&self, input: &str, context: &Context) -> Result<Vec<Vec<String>>, Error> {
        let invalid = || Error("invalid_vector".into());
        let groups = syntax::groups(input).ok_or_else(invalid)?;
        if !(2..=16).contains(&groups.len()) {
            return Err(invalid());
        }
        let mut cursor = 0;
        let mut vectors = Vec::new();
        for group in groups {
            let opening = group.start - 1;
            let delimiter = input[cursor..opening].trim().to_ascii_lowercase();
            if (cursor == 0 && !delimiter.is_empty())
                || (cursor != 0 && !matches!(delimiter.as_str(), "," | ", and" | "and"))
            {
                return Err(invalid());
            }
            vectors.push(self.vector(&input[opening..=group.end], context)?);
            cursor = group.end + 1;
        }
        if !input[cursor..].trim().is_empty() {
            return Err(invalid());
        }
        for vector in &vectors[1..] {
            self.compatible_vectors(&vectors[0], vector, context)?;
        }
        Ok(vectors)
    }

    pub(super) fn lower_supplied(
        &self,
        input: &str,
        context: &Context,
    ) -> Result<Option<String>, Error> {
        if let Some(c) = re!(r"(?i)^a cylindrical [a-z]+ has an internal radius of (.+?) and an internal height of (.+?); what volume does it hold in (.+?), using (?:pi|Ï€)\s*=\s*(.+?) and (.+?) per (.+)$").captures(input) {
            // This is an alias of the existing supplied cylinder/equivalence
            // operation. Its factor, target and every role remain validated there.
            let clause = format!(
                "Find the volume in {} of a cylinder with radius {} and height {}; use pi = {} and {} = 1 {}",
                &c[3], &c[1], &c[2], &c[4], &c[5], &c[6],
            );
            if clause.len() > 4096 {
                return Err(Error("expression_too_complex".into()));
            }
            return self.lower(&clause, context);
        }
        if let Some(c) = re!(r"(?i)^a cylindrical pipe has outer radius (.+?), inner radius (.+?), and length (.+?); what volume of metal does it contain in (.+?), using (?:pi|Ï€)\s*=\s*(.+)$").captures(input) {
            let outer = super::super::model_coordinates::read(&c[1], "m", &self.engine, context)?;
            let inner = super::super::model_coordinates::read(&c[2], "m", &self.engine, context)?;
            let length = super::super::model_coordinates::read(&c[3], "m", &self.engine, context)?;
            if !inner.value.is_positive() || outer.value <= inner.value || !length.value.is_positive() {
                return Err(Error("invalid_geometry".into()));
            }
            let pi = self.constant(&c[5], context)?;
            let pi_coordinate = super::super::model_coordinates::read(&c[5], "1", &self.engine, context)?;
            let formula = if outer.authored && inner.authored && length.authored && pi_coordinate.authored {
                // The radius sum and the individual squares may exceed binary64
                // even when the complete authored volume is finite.
                let annulus = (&outer.value - &inner.value) * (&outer.value + &inner.value);
                let volume = super::super::model_coordinates::bounded(
                    annulus * &length.value * &pi_coordinate.value,
                )?;
                format!("(rational({},{}) m³)", volume.numer(), volume.denom())
            } else {
                // Computed roles retain their typed binary64 provenance.
                format!("{pi}* (({})-({})) * (({})+({})) * ({})", &c[1], &c[2], &c[1], &c[2], &c[3])
            };
            self.engine.quantity_value(&formula, "m³", context)?;
            return self.output(formula, &c[4], "m³", context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a rectangle has area (.+?) and width (.+?); (?:find|calculate) its length and perimeter$").captures(input) {
            self.positive_shape_role(&c[1], "m²", context)?;
            self.positive_shape_role(&c[2], "m", context)?;
            let target = self.length_target(&c[2]);
            let length = format!("({})/({})", &c[1], &c[2]);
            let perimeter = format!("2*(({length})+({}))", &c[2]);
            return self.summary(&[("length", &target, length), ("perimeter", &target, perimeter)], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a right triangle has hypotenuse (.+?) and one leg (.+?); (?:find|calculate) the other leg and its area$").captures(input) {
            let hypotenuse = super::super::model_coordinates::read(&c[1], "m", &self.engine, context)?;
            let leg = super::super::model_coordinates::read(&c[2], "m", &self.engine, context)?;
            if !leg.value.is_positive() || hypotenuse.value <= leg.value {
                return Err(Error("invalid_geometry".into()));
            }
            let target = self.length_target(&c[1]);
            let squared = (&hypotenuse.value - &leg.value) * (&hypotenuse.value + &leg.value);
            let other = self.triangle_root(squared, context)?;
            let area = super::super::model_coordinates::bounded(
                &leg.value * &other / BigRational::from_integer(2.into()),
            )?;
            return self.summary(&[("other leg", &target, self.computed_shape(&other, "m")?),
                ("area", &format!("{target}²"), self.computed_shape(&area, "m²")?)], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a circular track has radius (.+?) and a (.+?) wide outer lane; using (?:pi|Ï€)\s*=\s*(.+?), (?:find|calculate) the outer lane's area$").captures(input) {
            let radius = self.length(&c[1], context)?.0;
            let width = self.length(&c[2], context)?.0;
            let pi = self.constant(&c[3], context)?;
            let target = format!("{}²", self.length_target(&c[1]));
            // π((r+w)²-r²) = πw(2r+w), retaining thin-lane differences.
            return self.output(format!("{pi}*{width}*(2*{radius}+{width})"), &target, "m²", context).map(Some);
        }
        if let Some(c) =
            re!(r"(?i)^for a cube of side (.+?), report surface area and volume$").captures(input)
        {
            let side = self.length(&c[1], context)?.0;
            let target = self.length_target(&c[1]);
            return self
                .summary(
                    &[
                        (
                            "surface area",
                            &format!("{target}²"),
                            format!("6*square({side})"),
                        ),
                        (
                            "volume",
                            &format!("{target}³"),
                            format!("square({side})*{side}"),
                        ),
                    ],
                    context,
                )
                .map(Some);
        }
        if let Some(c) = re!(r"(?i)^add vectors (.+); report the component sum and its magnitude$")
            .captures(input)
        {
            let vectors = self.vector_list(&c[1], context)?;
            let components = (0..vectors[0].len())
                .map(|index| {
                    format!(
                        "sum({})",
                        vectors
                            .iter()
                            .map(|vector| vector[index].as_str())
                            .collect::<Vec<_>>()
                            .join(",")
                    )
                })
                .collect::<Vec<_>>();
            return self
                .summary(
                    &[
                        ("components", "", format!("({})", components.join(","))),
                        ("magnitude", "", norm(&components)),
                    ],
                    context,
                )
                .map(Some);
        }
        if let Some(c) = re!(r"(?i)^subtract (\(.+\)) from (\(.+\)); give the resulting vector and its dot product with (\(.+\))$").captures(input) {
            let subtrahend = self.vector(&c[1], context)?;
            let minuend = self.vector(&c[2], context)?;
            let operand = self.vector(&c[3], context)?;
            self.compatible_vectors(&minuend, &subtrahend, context)?;
            if minuend.len() != operand.len() {
                return Err(Error("invalid_vector".into()));
            }
            let components = minuend.iter().zip(&subtrahend).map(|(a,b)| format!("({a}-{b})")).collect::<Vec<_>>();
            let dot = self.product(&components, &operand, false, false, None)?;
            return self.summary(&[("components", "", format!("({})", components.join(","))),
                ("dot product", "", dot)], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^for ([a-z])\s*=\s*(\(.+\)) and ([a-z])\s*=\s*(\(.+\)), (?:calculate|find) ([a-z]) dot ([a-z]) and ([a-z]) cross ([a-z])$").captures(input) {
            if c[1].eq_ignore_ascii_case(&c[3]) {
                return Err(Error("invalid_vector".into()));
            }
            let a = self.vector(&c[2], context)?;
            let b = self.vector(&c[4], context)?;
            let select = |name: &str| {
                if name.eq_ignore_ascii_case(&c[1]) { Ok(a.as_slice()) }
                else if name.eq_ignore_ascii_case(&c[3]) { Ok(b.as_slice()) }
                else { Err(Error("invalid_vector".into())) }
            };
            let dot = self.product(select(&c[5])?, select(&c[6])?, false, false, None)?;
            let cross = cross_components(select(&c[7])?, select(&c[8])?)?;
            return self.summary(&[("dot product", "", dot),
                ("cross product", "", format!("({})", cross.join(",")))], context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a displacement is (\(.+\)) (.+?); (?:find|calculate) its magnitude, direction angle measured counterclockwise from positive x in degrees, and unit vector$").captures(input) {
            self.target(&c[2])?;
            self.engine.quantity_value(&format!("1 {}", &c[2]), "m", context)?;
            let scalars = self.vector(&c[1], context)?;
            if scalars.len() != 2 {
                return Err(Error("invalid_vector".into()));
            }
            let x = super::super::model_coordinates::read(&scalars[0], "1", &self.engine, context)?;
            let y = super::super::model_coordinates::read(&scalars[1], "1", &self.engine, context)?;
            if x.value.is_zero() && y.value.is_zero() {
                return Err(Error("division_by_zero".into()));
            }
            let x = self.engine.quantity_value(&scalars[0], "1", context)?;
            let y = self.engine.quantity_value(&scalars[1], "1", context)?;
            let mut degrees = y.atan2(x).to_degrees();
            if degrees < 0.0 { degrees += 360.0; }
            let components = scalars.iter().map(|part| format!("({part}*(1 {}))", &c[2])).collect::<Vec<_>>();
            let magnitude = norm(&components);
            let direction = components.iter().map(|part| format!("{part}/({magnitude})")).collect::<Vec<_>>();
            let target = self.length_target(&format!("1 {}", &c[2]));
            return self.summary(&[("magnitude", &target, magnitude),
                ("direction angle", "degrees", format!("(real({degrees:e}) degrees)")),
                ("unit vector", "", format!("({})", direction.join(",")))], context).map(Some);
        }
        Ok(None)
    }
}