nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
//! Billing intervals and shift sections lower to ordinary dimensional arithmetic.
use crate::{Context, Error, ModelPosition, Outcome, Plugin, number, re};

pub struct RateQueries;
impl Plugin for RateQueries {
    fn rewrite_call(
        &self,
        name: &str,
        arguments: &str,
        context: &Context,
        _: ModelPosition,
    ) -> Outcome {
        let name = name.to_ascii_lowercase();
        if name == "finite_task" {
            return self.rewrite(&format!("finite_task({arguments})"), context);
        }
        if !matches!(
            name.as_str(),
            "rounded_duration" | "whole_intervals" | "remaining_duration"
        ) {
            return None;
        }
        Some((|| {
            let args = super::named_quantities::function_arguments(arguments, false)?;
            let [whole, interval] = args.as_slice() else {
                return Err(Error("invalid_expression".into()));
            };
            let value = if name == "remaining_duration" {
                remaining(whole, interval)?
            } else {
                let (count, seconds) = intervals(whole, interval)?;
                if name == "whole_intervals" {
                    count.floor()
                } else {
                    count.ceil() * seconds
                }
            };
            if !value.is_finite() {
                return Err(Error("numeric_overflow".into()));
            }
            Ok(if name == "whole_intervals" {
                format!("real({value:e})")
            } else {
                format!("(real({value:e})*(1 second))")
            })
        })())
    }
    fn rewrite(&self, input: &str, _: &Context) -> Outcome {
        if let Some(c) = re!(r"^finite_task\(([^()]+), ([^()]+), ([^()]+)\)$").captures(input) {
            let time = super::time::Time::default();
            for duration in [&c[1], &c[2]] {
                if !time
                    .seconds(duration)
                    .is_some_and(|seconds| seconds.is_finite() && seconds >= 0.0)
                {
                    return Some(Err(Error("invalid_duration".into())));
                }
            }
            if !super::arithmetic::eval(&c[3]).is_some_and(|speed| speed >= 0.0) {
                return Some(Err(Error("invalid_rate".into())));
            }
            return Some(Ok(format!(
                "min(({}), ({}) * ({})) in hours",
                &c[1], &c[2], &c[3]
            )));
        }
        if re!(r"^whole_intervals\([^()]+, [^()]+\)$").is_match(input) {
            return None;
        }
        let mut output = String::new();
        let mut start = 0;
        for c in
            re!(r"\b(rounded_duration|whole_intervals|remaining_duration)\(([^()]+), ([^()]+)\)")
                .captures_iter(input)
        {
            let result = if &c[1] == "remaining_duration" {
                remaining(&c[2], &c[3])
            } else {
                intervals(&c[2], &c[3]).map(|(quotient, interval)| {
                    if &c[1] == "whole_intervals" {
                        quotient.floor()
                    } else {
                        quotient.ceil() * interval
                    }
                })
            };
            let rounded = match result {
                Ok(value) => value,
                Err(error) => return Some(Err(error)),
            };
            if !rounded.is_finite() {
                return Some(Err(Error("numeric_overflow".into())));
            }
            let m = c.get(0).unwrap();
            output.push_str(&input[start..m.start()]);
            output.push_str(&if &c[1] == "whole_intervals" {
                number(rounded)
            } else {
                format!("({} seconds)", number(rounded))
            });
            start = m.end();
        }
        if start == 0 {
            return None;
        }
        output.push_str(&input[start..]);
        Some(Ok(output))
    }
    fn evaluate(&self, input: &str, context: &Context) -> Outcome {
        if let Some(expression) = input
            .strip_prefix("money_amount(")
            .and_then(|s| s.strip_suffix(')'))
        {
            return Some(
                super::compositions::Compositions::default().evaluate_money(expression, context),
            );
        }
        let c = re!(r"^whole_intervals\(([^()]+), ([^()]+)\)$").captures(input)?;
        Some(intervals(&c[1], &c[2]).map(|(count, _)| number(count.floor())))
    }
}
fn remaining(whole: &str, section: &str) -> Result<f64, Error> {
    let time = super::time::Time::default();
    let whole = time
        .seconds(whole)
        .ok_or_else(|| Error("invalid_duration".into()))?;
    let section = time
        .seconds(section)
        .ok_or_else(|| Error("invalid_duration".into()))?;
    let tolerance = 8.0 * f64::EPSILON * whole.abs().min(1e6);
    if !whole.is_finite()
        || !section.is_finite()
        || whole < 0.0
        || section < 0.0
        || section - whole > tolerance
    {
        return Err(Error("invalid_duration".into()));
    }
    Ok((whole - section).max(0.0))
}
fn intervals(duration: &str, interval: &str) -> Result<(f64, f64), Error> {
    let time = super::time::Time::default();
    let duration = time
        .seconds(duration)
        .ok_or_else(|| Error("invalid_duration".into()))?;
    let interval = time
        .seconds(interval)
        .ok_or_else(|| Error("invalid_duration".into()))?;
    if duration < 0.0 || !duration.is_finite() {
        return Err(Error("invalid_duration".into()));
    }
    if interval <= 0.0 || !interval.is_finite() {
        return Err(Error("invalid_rounding_increment".into()));
    }
    let quotient = duration / interval;
    if !quotient.is_finite() {
        return Err(Error("numeric_overflow".into()));
    }
    let integer = quotient.round();
    // Decimal durations can land one ulp across an exact interval boundary.
    let quotient = if integer > 0.0
        && (quotient - integer).abs() <= 8.0 * f64::EPSILON * quotient.abs().clamp(1.0, 1e6)
    {
        integer
    } else {
        quotient
    };
    Ok((quotient, interval))
}