nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
use super::{
    arithmetic::eval,
    time::{Time, span},
};
use crate::{Context, Error, Outcome, Plugin, number, re};
use std::hash::{BuildHasher, RandomState};
#[derive(Default)]
pub struct Phrases {
    time: Time,
}
fn n(s: &str) -> Option<f64> {
    s.trim().replace(',', "").parse().ok().or_else(|| eval(s))
}
fn out(value: f64) -> Outcome {
    Some(if value.is_finite() {
        Ok(number(value))
    } else {
        Err(Error("internal_error".into()))
    })
}
impl Plugin for Phrases {
    fn evaluate(&self, input: &str, _: &Context) -> Outcome {
        let s = input.to_lowercase().replace('−', "-");
        if let Some(c) = re!(r"^(?:square|squared) root of (.+)$").captures(&s) {
            return Some(
                super::decimal::root(n(&c[1])?, 2.0)
                    .map(number)
                    .ok_or_else(|| Error("internal_error".into())),
            );
        }
        if let Some(c) = re!(r"^\((.+) to (.+)\) as (?:a )?multiplier$").captures(&s) {
            return Some(Ok(format!("{}x", number(n(&c[2])? - n(&c[1])?))));
        }
        if let Some(c) = re!(r"^(?:([\d.]+) root|root ([\d.]+)) of (.+)$").captures(&s) {
            let power = n(c.get(1).or_else(|| c.get(2))?.as_str())?;
            let value = n(&c[3])?;
            return Some(
                super::decimal::root(value, power)
                    .map(|n| {
                        if n.abs() >= 1e12 {
                            format!("{n:.10e}")
                        } else {
                            number(n)
                        }
                    })
                    .ok_or_else(|| Error("internal_error".into())),
            );
        }
        if let Some(c) = re!(r"^logarithm (?:base )?(.+) of (.+)$").captures(&s) {
            return out(n(&c[2])?.log(n(&c[1])?));
        }
        if let Some(c) = re!(r"^(.+) to (.+) (?:is what|as(?: a)?) multiplier$").captures(&s) {
            let a = n(&c[1])?;
            return Some(if a == 0.0 {
                Err(Error("null_result".into()))
            } else {
                Ok(format!("{}x", number(n(&c[2])? / a)))
            });
        }
        if let Some(c) = re!(r"^logarithm (?:of )?(.+?) (?:to |with )?base (.+)$").captures(&s) {
            return out(n(&c[1])?.log(n(&c[2])?));
        }
        if let Some(c) =
            re!(r"^(.+) is (.+) to (?:the power of what|what power|the what)$").captures(&s)
        {
            return out(n(&c[1])?.log(n(&c[2])?));
        }
        if let Some(c) =
            re!(r"^(.+) (?:with what (?:exponent|power)|to what (?:power|exponent)) is (.+)$")
                .captures(&s)
        {
            return out(n(&c[2])?.log(n(&c[1])?));
        }
        if let Some(c) = re!(r"^(.+?) to (.+?) (?:is|as) (what|.+?) to (what|.+)$").captures(&s) {
            return if &c[3] == "what" {
                out(n(&c[1])? / n(&c[2])? * n(&c[4])?)
            } else if &c[4] == "what" {
                out(n(&c[2])? / n(&c[1])? * n(&c[3])?)
            } else {
                None
            };
        }
        if let Some(c) =
            re!(r"^(.+) (?:as (?:a )?|is what )multiplier (of|on|off) (.+)$").captures(&s)
        {
            let ratio = n(&c[1])? / n(&c[3])?;
            let v = match &c[2] {
                "on" => ratio - 1.0,
                "off" => 1.0 - ratio,
                _ => ratio,
            };
            return Some(Ok(format!("{}x", number(v))));
        }
        if let Some(c) =
            re!(r"^scrub(?:ber)? (.+) (?:from|between) (.+) (?:to|and) (.+)$").captures(&s)
        {
            n(&c[2])?;
            n(&c[3])?;
            return out(n(&c[1])?);
        }
        if re!(r#"^count (?:of )?(?:"[^"]*"|[+-]?[\d.]+)$"#).is_match(&s) {
            return out(1.0);
        }
        if let Some(c) =
            re!(r"^random (?:number )?(?:between|from) ([+-]?[\d.]+) (?:and|to) ([+-]?[\d.]+)$")
                .captures(&s)
        {
            let (a, b) = (n(&c[1])?, n(&c[2])?);
            if b < a {
                return Some(Err(Error("internal_error".into())));
            }
            let random = (RandomState::new().hash_one(0u64) >> 11) as f64 / (1u64 << 53) as f64;
            return out(if b - a <= 1.0 {
                a + random * (b - a)
            } else {
                a.round() + (random * (b.round() - a.round() + 1.0)).floor()
            });
        }
        if let Some(c) =
            re!(r"^(.+) after (.+) at ([+-]?[\d.]+)% (growth |decay )?every (.+)$").captures(&s)
        {
            let total = self.time.seconds(&c[2])?;
            let period = self
                .time
                .seconds(&format!("1 {}", &c[5]))
                .or_else(|| self.time.seconds(&c[5]))?;
            let rate = n(&c[3])? / 100.0
                * if c.get(4).is_some_and(|m| m.as_str() == "decay ") {
                    -1.0
                } else {
                    1.0
                };
            return out(n(&c[1])? * (1.0 + rate).powf(total / period));
        }
        if let Some(c) = re!(
            r"^time from (.+) to (.+) at ([+-]?[\d.]+)(%)? (?:growth |decay )?(?:every|per) (.+)$"
        )
        .captures(&s)
        {
            let period = self
                .time
                .seconds(&format!("1 {}", &c[5]))
                .or_else(|| self.time.seconds(&c[5]))?;
            let (a, b, r) = (n(&c[1])?, n(&c[2])?, n(&c[3])?);
            if c.get(4).is_some() {
                let raw = &c[5];
                let units = super::units::Units::default();
                let q = units
                    .quantity(raw)
                    .or_else(|| units.quantity(&format!("1 {raw}")))?;
                let rate = r.abs() / 100.0 * if b < a { -1.0 } else { 1.0 };
                let count = if a == 0.0 || a == b {
                    0.0
                } else {
                    (b / a).ln() / (1.0 + rate).ln()
                };
                return Some(Ok(super::units::format_quantity(
                    count * q.base / q.unit.scale,
                    &q.unit,
                )));
            }
            let time = period * (b - a) / r;
            return Some(Ok(span(time, 604800.0)));
        }
        if let Some(c) =
            re!(r"^(?:growth|decay) every (.+) from (.+) to (.+) over (.+)$").captures(&s)
        {
            let period = self
                .time
                .seconds(&format!("1 {}", &c[1]))
                .or_else(|| self.time.seconds(&c[1]))?;
            let total = self.time.seconds(&c[4])?;
            let units = super::units::Units::default();
            let total_quantity = units.quantity(&c[4])?;
            let base =
                super::decimal::root(n(&c[3])? / n(&c[2])?, total / total_quantity.unit.scale);
            let root = base.map(|base| {
                base.powf(super::decimal::exponent(period / total_quantity.unit.scale))
            });
            let value = (root
                .filter(|n| n.is_finite() && n.abs() < 1e165)
                .unwrap_or(1.0)
                - 1.0)
                * 100.0;
            let display = if value.abs() >= 1e12 {
                let raw = format!("{value:.10}");
                let raw = raw.trim_end_matches('0').trim_end_matches('.');
                let integer_len = raw.find('.').unwrap_or(raw.len());
                let mut text = String::new();
                for (i, ch) in raw.chars().enumerate() {
                    if i > 0 && i < integer_len && (integer_len - i).is_multiple_of(3) && ch != '-'
                    {
                        text.push(',');
                    }
                    text.push(ch);
                }
                text
            } else {
                number(value)
            };
            return Some(Ok(format!("{display}%")));
        }
        None
    }
}