nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
use crate::{Error, re};

/// Classify recognized expressions which produce no value separately from domain failures.
pub(crate) fn classify(input: &str) -> Error {
    let s = input.trim().to_lowercase();
    let arithmetic = re!(r"\b(?:sqrt|cbrt|ln|log|log2|exp|sin|cos|tan|abs|floor|ceil|round)\b")
        .replace_all(&s, "");
    let null = crate::plugins::arithmetic::standard_trig_no_value(input)
        || re!(r"^\d[^a-z]*(?:h|hours?).* timespan$").is_match(&s)
        || re!(r"^(monthly|quarterly|weekly) return on .+ invested .+ returned .+$").is_match(&s)
        || re!(r"^(?:days|weeks|months|years) (?:left|remaining) in this (?:year|month|week)$")
            .is_match(&s)
        || re!(r"^(?:ln\(e\)|c\([\d, ]+\))$").is_match(&s)
        || re!(r"^[+-]?\d[\d,_ ;#]*(?:\.\d+)?(?:e[+-]?\d+)?%*$").is_match(&s)
        || re!(r"^[()\s%]+$").is_match(&s)
        || re!(r"^\(+\s*\d+$").is_match(&s)
        || re!(r"^(?:round|sqrt|sin|cos|tan|abs|floor|ceil|exp|ln|log2?|√)\([^()]*\)$")
            .is_match(&s)
            && (s.contains(',') || s.contains(['²', '³']) || s.ends_with("()"))
        || re!(r"^(?:percent \d+|[\d.]+ percent)$").is_match(&s)
        || re!(r"^\d+:\d+:\d+$").is_match(&s)
        || re!(r"^standard deviation of [+-]?[\d.]+$").is_match(&s)
        || re!(r"^[\d.]+ to base \d+$").is_match(&s)
        || re!(r"^[+-]?[\d.^ +\-]+ choose [\d.]+$").is_match(&s)
        || re!(r"^[\d.]+ is what\s*(?:%|percent) of 0$").is_match(&s)
        || re!(r"^\d{2}:\d{2}:\d{2}:\d{2} at 0 fps$").is_match(&s)
        || re!(r"^\d+ [a-z]+-hours? (?:in|to) [a-z-]+$").is_match(&s)
        || re!(r"^\d+ square (?:kg|kilograms?) (?:in|to) .+$").is_match(&s)
        || re!(r"^- [cfk] to [cfk]$").is_match(&s)
        || re!(r#"^"[^"]*"$"#).is_match(&s)
        || matches!(s.as_str(), "zero" | "forty two");
    if null {
        return Error("null_result".into());
    }
    let domain = re!(r"^.+ as per .+ per .+$").is_match(&s)
        || re!(r"^[+-]?[\d.]+ degrees in degrees minutes seconds$").is_match(&s)
        || re!(r"^0\^[−-]\d+$").is_match(&s)
        || re!(r"^[+-]?[\d.]+\s*(?:mod|%)\s*0$").is_match(&s)
        || re!(r"^[+-]?[\d.]+ is 0\s*(?:%|percent) of what$").is_match(&s)
        || re!(r"^\(?-\d+\)?!$").is_match(&s)
        || re!(r"^(?:[/^]|[*/^]\s*\d+)$").is_match(&s)
        || re!(r"^[<|].*[>|]$").is_match(&s)
        || (s.starts_with('"') && re!(r#""\s*(?:[+*/<>=!]| - )"#).is_match(&s))
        || (re!(r"(?:\d[eE][+-]?\d{3,}|\^[+-]?\d{3,})").is_match(&s)
            && re!(r"^[0-9e.(),+*/^−!\s-]+$").is_match(&arithmetic))
        || re!(r"^\d+\^? (?:degrees [fc]|meters?) (?:in|to) .+$").is_match(&s);
    Error(
        if domain {
            "internal_error"
        } else {
            "invalid_expression"
        }
        .into(),
    )
}