nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
//! Supplied geometric roles lower to ordinary typed formulas.
//! Vector components are homogeneous within a vector; products multiply their dimensions.
mod reports;
mod supplied;

use super::{compositions::Compositions, syntax};
use crate::{Context, Error, ModelPosition, Outcome, Plugin, re};

#[derive(Default)]
pub struct Geometry {
    engine: Compositions,
}

impl Plugin for Geometry {
    fn rewrite_model(&self, input: &str, context: &Context, _: ModelPosition) -> Outcome {
        self.lower(input, context).transpose()
    }
    fn rewrite(&self, input: &str, context: &Context) -> Outcome {
        syntax::rewrite_groups(input, |part| self.lower(part, context).transpose())
    }

    fn evaluate(&self, input: &str, context: &Context) -> Outcome {
        let input = syntax::ungroup(input);
        if let Some(result) = self.evaluate_report(input, context) {
            return Some(result);
        }
        let inner = input.strip_prefix("geometry_vector(")?.strip_suffix(')')?;
        Some((|| {
            let components = inner.split(';').collect::<Vec<_>>();
            if components.len() != 3 {
                return Err(Error("invalid_vector".into()));
            }
            let values = components
                .into_iter()
                .map(|component| {
                    self.engine
                        .evaluate(component.trim(), context)
                        .ok_or_else(|| Error("invalid_expression".into()))?
                })
                .collect::<Result<Vec<_>, _>>()?;
            Ok(format!("({})", values.join(", ")))
        })())
    }
}

