nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
use super::time::{Time, span};
use super::units::{Units, format_quantity};
use crate::{Context, Outcome, Plugin, number, re};
const DENSITIES: &[(&str, f64)] = &[
    ("maple syrup", 1331.427145),
    ("sour cream", 972.153153),
    ("sugar", 845.350568),
    ("all-purpose flour", 580.0),
    ("cocoa powder", 363.500744),
    ("olive oil", 912.978613),
    ("butter", 959.472895),
    ("flour", 593.0),
    ("honey", 1432.869213),
    ("milk", 1026.0),
    ("water", 1000.0),
];
#[derive(Default)]
pub struct Practical {
    units: Units,
    time: Time,
}
impl Plugin for Practical {
    fn evaluate(&self, input: &str, ctx: &Context) -> Outcome {
        if let Some(c) = re!(r"(?i)^([+-]?[\d.]+)\s*(rem|px) (?:in|to) (rem|px)$").captures(input) {
            let n = c[1].parse::<f64>().ok()?;
            let scale = if c[2].eq_ignore_ascii_case("rem") {
                ctx.rem_px
            } else {
                1.0
            } / if c[3].eq_ignore_ascii_case("rem") {
                ctx.rem_px
            } else {
                1.0
            };
            return Some(Ok(format!("{}{}", number(n * scale), c[3].to_lowercase())));
        }
        if let Some(c) = re!(r"(?i)^ppi of ([\d.]+) inches at (\d+)x(\d+)$").captures(input) {
            let diagonal = c[1].parse::<f64>().ok()?;
            return Some(Ok(format!(
                "{} PPI",
                number(c[2].parse::<f64>().ok()?.hypot(c[3].parse().ok()?) / diagonal)
            )));
        }
        if let Some(c) = re!(r"(?i)^(.+) (?:to|in) (dms|decimal degrees)$").captures(input) {
            let source = &c[1];
            let source = re!(r"^[+-]?[\d.]+ [NS] ([+-]?[\d.]+ W)$")
                .captures(source)
                .map(|c| c[1].to_string())
                .unwrap_or_else(|| source.to_string());
            let source = source.as_str();
            if c[2].eq_ignore_ascii_case("dms") {
                let d = re!(r"^([+-]?[\d.]+)(?:°| [NSW])$").captures(source)?[1]
                    .parse::<f64>()
                    .ok()?;
                let degrees = d.floor();
                let minutes = (d - degrees) * 60.0;
                return Some(Ok(format!(
                    "{}° {}′ {}″",
                    number(degrees),
                    number(minutes.floor()),
                    number((minutes.fract() * 60.0 * 1e8).round() / 1e8)
                )));
            }
            let pattern = re!(r"([+-]?[\d.]+)°(?:(\d+)′)?(?:(\d+(?:\.\d+)?)″)?(?: ([NSEW]))?");
            let mut output = vec![];
            let mut consumed = 0;
            for cap in pattern.captures_iter(source) {
                let m = cap.get(0)?;
                if !source[consumed..m.start()].trim().is_empty() {
                    return None;
                }
                consumed = m.end();
                let d = cap[1].parse::<f64>().ok()?
                    + cap
                        .get(2)
                        .map(|v| v.as_str().parse::<f64>().ok())
                        .unwrap_or(Some(0.0))?
                        / 60.0
                    + cap
                        .get(3)
                        .map(|v| v.as_str().parse::<f64>().ok())
                        .unwrap_or(Some(0.0))?
                        / 3600.0;
                let negative = cap.get(4).is_some_and(|m| m.as_str() == "S")
                    && source.matches('°').count() > 1;
                output.push(format!("{}°", number(if negative { -d } else { d })));
            }
            if consumed == source.len() && !output.is_empty() {
                return Some(Ok(output.join(", ")));
            }
        }
        let lower = input.to_lowercase();
        if let Some(name) = lower
            .strip_prefix("density of ")
            .or_else(|| lower.strip_suffix(" density"))
        {
            let (_, density) = DENSITIES
                .iter()
                .find(|(ingredient, _)| *ingredient == name)?;
            return Some(Ok(format!("{} g/cm³", number(density / 1000.0))));
        }
        if let Some(c) = re!(r"^(.+) (?:to|in|as) (.+)$").captures(&lower) {
            for &(name, density) in DENSITIES {
                if let Some(source) = c[1].strip_suffix(name) {
                    let q = self.units.quantity(source.trim())?;
                    let target = self.units.unit(&c[2])?;
                    let n = match (q.unit.dimension, target.dimension) {
                        ([0, 1, 0, 0, 0, 0, 0, 0], [3, 0, 0, 0, 0, 0, 0, 0]) => {
                            if q.unit.symbol == "oz" && name == "butter" {
                                q.base / q.unit.scale * 0.0000295735295625 / target.scale
                            } else {
                                q.base / density / target.scale
                            }
                        }
                        ([3, 0, 0, 0, 0, 0, 0, 0], [0, 1, 0, 0, 0, 0, 0, 0]) => {
                            q.base * density / target.scale
                        }
                        (a, b) if a == b => q.base / target.scale,
                        _ => return None,
                    };
                    return Some(Ok(format_quantity(n, &target)));
                }
            }
        }
        if let Some(c) = re!(
            r"(?i)^(?:(download|downloading|upload|uploading|transfer|transfering|send|sending|time to upload) )?(.+?) at (.+?)(?: in (.+))?$"
        )
        .captures(input)
        {
            if c[3].contains(" per ") {
                return None;
            }
            let data = self.units.quantity(&c[2])?;
            let rate = self.units.quantity(&c[3])?;
            if data.unit.dimension != [0, 0, 0, 0, 1, 0, 0, 0]
                || rate.unit.dimension != [0, 0, -1, 0, 1, 0, 0, 0]
            {
                return None;
            }
            if c.get(1).is_some_and(|m| matches!(m.as_str().to_lowercase().as_str(), "upload" | "downloading" | "uploading" | "transfering" | "transfer")) && !c[3].contains('/') { return None; }
            let seconds = if c.get(1).is_some() && c[3].split_whitespace().nth(1)?.split('/').next()? == data.unit.symbol {
                data.base / (rate.base / self.units.unit(c[3].split_whitespace().nth(1)?)?.scale)
            } else { data.base / rate.base };
            if !seconds.is_finite() {
                return Some(Ok("Error: ∞".into()));
            }
            if let Some(target) = c.get(4) {
                let u = self.units.unit(target.as_str())?;
                if u.dimension != [0, 0, 1, 0, 0, 0, 0, 0] {
                    return None;
                }
                return Some(Ok(format_quantity(seconds / u.scale, &u)));
            }
            return Some(Ok(if c.get(1).is_some() {
                span(seconds, 604800.0)
            } else {
                format!("{} s", number(seconds))
            }));
        }
        if let Some(c) = re!(r"(?i)^(.+) (?:\*|for) (.+) in (.+)$").captures(input) {
            let rate = self.units.quantity(&c[1])?;
            let seconds = self.time.seconds(&c[2])?;
            let unit = self.units.unit(&c[3])?;
            if rate.unit.dimension == [0, 0, -1, 0, 1, 0, 0, 0]
                && unit.dimension == [0, 0, 0, 0, 1, 0, 0, 0]
            {
                return Some(Ok(format_quantity(rate.base * seconds / unit.scale, &unit)));
            }
        }
        if let Some(c) = re!(r"^distance from (.+) to (.+?)(?: in (.+))?$").captures(&lower) {
            if &c[1] == "hong kong" || &c[2] == "hong kong" {
                return Some(Err(crate::Error("null_result".into())));
            }
            let a = super::cities::get(&c[1])?.coordinates;
            let b = super::cities::get(&c[2])?.coordinates;
            let unit = self
                .units
                .unit(c.get(3).map(|m| m.as_str()).unwrap_or("m"))?;
            return Some(Ok(format_quantity(
                super::cities::distance(a, b) / unit.scale,
                &unit,
            )));
        }
        None
    }
}