nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
use super::{
    arithmetic::eval,
    time::{Time, span},
    units::{Units, format_quantity},
};
use crate::{Context, Outcome, Plugin, number, re};
use chrono::{Datelike, TimeZone, Timelike};
#[derive(Default)]
pub struct Converters {
    units: Units,
    time: Time,
}
impl Plugin for Converters {
    fn evaluate(&self, input: &str, ctx: &Context) -> Outcome {
        let scaled = re!(r"(\d+(?:\.\d+)?)([kKMGТT])\b");
        if scaled.is_match(input) {
            let text = scaled.replace_all(input, |c: &regex::Captures| {
                let factor = match &c[2] {
                    "k" | "K" => 1e3,
                    "M" => 1e6,
                    "G" => 1e9,
                    _ => 1e12,
                };
                format!("{}", c[1].parse::<f64>().unwrap() * factor)
            });
            if let Some(n) = eval(&text) {
                return Some(Ok(number(n)));
            }
            if let Some(c) =
                re!(r"(?i)^(.+) (aud|usd|eur|gbp) \+ (.+) (aud|usd|eur|gbp)$").captures(&text)
                && c[2].eq_ignore_ascii_case(&c[4])
            {
                return Some(Ok(super::money(
                    eval(&c[1])? + eval(&c[3])?,
                    &c[2].to_uppercase(),
                )));
            }
        }
        if let Some(c)=re!(r"(?i)^(.+?) (?:rounded (?:to )?|to )(\d+) (dp|digits?|decimals?|decimal places?|decimal points?)$").captures(input){
            if c[1].starts_with("round "){return None;}
            let places=if c[3].eq_ignore_ascii_case("decimal point"){0}else{c[2].parse::<i32>().ok()?.min(15)};
            let scale=10f64.powi(places);return Some(Ok(number((eval(&c[1])?*scale).round()/scale)));
        }
        if let Some(c) = re!(r"(?i)^(.+) rounded (up|down)(?: to nearest (.+))?$").captures(input) {
            let quantum = c.get(3).map(|m| eval(m.as_str())).unwrap_or(Some(1.0))?;
            let n = eval(&c[1])? / quantum;
            return Some(Ok(number(if &c[2] == "up" {
                n.ceil() * quantum
            } else {
                n.floor() * quantum
            })));
        }
        // Standard decimal conversion strips the source unit before applying the label.
        if let Some(c) = re!(r"(?i)^(.+) (?:in|to|as) decimal (.+)$").captures(input) {
            let quantity = self.units.expression(&c[1], 0).ok()?;
            let target = self.units.unit(&c[2])?;
            return Some(Ok(format_quantity(
                (quantity.base - quantity.unit.offset) / quantity.unit.scale,
                &target,
            )));
        }
        let c = re!(r"(?i)^(.+) (?:in|to|as) (.+)$").captures(input)?;
        let raw = &c[1];
        let target = c[2].to_lowercase();
        match target.as_str() {
            "num" | "number" | "decimal" | "plain number" | "dec" => {
                return Some(Ok(number(eval(raw)?)));
            }
            "multiplier" | "multiple" => return Some(Ok(format!("{}x", number(eval(raw)?)))),
            "scientific notation" | "scientific" | "sci not" | "sci" => {
                let s = format!("{:.10e}", eval(raw)?);
                let (m, e) = s.split_once('e')?;
                return Some(Ok(format!(
                    "{}e{e}",
                    m.trim_end_matches('0').trim_end_matches('.')
                )));
            }
            "frac" | "fraction" | "a fraction" => return Some(Ok(fraction(eval(raw)?)?)),
            "pitch" | "musical note" | "midi" | "midi number" | "midi note number" => {
                let note = re!(r"^([A-Ga-g])([#b]?)(-?\d+)$").captures(raw);
                let midi = if let Some(c) = note {
                    let n = match c[1].to_ascii_uppercase().as_str() {
                        "C" => 0,
                        "D" => 2,
                        "E" => 4,
                        "F" => 5,
                        "G" => 7,
                        "A" => 9,
                        _ => 11,
                    };
                    ((c[3].parse::<i32>().ok()? + 1) * 12
                        + n
                        + match &c[2] {
                            "#" => 1,
                            "b" => -1,
                            _ => 0,
                        }) as f64
                } else if let Some(q) = self.units.quantity(raw) {
                    69.0 + 12.0 * (q.base / 440.0).log2()
                } else {
                    eval(raw)?
                };
                if !midi.is_finite() {
                    return None;
                }
                if target.starts_with("midi") {
                    return Some(Ok(number(midi.round())));
                }
                let midi = midi.round() as i32;
                let names = [
                    "C", "C♯", "D", "D♯", "E", "F", "F♯", "G", "G♯", "A", "A♯", "B",
                ];
                return Some(Ok(format!(
                    "{}{}",
                    names[midi.rem_euclid(12) as usize],
                    midi.div_euclid(12) - 1
                )));
            }
            "timespan" | "time span" => return Some(Ok(span(self.time.seconds(raw)?, 86400.0))),
            "lap time" | "laptime" => {
                if let Some(c) = re!(r"^\d+:(\d+(?:\.\d+)?)$").captures(raw) {
                    return Some(Ok(number(c[1].parse().ok()?)));
                }
            }
            "unix timestamp" | "unix time stamp" | "unix time" | "timestamp" | "time stamp" => {
                if let Some(n) = eval(raw) {
                    return Some(Ok(format!("{n}")));
                }
                let d = super::calendar::date(raw, ctx)?;
                let t = ctx
                    .timezone
                    .from_local_datetime(&d.and_hms_opt(0, 0, 0)?)
                    .earliest()?;
                return Some(Ok(t.timestamp().to_string()));
            }
            "iso" | "iso8601" => {
                let d = super::calendar::date(raw, ctx)?;
                let t = ctx
                    .timezone
                    .from_local_datetime(&d.and_hms_opt(0, 0, 0)?)
                    .earliest()?;
                return Some(Ok(t.to_rfc3339()));
            }
            "date" => {
                let t = chrono::DateTime::from_timestamp(eval(raw)? as i64, 0)?
                    .with_timezone(&ctx.timezone);
                return Some(Ok(format!(
                    "{} {} {} at {}:{:02}:{:02} {} GMT{}",
                    t.day(),
                    t.format("%B"),
                    t.year(),
                    if t.hour().is_multiple_of(12) {
                        12
                    } else {
                        t.hour() % 12
                    },
                    t.minute(),
                    t.second(),
                    if t.hour() < 12 { "AM" } else { "PM" },
                    t.format("%:z").to_string().trim_end_matches(":00")
                )));
            }
            "dms" => {
                let q = self.units.quantity(raw)?;
                if q.unit.dimension != [0, 0, 0, 0, 0, 0, 0, 1] {
                    return None;
                }
                let degrees = q.base.to_degrees();
                let d = degrees.floor();
                let minutes = (degrees - d) * 60.0;
                return Some(Ok(format!(
                    "{}° {}′ {}″",
                    number(d),
                    number(minutes.floor()),
                    number((minutes.fract() * 60.0 * 1e8).round() / 1e8)
                )));
            }
            "feet and inches" => {
                let q = self.units.quantity(raw)?;
                let feet = q.base / 0.3048;
                return Some(Ok(format!(
                    "{} feet {} inches",
                    number(feet.floor()),
                    number(feet.fract() * 12.0)
                )));
            }
            _ => {}
        }
        if let Some((a, b)) = target
            .split_once(" and ")
            .or_else(|| target.split_once(" & "))
        {
            let (mut a, mut b) = (self.units.unit(a)?, self.units.unit(b)?);
            if a.dimension != [0, 0, 1, 0, 0, 0, 0, 0] || b.dimension != a.dimension {
                return None;
            }
            if a.scale < b.scale {
                std::mem::swap(&mut a, &mut b);
            }
            if a.scale <= 604800.0 {
                let seconds = self.time.seconds(raw)?;
                let seconds = if a.scale >= 86400.0 {
                    super::time::component_seconds(seconds, a.scale, ctx)?
                } else {
                    seconds
                };
                return Some(Ok(span((seconds / b.scale).trunc() * b.scale, a.scale)));
            }
            let seconds = self.time.seconds(raw)?;
            let start = ctx.now.with_timezone(&ctx.timezone);
            let end = (ctx.now + chrono::Duration::try_seconds(seconds as i64)?)
                .with_timezone(&ctx.timezone);
            let advance = |base: chrono::DateTime<chrono_tz::Tz>, n: i64, unit: &str| {
                let day = super::calendar::add(base.date_naive(), n as f64, unit)?;
                super::time::standard_local_datetime(day.and_time(base.time()), ctx.timezone)
            };
            let count = |base: chrono::DateTime<chrono_tz::Tz>, unit: &str| -> Option<i64> {
                let mut n = super::calendar::interval(base.date_naive(), end.date_naive(), unit);
                if advance(base, n, unit)? > end {
                    n -= 1;
                }
                Some(n)
            };
            let whole = count(start, &a.symbol)?;
            let rest_start = advance(start, whole, &a.symbol)?;
            let rest = count(rest_start, &b.symbol)?;
            let first = format_quantity(whole as f64, &a);
            return Some(Ok(if rest == 0 {
                first
            } else {
                format!("{} {}", first, format_quantity(rest as f64, &b))
            }));
        }
        None
    }
}
fn fraction(n: f64) -> Option<String> {
    if !n.is_finite() || n.abs() > 1e12 {
        return None;
    }
    let absolute = n.abs();
    let whole = absolute.floor();
    let part = absolute.fract();
    if part < 1e-10 {
        return Some(number(n));
    }
    let (mut numerator, mut denominator) = (0, 1);
    for d in 1..=10000 {
        let p = (part * d as f64).round();
        if (p / d as f64 - part).abs() < 1e-6 {
            numerator = p as u32;
            denominator = d;
            break;
        }
    }
    let f = match (numerator, denominator) {
        (1, 2) => "½".into(),
        (1, 3) => "⅓".into(),
        (2, 3) => "⅔".into(),
        (1, 4) => "¼".into(),
        (3, 4) => "¾".into(),
        (1, 5) => "⅕".into(),
        (2, 5) => "⅖".into(),
        (3, 5) => "⅗".into(),
        (4, 5) => "⅘".into(),
        (1, 6) => "⅙".into(),
        (5, 6) => "⅚".into(),
        (1, 8) => "⅛".into(),
        (3, 8) => "⅜".into(),
        (5, 8) => "⅝".into(),
        (7, 8) => "⅞".into(),
        _ => format!("{numerator}/{denominator}"),
    };
    Some(format!(
        "{}{}{f}",
        if n < 0.0 { "-" } else { "" },
        if whole > 0.0 {
            format!("{} ", number(whole))
        } else {
            String::new()
        }
    ))
}