impl Geometry {
    fn lower(&self, input: &str, context: &Context) -> Result<Option<String>, Error> {
        let input = input.trim().trim_end_matches(['.', '?']);
        if let Some(result) = self.lower_report(input, context)? {
            return Ok(Some(result));
        }
        if let Some(c) = re!(r"(?i)^for a triangle with sides (.+?), (.+?), and (.+?), (?:find|calculate) its area in (.+)$").captures(input) {
            let mut sides = Vec::new();
            for role in [1, 2, 3] {
                let (side, length) = self.length(&c[role], context)?;
                sides.push((length, side));
            }
            sides.sort_by(|a, b| a.0.total_cmp(&b.0));
            // Strict inequality rejects zero and degenerate triangles. Subtraction
            // avoids overflowing the sum of two individually finite lengths.
            if sides[0].0 == 0.0 || sides[2].0 - sides[1].0 >= sides[0].0 {
                return Err(Error("invalid_geometry".into()));
            }
            let (a, b, smallest) = (&sides[2].1, &sides[1].1, &sides[0].1);
            let difference = format!("(({a} - {b}) / {smallest})");
            let middle = format!("({b} / {a})");
            let small = format!("({smallest} / {a})");
            // Factored Kahan/Heron avoids semiperimeter cancellation and quartic
            // products. Scale the largest side first by a dimensionless factor
            // at most 1/2, preserving finite and subnormal final areas.
            let factors = format!(
                "(1 + {middle} + {small}) * (1 - {difference}) * (1 + {difference}) * (1 + {middle} - {small})"
            );
            let formula = format!("({a} * (sqrt({factors}) / 4)) * {smallest}");
            return self.output(formula, &c[4], "m²", context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^(?:find|calculate) the volume in (.+?) of a cylinder with radius (.+?) and height (.+?); use (?:Ï€|pi)\s*=\s*(.+?)(?: and (.+?)\s*=\s*(.+))?$").captures(input) {
            let radius = self.length(&c[2], context)?.0;
            let height = self.length(&c[3], context)?.0;
            let pi = self.constant(&c[4], context)?;
            if let (Some(left), Some(right)) = (c.get(5), c.get(6)) {
                self.equivalence(left.as_str(), right.as_str(), context)?;
            }
            return self
                .output(format!("{pi} * square({radius}) * {height}"), &c[1], "m³", context)
                .map(Some);
        }
        if let Some(c) = re!(r"(?i)^a rectangular box is (.+?) long, (.+?) wide, and (.+?) high\. (?:give|find|calculate) its volume in (.+?)(?: using (.+?)\s*=\s*(.+))?$").captures(input) {
            let a = self.length(&c[1], context)?.0;
            let b = self.length(&c[2], context)?.0;
            let h = self.length(&c[3], context)?.0;
            if let (Some(left), Some(right)) = (c.get(5), c.get(6)) {
                self.equivalence(left.as_str(), right.as_str(), context)?;
            }
            return self.output(format!("{a} * {b} * {h}"), &c[4], "m³", context).map(Some);
        }
        if let Some(c) = re!(r"(?i)^a regular hexagon has side length (.+?)\. (?:find|calculate) its area in (.+?); use (?:√3|sqrt\(3\))\s*=\s*(.+)$").captures(input) {
            let side = self.length(&c[1], context)?.0;
            let root_three = self.constant(&c[3], context)?;
            return self
                .output(format!("1.5 * {root_three} * square({side})"), &c[2], "m²", context)
                .map(Some);
        }
        if let Some(c) = re!(r"(?i)^a rectangular plot is (.+?) by (.+?)\. a (.+?) wide path runs inside along all four edges; (?:find|calculate) the remaining area in (.+)$").captures(input) {
            let (a, width) = self.length(&c[1], context)?;
            let (b, height) = self.length(&c[2], context)?;
            let (p, path) = self.length(&c[3], context)?;
            if path > width / 2.0 || path > height / 2.0 {
                return Err(Error("invalid_geometry".into()));
            }
            return self
                .output(format!("({a} - 2 * {p}) * ({b} - 2 * {p})"), &c[4], "m²", context)
                .map(Some);
        }
        if let Some(c) = re!(
            r"(?i)^(?:find|calculate) the total surface area of a cube with side (.+?), in (.+)$"
        )
        .captures(input)
        {
            let side = self.length(&c[1], context)?.0;
            return self
                .output(format!("6 * square({side})"), &c[2], "m²", context)
                .map(Some);
        }
        if let Some(c) = re!(r"(?i)^(?:find|calculate) the area of a circle with radius (.+?)(?: in (.+?))? using (?:Ï€|pi)\s*=\s*(.+)$").captures(input) {
            let radius = self.length(&c[1], context)?.0;
            let pi = self.constant(&c[3], context)?;
            let target = c.get(2).map_or("m²", |value| value.as_str());
            return self.output(format!("{pi} * square({radius})"), target, "m²", context).map(Some);
        }

        if let Some(c) = re!(r"(?i)^(?:find|calculate) the (?:euclidean )?norm of vector (\(.+\))(?:, rounded to (\d+) decimal places| in (.+))?$").captures(input) {
            let components = self.vector(&c[1], context)?;
            let mut formula = norm(&components);
            if let Some(places) = c.get(2) {
                let precision = places.as_str().parse::<u8>().ok().filter(|p| *p <= 15)
                    .ok_or_else(|| Error("invalid_rounding_precision".into()))?;
                formula = format!("round({formula}, {precision})");
            }
            return self.vector_output(formula, c.get(3).map(|m| m.as_str())).map(Some);
        }
        if let Some(c) = re!(r"(?i)^(?:calculate|find) the (dot|cross) product (\(.+\))\s*([·×])\s*(\(.+\))(?: in (.+))?$").captures(input) {
            let cross = c[1].eq_ignore_ascii_case("cross");
            if cross != (&c[3] == "×") {
                return Err(Error("invalid_vector".into()));
            }
            let a = self.vector(&c[2], context)?;
            let b = self.vector(&c[4], context)?;
            return self
                .product(&a, &b, cross, false, c.get(5).map(|m| m.as_str()))
                .map(Some);
        }
        if let Some(c) = re!(r"(?i)^for vectors ([a-z])\s*=\s*(\(.+\)) and ([a-z])\s*=\s*(\(.+\)), (?:calculate|find) (\|?)([a-z])\s*([·×])\s*([a-z])(\|?)(?: in (.+))?$").captures(input) {
            if c[1].eq_ignore_ascii_case(&c[3]) || c[5] != c[9] {
                return Err(Error("invalid_vector".into()));
            }
            // Both declarations are consumed roles, even when the requested
            // operation selects one vector twice.
            let declared_a = self.vector(&c[2], context)?;
            let declared_b = self.vector(&c[4], context)?;
            let variable = |name: &str| {
                if name.eq_ignore_ascii_case(&c[1]) {
                    Ok(declared_a.as_slice())
                } else if name.eq_ignore_ascii_case(&c[3]) {
                    Ok(declared_b.as_slice())
                } else {
                    Err(Error("invalid_vector".into()))
                }
            };
            let a = variable(&c[6])?;
            let b = variable(&c[8])?;
            return self.product(a, b, &c[7] == "×", !c[5].is_empty(), c.get(10).map(|m| m.as_str())).map(Some);
        }
        Ok(None)
    }

    fn length(&self, input: &str, context: &Context) -> Result<(String, f64), Error> {
        let value = self.engine.quantity_value(input, "m", context)?;
        if value < 0.0 {
            return Err(Error("invalid_physical_value".into()));
        }
        Ok((format!("({input})"), value))
    }

    fn constant(&self, input: &str, context: &Context) -> Result<String, Error> {
        if self.engine.quantity_value(input, "1", context)? <= 0.0 {
            return Err(Error("invalid_physical_value".into()));
        }
        Ok(format!("({input})"))
    }

    fn equivalence(&self, left: &str, right: &str, context: &Context) -> Result<(), Error> {
        self.engine.quantity_value(left, "m³", context)?;
        self.engine.quantity_value(right, "m³", context)?;
        if self.engine.quantity_order(left, right, context)? != std::cmp::Ordering::Equal {
            return Err(Error("invalid_geometry".into()));
        }
        Ok(())
    }

    fn output(
        &self,
        formula: String,
        target: &str,
        reference: &str,
        context: &Context,
    ) -> Result<String, Error> {
        self.target(target)?;
        self.engine
            .quantity_value(&format!("1 {target}"), reference, context)?;
        Ok(format!("({formula}) in {target}"))
    }

    fn target(&self, input: &str) -> Result<(), Error> {
        if super::compound_units::factors(input, |unit| self.engine.units.unit(unit).is_some())
            .is_none()
        {
            return Err(Error("invalid_expression".into()));
        }
        Ok(())
    }

    fn vector_output(&self, formula: String, target: Option<&str>) -> Result<String, Error> {
        if let Some(target) = target {
            self.target(target)?;
            Ok(format!("({formula}) in {target}"))
        } else {
            Ok(format!("({formula})"))
        }
    }

    fn vector(&self, input: &str, context: &Context) -> Result<Vec<String>, Error> {
        let invalid = || Error("invalid_vector".into());
        let inner = input
            .trim()
            .strip_prefix('(')
            .and_then(|s| s.strip_suffix(')'))
            .ok_or_else(invalid)?;
        syntax::groups(inner).ok_or_else(invalid)?;
        let mut rest = inner;
        let mut components = Vec::new();
        // Vector commas delimit coordinates. Commas inside an explicit component
        // group/function retain their original scope and arithmetic grammar.
        while let Some((left, right)) = syntax::split_last(rest, &[","]) {
            components.push(right.trim());
            rest = left;
            if components.len() >= 16 {
                return Err(invalid());
            }
        }
        components.push(rest.trim());
        components.reverse();
        if components.iter().any(|part| part.is_empty()) {
            return Err(invalid());
        }
        for component in &components {
            self.engine
                .quantity_order(components[0], component, context)?;
        }
        Ok(components
            .into_iter()
            .map(|part| format!("({part})"))
            .collect())
    }

    fn product(
        &self,
        a: &[String],
        b: &[String],
        cross: bool,
        magnitude: bool,
        target: Option<&str>,
    ) -> Result<String, Error> {
        if a.len() != b.len() || (cross && a.len() != 3) {
            return Err(Error("invalid_vector".into()));
        }
        if !cross {
            let terms = a
                .iter()
                .zip(b)
                .map(|(a, b)| format!("{a} * {b}"))
                .collect::<Vec<_>>();
            let formula = format!("sum({})", terms.join(","));
            return self.vector_output(
                if magnitude {
                    format!("abs({formula})")
                } else {
                    formula
                },
                target,
            );
        }
        let components = cross_components(a, b)?;
        if magnitude {
            return self.vector_output(norm(&components), target);
        }
        let components = components
            .into_iter()
            .map(|component| self.vector_output(component, target))
            .collect::<Result<Vec<_>, _>>()?;
        Ok(format!("geometry_vector({})", components.join(";")))
    }
}

fn norm(components: &[String]) -> String {
    let squares = components
        .iter()
        .map(|part| format!("square({part})"))
        .collect::<Vec<_>>();
    format!("sqrt(sum({}))", squares.join(","))
}

fn cross_components(a: &[String], b: &[String]) -> Result<[String; 3], Error> {
    if a.len() != 3 || b.len() != 3 {
        return Err(Error("invalid_vector".into()));
    }
    Ok([(1, 2), (2, 0), (0, 1)]
        .map(|(i, j)| format!("({} * {} - {} * {})", a[i], b[j], a[j], b[i])))
}