nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
//! Rate word problems lower to the existing dimensional calculator.
use crate::{plugins::units::Units, re};

pub(super) fn rewrite(s: &str, _units: &Units) -> String {
    if let Some(c) = re!(
        r"^(?:exchange|convert) ([a-z]{3}) (.+?) (?:into|to) ([a-z]{3}) (?:at|using) (.+) = (.+)$"
    )
    .captures(s)
        && !s.contains(" and ")
    {
        return format!(
            "({} {}) / ({}) * ({}) in {}",
            &c[2], &c[1], &c[4], &c[5], &c[3]
        );
    }
    if let Some(c) =
        re!(r"^convert ([a-z]{3}) (.+?) to ([a-z]{3}) using (.+) = (.+) and (.+) = (.+)$")
            .captures(s)
    {
        return format!(
            "({} {}) / ({}) * ({}) / ({}) * ({}) in {}",
            &c[2], &c[1], &c[5], &c[4], &c[6], &c[7], &c[3]
        );
    }
    if let Some(c) = re!(r"^how many ([a-z]{3}) is ([a-z]{3}) (.+?) if (.+) = (.+)$").captures(s) {
        return format!(
            "({} {}) / ({}) * ({}) in {}",
            &c[3], &c[2], &c[5], &c[4], &c[1]
        );
    }
    if let Some(c) = re!(r"^a ([a-z]{3}) (.+?) item is paid in ([a-z]{3}); use (.+) = (.+)[.] what is the [a-z]{3} amount$").captures(s) {
        return format!("({} {}) / ({}) * ({}) in {}", &c[2], &c[1], &c[5], &c[4], &c[3]);
    }
    if let Some(c) =
        re!(r"^at (.+?) for (.+?), what is the charge in ([a-z]{3}) using (.+) = (.+)$").captures(s)
    {
        return format!(
            "({}) / ({}) * ({}) in {}",
            accumulate(&c[1], &c[2]),
            &c[4],
            &c[5],
            &c[3]
        );
    }
    if let Some(c) = re!(r"^how many (.+?) (?:are in|do) (.+?) (?:at|take at) (.+)$").captures(s) {
        return format!("({}) / ({}) in {}", &c[2], &c[3], &c[1]);
    }
    if let Some(c) = re!(r"^at (.+?), how many (.+?) do (.+?) take$").captures(s) {
        return format!("({}) / ({}) in {}", &c[3], &c[1], &c[2]);
    }
    if let Some(c) = re!(r"^a rate of (.+?) for (.+?): how many (.+)$").captures(s) {
        return format!("{} in {}", accumulate(&c[1], &c[2]), &c[3]);
    }
    if let Some(c) = re!(r"([\d.]+) million ([a-z]+)").captures(s) {
        return s.replacen(&c[0], &format!("{}e6 {}", &c[1], &c[2]), 1);
    }
    if let Some(c) =
        re!(r"^(?:a \w+ earns|a subscription costs) (.+)[;.]+ what is that per (.+)$").captures(s)
    {
        return format!("({}) in dollars/{}", &c[1], &c[2]);
    }
    if let Some(c) = re!(
        r"^at (.+), (?:what do i earn in|what is the pay for|how much for (?:the next )?) (.+)$"
    )
    .captures(s)
    {
        return money(&accumulate(&c[1], &c[2]));
    }
    if let Some(c) = re!(r"^at (.+), what do i earn for (.+)$").captures(s) {
        return money(&accumulate(&c[1], &c[2]));
    }
    if let Some(c) = re!(r"^if i earn (.+) and work (.+), what is my gross pay$").captures(s) {
        return money(&accumulate(&c[1], &c[2]));
    }
    if let Some(c) = re!(r"^if i save (.+) every day, how much will i save in (.+)$").captures(s) {
        return money(&accumulate(&format!("{}/day", &c[1]), &c[2]));
    }
    if let Some(c) = re!(r"^(?:a \w+ (?:produces|makes)|we process) (.+?) (?:in|over) (.+?)[;.]+ (?:how many (.+?) per (.+)|give its output rate per (.+)|what is the average (.+?)-per-(.+?) rate)$").captures(s) {
        let target = if c.get(3).is_some() { format!("{}/{}", &c[3], &c[4]) }
            else if c.get(5).is_some() { format!("{}/{}", noun(&c[1]), &c[5]) }
            else { format!("{}/{}", &c[6], &c[7]) };
        return format!("({}) / ({}) in {target}", &c[1], &c[2]);
    }
    if let Some(c) =
        re!(r"^if (.+?) take (.+?) to read, how many (.+?) per (.+?) is that$").captures(s)
    {
        return format!("({}) / ({}) in {}/{}", &c[1], &c[2], &c[3], &c[4]);
    }
    if let Some(c) = re!(r"^we used (.+?) in (.+?)[.] what is the usage rate in (.+)$").captures(s)
    {
        return format!("({}) / ({}) in {}", &c[1], &c[2], &c[3]);
    }
    if let Some(c) =
        re!(r"^i spend (.+?) over (.+?)[.] what is my average daily spend$").captures(s)
    {
        return money(&scale(&c[1], &c[2], "1 day"));
    }
    if let Some(c) =
        re!(r"^a (.+?) bottle fills (.+?); how many (.+?) can i fill per (.+?) at the same rate$")
            .captures(s)
    {
        return format!("({}) / ({}) in {}/{}", &c[2], &c[1], &c[3], &c[4]);
    }
    if let Some(c) = re!(r"^i can pack (.+?) in (.+?)[.] how long per (.+?), in (.+)$").captures(s)
    {
        return format!("({}) / (({}) / (1 {})) in {}", &c[2], &c[1], &c[3], &c[4]);
    }
    if let Some(c) = re!(r"^at (.+?), how long will a ([\d,]+)-word speech take$").captures(s) {
        return format!("({} words) / ({}) in minutes", &c[2], &c[1]);
    }
    if let Some(c) =
        re!(r"^if a \w+ (?:drips|moves) (.+?) every (.+?), how many (.+?) (?:drip|move) in (.+)$")
            .captures(s)
    {
        return format!("{} in {}", scale(&c[1], &c[2], &c[4]), &c[3]);
    }
    if let Some(c) = re!(r"^at (.+?), how far do i (?:walk|travel|ride) in (.+)$").captures(s) {
        return format!("{} in km", accumulate(&c[1], &c[2]));
    }
    if let Some(c) = re!(r"^a \w+ travels (.+?) in (.+?)[.] what is its average speed$").captures(s)
    {
        return format!("({}) / ({}) in km/hour", &c[1], &c[2]);
    }
    if let Some(c) = re!(r"^split (.+?) into (\d+) equal work sessions$").captures(s) {
        return format!("({}) / {} in hours", &c[1], &c[2]);
    }
    if let Some(c) =
        re!(r"^how many ([\d]+)-minute-([\d]+)-second intervals fit into (.+)$").captures(s)
    {
        return format!(
            "whole_intervals({}, {} minutes {} seconds)",
            &c[3], &c[1], &c[2]
        );
    }
    if let Some(c) = re!(r"^add (.+), (.+), (?:and )?(.+)$").captures(s)
        && [&c[1], &c[2], &c[3]].iter().all(|value| {
            crate::plugins::time::Time::default()
                .seconds(value)
                .is_some()
        })
    {
        return format!("({}) + ({}) + ({})", &c[1], &c[2], &c[3]);
    }
    if let Some(c) = re!(r"^charge (.+?) for (.+?); what is the total$").captures(s) {
        return money(&accumulate(&c[1], &c[2]));
    }
    if let Some(c) = re!(r"^for (?:the next )?(.+?), a \w+ (?:charges|adds) (.+?)[.] (?:what will it cost|how many (.+?) will it add)$").captures(s) {
        let amount = accumulate(&c[2], &c[1]);
        return c.get(3).map_or_else(|| money(&amount), |target| format!("{amount} in {}", target.as_str()));
    }
    if let Some(c) = re!(r"^at (.+?), how many (.+?) will i pack for (.+)$").captures(s) {
        return format!("{} in {}", accumulate(&c[1], &c[3]), &c[2]);
    }
    if let Some(c) = re!(r"^a \w+ rides at (.+?) for (.+?); how far$").captures(s) {
        return format!("{} in km", accumulate(&c[1], &c[2]));
    }
    if let Some(c) =
        re!(r"^a worker earns (.+?) for (.+?), then (.+?) for (.+?)[.] total pay$").captures(s)
    {
        return money(&format!(
            "({}) + ({})",
            accumulate(&c[1], &c[2]),
            accumulate(&c[3], &c[4])
        ));
    }
    if let Some(c) = re!(r"^at (.+?) for (.+?), \+ (.+?) allowance, what is the total$").captures(s)
    {
        return money(&format!(
            "({}) + ({})",
            accumulate(&c[1], &c[2]),
            c[3].trim_start_matches("a ")
        ));
    }
    if let Some(c) = re!(r"^a (.+?)-per-hour consultant bills (.+?), then gives a (.+)% discount[.] what is the final bill$").captures(s) {
        let amount = re!(r"([\d.])-([a-zA-Z])").replace_all(&c[1], "$1 $2");
        return money(&format!("({}) * (1 - ({}) / 100)", accumulate(&format!("{amount}/hour"), &c[2]), &c[3]));
    }
    if let Some(c) =
        re!(r"^a device uses (.+?) for (.+?); electricity costs (.+?)[.] what is the cost$")
            .captures(s)
    {
        return format!("({}) * ({}) in dollars", accumulate(&c[1], &c[2]), &c[3]);
    }
    if let Some(c) =
        re!(r"^at (.+?) every (.+?), how many (.+?) in (?:the next )?(.+)$").captures(s)
    {
        return format!("{} in {}", scale(&c[1], &c[2], &c[4]), &c[3]);
    }
    if let Some(c) = re!(r"^a pump moves (.+?)[.] how long will it take to move (.+)$").captures(s)
    {
        return format!("({}) / ({}) in minutes", &c[2], &c[1]);
    }
    if let Some(c) = re!(r"^i read (.+?)[.] how many (.+?) over (?:the next )?(.+)$").captures(s) {
        return format!("{} in {}", accumulate(&c[1], &c[3]), &c[2]);
    }
    if let Some(c) = re!(r"^for (?:the next )?(.+?), pay is (.+?), but the last (.+?) are paid at (.+?) \* the rate[.] what is the total$").captures(s) {
        return money(&format!("({}) * (remaining_duration({}, {}) + ({}) * ({}))", &c[2], &c[1], &c[3], &c[3], &c[4]));
    }
    if let Some(c) = re!(r"^for a (.+?)-hour shift at (.+?), the first (.+?) are unpaid training[.] how much is paid$").captures(s) { return money(&format!("({}) * remaining_duration({} hours, {})", &c[2], &c[1], &c[3])); }
    if let Some(c) =
        re!(r"^a courier charges (.+?) and travels (.+?) in (.+?)[.] what is the fare$").captures(s)
    {
        return money(&format!("({}) * ({})", &c[1], &c[2]));
    }
    if let Some(c) =
        re!(r"^a car uses (.+?) and travels (.+?); petrol is (.+?)[.] what does the fuel cost$")
            .captures(s)
    {
        return money(&format!("({}) * ({}) * ({})", &c[1], &c[2], &c[3]));
    }
    if let Some(c) =
        re!(r"^a café sells (.+?) every (.+?)[.] at the same rate, how many (.+?) in (.+)$")
            .captures(s)
    {
        return format!("{} in {}", scale(&c[1], &c[2], &c[4]), &c[3]);
    }
    if let Some(c) =
        re!(r"^a server handles (.+?) in (.+?)[.] what is its rate per (.+)$").captures(s)
    {
        return format!("({}) / ({}) in {}/{}", &c[1], &c[2], noun(&c[1]), &c[3]);
    }
    if let Some(c) = re!(r"^if (.+?) workers finish (.+?) identical jobs in (.+?), how many hours per job for (?:one|1) worker at the same productivity$").captures(s) { return format!("({}) * ({}) / ({}) in hours", &c[3], &c[1], &c[2]); }
    if let Some(c) =
        re!(r"^a recipe uses (.+?) flour for (.+?)[.] how much flour for (.+)$").captures(s)
    {
        return scale(&c[1], &c[2], &c[3]);
    }
    if let Some(c) =
        re!(r"^the next (.+?) cost (.+?), billed proportionally[.] what is the charge$").captures(s)
    {
        return money(&accumulate(&c[2], &c[1]));
    }
    if let Some(c) = re!(
        r"^a parking meter charges (.+?), rounded up to the next (.+?)[.] what does (.+?) cost$"
    )
    .captures(s)
    {
        return money(&accumulate(
            &c[1],
            &format!("rounded_duration({}, {})", &c[3], &c[2]),
        ));
    }
    if let Some(c) = re!(r"^a (.+?) monthly plan starts on (.+?)[.] what is its daily cost if this billing month has (.+?) days$").captures(s) { return money(&format!("({}) / ({})", &c[1], &c[3])); }
    if let Some(c) = re!(r"^a monthly fee of (.+?) is prorated by calendar days for (.+?) in a (.+?)-day billing month[.] what is the charge$").captures(s) { return money(&scale(&c[1], &format!("{} days", &c[3]), &c[2])); }
    if let Some(c) =
        re!(r"^if i spend (.+?) every (.+?), what is the average spend per (.+)$").captures(s)
    {
        return money(&scale(&c[1], &c[2], &format!("1 {}", &c[3])));
    }
    if let Some(c) = re!(r"^a printer makes (.+?) for (.+?), pauses (.+?), then runs at (.+?) for (.+?)[.] how many (.+)$").captures(s) { return format!("({}) + ({}) in {}", accumulate(&c[1], &c[2]), accumulate(&c[4], &c[5]), &c[6]); }
    if let Some(c) =
        re!(r"^a clock gains (.+?) every (.+?)[.;] how many (.+?) ahead after (.+)$").captures(s)
    {
        return format!("{} in {}", scale(&c[1], &c[2], &c[4]), &c[3]);
    }
    if let Some(c) =
        re!(r"^a clock gains (.+?) every (.+?)[.;] how far ahead (?:will it be )?after (.+)$")
            .captures(s)
    {
        return format!("{} in seconds", scale(&c[1], &c[2], &c[3]));
    }
    if let Some(c) =
        re!(r"^a fee is (.+?) for (.+?), \+ a fixed (.+?) setup charge[.] total$").captures(s)
    {
        return money(&format!("({}) + ({})", accumulate(&c[1], &c[2]), &c[3]));
    }
    if let Some(c) =
        re!(r"^at (.+?), how long to travel (.+?)(?:, expressed)? in hours and minutes$")
            .captures(s)
    {
        return format!("({}) / ({}) in hours", &c[2], &c[1]);
    }
    if let Some(c) = re!(r"^a pool fills at (.+?) for (.+?), then drains at (.+?) for (.+?)[.] what is the net volume added$").captures(s) { return format!("({}) - ({})", accumulate(&c[1], &c[2]), accumulate(&c[3], &c[4])); }
    if let Some(c) = re!(r"^if a (.+?) fee applies every (.+?), how many fees accrue over (.+?), counting a partial interval as a full fee$").captures(s) { return format!("(rounded_duration({}, {})) / ({})", &c[3], &c[2], &c[2]); }
    if let Some(c) =
        re!(r"^at (.+?), how much does a call cost for (.+?) if billed by each started minute$")
            .captures(s)
    {
        return format!(
            "{} in dollars",
            accumulate(&c[1], &format!("rounded_duration({}, 1 minute)", &c[2]))
        );
    }
    if let Some(c) = re!(r"^a task takes (.+?)[.] if i work on it for (.+?) at (.+?) \* normal speed, how much task time is completed$").captures(s) {
        return format!("finite_task({}, {}, {})", &c[1], c[2].trim_start_matches("the next "), &c[3]);
    }
    if let Some(c) =
        re!(r"^how many (.+?) are produced at (.+?) for (.+?), then (.+?) every (.+?) for (.+)$")
            .captures(s)
    {
        return format!(
            "({}) + ({}) in {}",
            accumulate(&c[2], &c[3]),
            scale(&c[4], &c[5], &c[6]),
            &c[1]
        );
    }
    if let Some(c) = re!(r"^at (.+?), how much do (.+?) cost$").captures(s) {
        return money(&format!("({}) * ({})", &c[1], &c[2]));
    }
    if let Some(c) =
        re!(r"^split (.+?) evenly among (.+?) people; what does each pay to the nearest cent$")
            .captures(s)
    {
        return money(&format!("({}) / ({})", &c[1], &c[2]));
    }
    if let Some(c) =
        re!(r"^a counter records (.+?) in (.+?)[.] what is the average interval between events$")
            .captures(s)
    {
        return format!("({}) / (({}) / (1 events)) in seconds", &c[2], &c[1]);
    }
    if let Some(c) =
        re!(r"^a (.+?) file downloads at (.+?)[.] how long does it take using decimal units$")
            .captures(s)
    {
        return format!("({}) / ({}) in seconds", &c[1], &c[2]);
    }
    if let Some(c) =
        re!(r"^a café makes (.+?) in (.+?)[.] at the same rate, how long for (.+)$").captures(s)
    {
        return format!("({}) / (({}) / ({})) in minutes", &c[3], &c[1], &c[2]);
    }
    if let Some(c) = re!(r"^(?:(?:the )?cost of )?(.+?) at (.+?), \+ (.+)% tax$").captures(s) {
        return money(&format!(
            "({}) * ({}) * (1 + ({}) / 100)",
            &c[1], &c[2], &c[3]
        ));
    }
    if let Some(rest) = s.strip_prefix("rate ") {
        return rest.to_string();
    }
    s.to_string()
}

fn accumulate(rate: &str, duration: &str) -> String {
    format!("({rate}) for {duration}")
}
fn scale(amount: &str, period: &str, duration: &str) -> String {
    format!("({amount}) / ({period}) * ({duration})")
}
fn money(expression: &str) -> String {
    format!("money_amount({expression})")
}
fn noun(quantity: &str) -> &str {
    quantity.split_whitespace().next_back().unwrap_or("")
}