nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
//! Wording adapters; grouped expressions are evaluated by the common calculator.
use super::percentage;
use crate::{plugins::units::Units, re};
pub(super) fn rewrite(s: &str, units: &Units) -> String {
    let mut normalized = s.replace("%age", "%");
    for (symbol, fraction) in [
        ('½', "1/2"),
        ('⅓', "1/3"),
        ('⅔', "2/3"),
        ('¼', "1/4"),
        ('¾', "3/4"),
        ('⅕', "1/5"),
        ('⅖', "2/5"),
        ('⅗', "3/5"),
        ('⅘', "4/5"),
        ('⅙', "1/6"),
        ('⅚', "5/6"),
        ('⅐', "1/7"),
        ('⅛', "1/8"),
        ('⅜', "3/8"),
        ('⅝', "5/8"),
        ('⅞', "7/8"),
        ('⅑', "1/9"),
        ('⅒', "1/10"),
    ] {
        normalized = normalized.replace(symbol, &format!(" ({fraction})"));
    }
    normalized = re!(r"\b(\d+) \((\d+/\d+)\)")
        .replace_all(&normalized, "($1 + ($2))")
        .into_owned();
    normalized = normalized.replace("− ", "-");
    normalized = normalized.split_whitespace().collect::<Vec<_>>().join(" ");
    if normalized != s {
        return normalized;
    }
    if let Some(expression) = s
        .strip_prefix("using the stated rates, ")
        .or_else(|| s.strip_prefix("at the stated rates, "))
    {
        return expression.into();
    }
    if let Some(next) = sequence(s) {
        return next;
    }
    if let Some(expression) = s.strip_prefix("take ")
        && !s.contains(" off ")
    {
        return expression.into();
    }
    if let Some(c) =
        re!(r"^(?:the )?(?:signed )?(?:%|percentage) change from (.+) to (.+)$").captures(s)
    {
        return format!("{} to {} as %", &c[1], &c[2]);
    }
    if let Some(c) = re!(r"^by what % is (.+) (less|greater) than (.+)$").captures(s) {
        return format!(
            "(({}) {} ({})) is what % of ({})",
            if &c[2] == "less" { &c[3] } else { &c[1] },
            "-",
            if &c[2] == "less" { &c[1] } else { &c[3] },
            &c[3]
        );
    }
    if let Some(c) =
        re!(r"^compare (.+) with (.+): by what % is the first greater than the second$").captures(s)
    {
        return format!("by what % is {} greater than {}", &c[1], &c[2]);
    }
    if let Some(c) = re!(r"^what % must (.+) be increased by to become (.+)$").captures(s) {
        return format!("{} to {} as %", &c[1], &c[2]);
    }
    if let Some(c) = re!(r"^(?:express )?(.+) as (?:a )?% of (.+)$").captures(s) {
        return format!("({}) is what % of ({})", &c[1], &c[2]);
    }
    if let Some(c) =
        re!(r"^(?:express |convert )?(.+) (?:as|to) (?:a )?(fraction|%)(?: in lowest terms)?$")
            .captures(s)
            .filter(|c| !c[1].contains('?'))
    {
        return if &c[2] == "%" {
            if c[1].contains(" to ") {
                return s.into();
            }
            format!("({}) is what % of 1", &c[1])
        } else {
            format!("{} as fraction", &c[1])
        };
    }
    if let Some(c) =
        re!(r"^what fraction of (.+) is (.+)\? give the result as (?:a )?%$").captures(s)
    {
        return format!("({}) is what % of ({})", &c[2], &c[1]);
    }
    if let Some(c) = re!(r"^(?:the )?signed difference between (.+) and (.+)$").captures(s) {
        return format!("({}) - ({})", &c[1], &c[2]);
    }
    if let Some(c) =
        re!(r"^(?:the )?(?:signed )?%-point difference between (.+)% and (.+)%$").captures(s)
    {
        return format!("({}) - ({})", &c[1], &c[2]);
    }
    if let Some(c) = re!(r"^(?:a )?number after (?:a )?(.+)% (increase|decrease) is (.+); (?:what was it before the (?:increase|decrease)|find the original)$").captures(s) {
        return format!("({}) / (1 {} ({})/100)", &c[3], if &c[2] == "increase" { "+" } else { "-" }, &c[1]);
    }
    if let Some(c) = re!(r"^after (?:a )?(.+)% reduction, (?:a(?: quantity)?|value) is (.+)\. what was the original (?:quantity|value)$").captures(s) {
        return format!("({}) / (1 - ({})/100)", &c[2], &c[1]);
    }
    if let Some(c) = re!(r"^if (.+)% of (?:a(?: quantity| number)?|number) is (.+), what is (.+)% of (?:that |the )?(?:quantity|number)$").captures(s) {
        return format!("({}) / ({}) * ({})", &c[2], &c[1], &c[3]);
    }
    if let Some(c) =
        re!(r"^if (.+) (?:of (?:a )?|\* )number is (.+), what is (.+)% of (?:the )?number$")
            .captures(s)
    {
        return format!("({}) / ({}) * (({})/100)", &c[2], &c[1], &c[3]);
    }
    if let Some(c) = re!(
        r"^apply (?:a )?(.+)% (increase|decrease), then (?:a )?(.+)% (increase|decrease) to (.+)$"
    )
    .captures(s)
    {
        return format!(
            "({}) * (1 {} ({})/100) * (1 {} ({})/100)",
            &c[5],
            if &c[2] == "increase" { "+" } else { "-" },
            &c[1],
            if &c[4] == "increase" { "+" } else { "-" },
            &c[3]
        );
    }
    if let Some(c) =
        re!(r"^(.+) is to (.+) as x is to (.+), find x$").captures(s.trim_start_matches("if "))
    {
        return format!("({}) / ({}) * ({})", &c[1], &c[2], &c[3]);
    }
    if let Some(c) = re!(r"^(.+)% of (?:the )?(difference between|average of) (.+)$").captures(s) {
        let operand = if &c[2] == "average of" {
            format!("mean({})", c[3].replace(" and ", ", "))
        } else {
            format!("{} {}", &c[2], &c[3])
        };
        return format!("({}/100) * ({operand})", &c[1]);
    }
    if let Some(c) = re!(r"^add ([+-]?[\d.]+)% to (.+)$").captures(s) {
        return format!("({}) * (1 + {}/100)", &c[2], &c[1]);
    }
    if let Some(c) =
        re!(r"^(?:a )?fraction has denominator (.+) and is (.+)%; find its numerator$").captures(s)
    {
        return format!("({}) * (({})/100)", &c[1], &c[2]);
    }
    if let Some(c) = re!(r"^(?:the )?numerator of (?:a )?fraction is (.+)% of its denominator\. what is the fraction in simplest terms$").captures(s) {
        return format!("({}/100) as fraction", &c[1]);
    }
    if let Some(c) = re!(r"^(.+)% discount saves (.+)\. what is the price after discount$")
        .captures(s.trim_start_matches("a "))
    {
        return format!("({}) / ({}/100) * (1 - {}/100)", &c[2], &c[1], &c[1]);
    }
    if let Some(c) = re!(r"^after (.+) successive equal % increases, (.+) becomes (.+)\. what is the increase rate each time$").captures(s) {
        return format!("1 to (({})/({}))^(1/({})) as %", &c[3], &c[2], &c[1]);
    }
    if let Some(c) =
        re!(r"^(.+) (?:of|\*) the amount left after (.+)% of (.+) is removed$").captures(s)
    {
        return format!("({}) * ({}) * (1 - ({})/100)", &c[1], &c[3], &c[2]);
    }
    if let Some(c) = re!(r"^(.+)% of the remainder after subtracting (.+)% of (.+)$").captures(s) {
        return format!("({}/100) * ({}) * (1 - ({})/100)", &c[1], &c[3], &c[2]);
    }
    if let Some(c) = re!(r"^(?:a )?(?:quantity|value|number)? ?is (.+)% greater than (.+)\. what is (.+)% of that (?:quantity|value|number)$").captures(s) {
        return format!("({}) * (1 + ({})/100) * (({})/100)", &c[2], &c[1], &c[3]);
    }
    if let Some(c) =
        re!(r"^add ([+-]?[\d.]+)% tax after taking ([+-]?[\d.]+)% off (.+)$").captures(s)
    {
        return discount(&c[3], &c[2], &c[1]);
    }
    if let Some(c) = re!(
        r"^what does (.+) cost after (?:a )?([+-]?[\d.]+)% discount and then ([+-]?[\d.]+)% tax$"
    )
    .captures(s)
    {
        return discount(&c[1], &c[2], &c[3]);
    }
    if let Some(c) =
        re!(r"^(?:a )?(.+) (?:meal|bill) gets (?:a )?([+-]?[\d.]+)% tip; what's the total$")
            .captures(s)
    {
        return format!("({}) * (1 + {}/100)", &c[1], &c[2]);
    }
    if let Some(c) = re!(r"^(?:a )?([+-]?[\d.]+)\s*% tip on (?:a )?(.+?)(?: bill)?$").captures(s) {
        return format!("({}) * ({}/100)", &c[2], &c[1]);
    }
    if let Some(c) = re!(r"^split (.+) evenly between (.+) people$").captures(s) {
        return format!("({}) / ({})", &c[1], &c[2]);
    }
    if let Some(c) = re!(
        r"^(.+) friends split (?:a )?(.+) bill, then each adds (?:a )?(.+) tip; total per person$"
    )
    .captures(s)
    {
        return format!("({}) / ({}) + ({})", &c[2], &c[1], &c[3]);
    }
    if let Some(c) =
        re!(r"^i paid (.+) for (.+) identical \w+; what did each \w+ cost$").captures(s)
    {
        return format!("({}) / ({})", &c[1], &c[2]);
    }
    if let Some(c) = re!(r"^(.+), then add ([+-]?[\d.]+)% (?:tax|tip) to the result$").captures(s) {
        return format!("({}) * (1 + {}/100)", percentage(&c[1], units), &c[2]);
    }
    if let Some(c) =
        re!(r"^apply (?:a )?([+-]?[\d.]+)% discount then ([+-]?[\d.]+)% tax to (.+)$").captures(s)
    {
        return discount(&c[3], &c[1], &c[2]);
    }
    if let Some(c) = re!(r"^(increase|decrease|reduce) (.+) by ([+-]?[\d.]+)%$").captures(s) {
        return format!(
            "({}) * (1 {} {}/100)",
            &c[2],
            if &c[1] == "increase" { "+" } else { "-" },
            &c[3]
        );
    }
    if let Some(c) = re!(r"^(.+) (increased|decreased|less) (?:by )?([+-]?[\d.]+)\s*%$").captures(s)
    {
        return format!(
            "({}) * (1 {} {}/100)",
            &c[1],
            if &c[2] == "increased" { "+" } else { "-" },
            &c[3]
        );
    }
    if let Some(c) =
        re!(r"^(.+) with (?:a )?([+-]?[\d.]+)% (discount|increase|decrease|surcharge)$").captures(s)
    {
        return format!(
            "({}) * (1 {} {}/100)",
            &c[1],
            if matches!(&c[3], "increase" | "surcharge") {
                "+"
            } else {
                "-"
            },
            &c[2]
        );
    }
    if let Some(c) =
        re!(r"^apply ([+-]?[\d.]+)% to (.+) as (?:an? )?(increase|decrease)$").captures(s)
    {
        return format!(
            "({}) * (1 {} {}/100)",
            &c[2],
            if &c[3] == "increase" { "+" } else { "-" },
            &c[1]
        );
    }
    if let Some(c) = re!(r"^subtract ([+-]?[\d.]+)% from (.+)$").captures(s) {
        return format!("({}) * (1 - {}/100)", &c[2], &c[1]);
    }
    if let Some(c) =
        re!(r"^(?:(?:add|apply) )?(?:a )?([+-]?[\d.]+)% (?:tax|tip) (?:to|on) (.+)$").captures(s)
    {
        return format!("({}) * (1 + {}/100)", &c[2], &c[1]);
    }
    if let Some(c) = re!(r"^(.+) \+ ([+-]?[\d.]+)% (?:tax|tip)$").captures(s) {
        return format!("({}) * (1 + {}/100)", &c[1], &c[2]);
    }
    if let Some(c) = re!(r"^what % of (.+) is (.+)$").captures(s) {
        return format!("{} is what % of {}", &c[2], &c[1]);
    }
    if let Some(c) = re!(r"^split (?:a )?(.+?)(?: bill)? ([+-]?[\d.]+) ways$").captures(s) {
        return format!("({}) / {}", &c[1], &c[2]);
    }
    if let Some(c) = re!(r"^(?:split )?(.+?) (?:split|divided)(?: equally| evenly)? (?:among|between) ([+-]?[\d.]+) (?:people|diners)$").captures(s) {
        return format!("({}) / {}", &c[1], &c[2]);
    }
    if let Some(c) = re!(r"^(.+) items at (.+) each \+ (.+) shipping$").captures(s) {
        return format!("{} * ({}) + ({})", &c[1], &c[2], &c[3]);
    }
    if let Some(c) = re!(r"^if i earn (.+), how much for (.+)$").captures(s) {
        return format!("{} for {}", &c[1], &c[2]);
    }
    if let Some(c) = re!(r"^(?:take )?([+-]?[\d.]+)% off (.+)$").captures(s) {
        return format!("({}) * (1 - {}/100)", &c[2], &c[1]);
    }
    if let Some(c) = re!(r"^what remains after (?:a )?([+-]?[\d.]+)% discount on (.+)$").captures(s)
    {
        return format!("({}) * (1 - {}/100)", &c[2], &c[1]);
    }
    if let Some(c) = re!(r"^(?:a )?(.+) purchase has (?:a )?(.+) coupon, then ([+-]?[\d.]+)% tax on the discounted price; total$").captures(s) {
        return format!("(({}) - ({})) * (1 + {}/100)", &c[1], &c[2], &c[3]);
    }
    s.to_string()
}

fn discount(amount: &str, discount: &str, tax: &str) -> String {
    format!("({amount}) * (1 - {discount}/100) * (1 + {tax}/100)")
}

fn sequence(input: &str) -> Option<String> {
    if let Some(c) =
        re!(r"^(.+?), then take (.+?)% of (?:that|the) result and subtract it from (.+)$")
            .captures(input)
    {
        return Some(format!("({}) - (({}) * (({})/100))", &c[3], &c[1], &c[2]));
    }
    let (first, next) = crate::plugins::syntax::split_last(
        input,
        &[", then ", " and then ", ", halve ", ", increase "],
    )?;
    let next = if input.contains(", halve ") && next == "the result" {
        "halve the result".to_string()
    } else if input.contains(", increase ") && next.starts_with("that amount by ") {
        format!("increase {next}")
    } else {
        next.to_string()
    };
    let next = next.as_str();
    let first = first
        .trim_start_matches("start with ")
        .trim_start_matches("convert ");
    if let Some(c) =
        re!(r"^(increase|decrease|reduce)(?: the result| that amount)? by ([+-]?[\d.]+)%$")
            .captures(next)
    {
        return Some(format!(
            "({first}) * (1 {} {}/100)",
            if &c[1] == "increase" { "+" } else { "-" },
            &c[2]
        ));
    }
    if let Some(c) =
        re!(r"^take (?:another )?([+-]?[\d.]+)% off the (?:new price|result|new amount)$")
            .captures(next)
    {
        return Some(format!("({first}) * (1 - {}/100)", &c[1]));
    }
    if let Some(c) = re!(r"^(?:take|find|calculate) (.+)% of (?:it|that (?:length|duration)|the (?:mass|AUD amount|aud amount|volume|result|sum|new amount|converted amount))$").captures(next) {
        return Some(format!("({first}) * ({}/100)", &c[1]));
    }
    if let Some(c) = re!(r"^(?:find|take) (.+) (?:of|\*) that amount$").captures(next) {
        return Some(format!("({first}) * ({})", &c[1]));
    }
    if next == "halve the result" {
        return Some(format!("({first}) / 2"));
    }
    if let Some(c) = re!(r"^divide by (.+)$").captures(next) {
        return Some(format!("({first}) / ({})", &c[1]));
    }
    if let Some(c) =
        re!(r"^(?:add|apply) ([+-]?[\d.]+)% (?:tax|tip)(?: to the result)?$").captures(next)
    {
        return Some(format!("({first}) * (1 + {}/100)", &c[1]));
    }
    if let Some(c) = re!(r"^(add|subtract) ([+-]?[\d.]+)%(?: from the result)?$").captures(next) {
        return Some(format!(
            "({first}) * (1 {} {}/100)",
            if &c[1] == "add" { "+" } else { "-" },
            &c[2]
        ));
    }
    super::operations::sequence(input)
}