nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
//! Natural-language calculations with explicit, composable plugins.
mod diagnostics;
pub mod plugins;
pub mod presentation;
use presentation::{Highlighter, SyntaxHighlighter};
use std::{borrow::Cow, fmt};

#[derive(Debug, Clone, PartialEq)]
pub struct Context {
    pub rem_px: f64,
    pub work_hours_per_day: f64,
    pub now: chrono::DateTime<chrono::Utc>,
    pub timezone: chrono_tz::Tz,
    pub rates: std::collections::BTreeMap<String, f64>,
}
impl Default for Context {
    fn default() -> Self {
        Self {
            rem_px: 16.0,
            work_hours_per_day: 8.0,
            now: chrono::Utc::now(),
            timezone: chrono_tz::UTC,
            rates: std::collections::BTreeMap::new(),
        }
    }
}
#[derive(Debug, Clone, PartialEq)]
pub struct Error(pub String);
impl fmt::Display for Error {
    fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
        f.write_str(&self.0)
    }
}
impl std::error::Error for Error {}
#[derive(Debug, Clone, PartialEq)]
pub struct Span {
    pub start: usize,
    pub end: usize,
}
#[derive(Debug, Clone, PartialEq)]
pub struct Answer {
    pub display: String,
    pub highlights: Vec<Span>,
}
pub type Outcome = Option<Result<String, Error>>;
/// Standalone model answers may retain an exact presentation directive.
#[derive(Clone, Copy, Debug, PartialEq, Eq)]
pub enum ModelPosition {
    Standalone,
    Operand,
}
/// Wording hooks run once in registration order, then operation hooks receive the
/// final expression. Return None to decline; errors mean recognized but invalid.
pub trait Plugin: Send + Sync {
    /// Return a lowered expression. Highlighting always uses the original source.
    fn rewrite(&self, _input: &str, _context: &Context) -> Outcome {
        None
    }
    /// Lower one complete model call after its inner calls have been lowered.
    /// Decline unowned names; return a terminal typed expression for owned calls.
    fn rewrite_call(
        &self,
        _name: &str,
        _arguments: &str,
        _context: &Context,
        _position: ModelPosition,
    ) -> Outcome {
        None
    }
    /// Lower a complete natural model request after its original children.
    /// Decline unrelated wording; replacements are terminal for this model walk.
    fn rewrite_model(&self, _input: &str, _context: &Context, _position: ModelPosition) -> Outcome {
        None
    }
    /// Return the formatted result of an operation.
    fn evaluate(&self, _input: &str, _context: &Context) -> Outcome {
        None
    }
}
pub struct Calculator {
    plugins: Vec<Box<dyn Plugin>>,
    context: Context,
    highlighter: Box<dyn Highlighter>,
    model_calls: bool,
}
impl Calculator {
    pub fn empty(context: Context) -> Self {
        Self {
            plugins: vec![],
            context,
            highlighter: Box::new(SyntaxHighlighter::default()),
            model_calls: false,
        }
    }
    pub fn with_plugin(mut self, plugin: impl Plugin + 'static) -> Self {
        self.plugins.push(Box::new(plugin));
        self
    }
    /// Resolve nested model calls through their owners before ordered wording hooks.
    pub fn with_model_calls(mut self) -> Self {
        self.model_calls = true;
        self
    }
    pub fn with_highlighter(mut self, highlighter: impl Highlighter + 'static) -> Self {
        self.highlighter = Box::new(highlighter);
        self
    }
    pub fn with_context(mut self, context: Context) -> Self {
        self.context = context;
        self
    }
    pub fn standard() -> Self {
        plugins::standard(Self::empty(Context::default()))
    }
    /// Standard plugins plus opt-in shorthand and composition conveniences.
    pub fn extended() -> Self {
        plugins::standard(
            Self::empty(Context::default())
                .with_model_calls()
                .with_plugin(plugins::predicates::Predicates::default())
                .with_plugin(plugins::electrical_queries::ElectricalQueries::default())
                .with_plugin(plugins::practical_queries::PracticalQueries::default())
                .with_plugin(plugins::probability::Probability)
                .with_plugin(plugins::finance_queries::FinanceQueries)
                .with_plugin(plugins::chemistry::Chemistry::default())
                .with_plugin(plugins::mechanics::Mechanics::default())
                .with_plugin(plugins::geometry::Geometry::default())
                .with_plugin(plugins::algebra_queries::AlgebraQueries::default())
                .with_plugin(plugins::business_queries::BusinessQueries::default())
                .with_plugin(plugins::thermal_queries::ThermalQueries::default())
                .with_plugin(plugins::fluid_queries::FluidQueries::default())
                .with_plugin(plugins::optics_queries::OpticsQueries::default())
                .with_plugin(plugins::acoustics_queries::AcousticsQueries::default())
                .with_plugin(plugins::accumulation_queries::AccumulationQueries::default())
                .with_plugin(plugins::language::Language::default())
                .with_plugin(plugins::rate_queries::RateQueries)
                .with_plugin(plugins::integer_queries::IntegerQueries)
                .with_plugin(plugins::compositions::Compositions::default()),
        )
    }
    pub fn evaluate(&self, input: &str) -> Result<Answer, Error> {
        self.evaluate_with(input, &self.context)
    }
    pub fn evaluate_with(&self, input: &str, context: &Context) -> Result<Answer, Error> {
        let original = input;
        let input = input.trim();
        if input.is_empty() || original.len() > 4096 {
            return Err(Error("invalid_expression".into()));
        }
        let mut expression = if self.model_calls {
            Cow::Owned(self.rewrite_model_calls(input, context)?)
        } else {
            Cow::Borrowed(input)
        };
        for plugin in &self.plugins {
            if let Some(result) = plugin.rewrite(expression.trim(), context) {
                let next = result.map_err(|error| {
                    if error.0 == "invalid_expression" {
                        diagnostics::classify(expression.trim())
                    } else {
                        error
                    }
                })?;
                let next = checked_expression(next)?;
                let next = if self.model_calls && next.trim() != expression.trim() {
                    self.rewrite_model_calls(&next, context)?
                } else {
                    next
                };
                expression = Cow::Owned(next);
            }
        }
        let input = expression.trim();
        for p in &self.plugins {
            if let Some(result) = p.evaluate(input, context) {
                return result
                    .map_err(|e| {
                        if e.0 == "invalid_expression" {
                            diagnostics::classify(input)
                        } else {
                            e
                        }
                    })
                    .map(|display| Answer {
                        display,
                        highlights: self.highlighter.highlight(original),
                    });
            }
        }
        Err(diagnostics::classify(input))
    }

    fn rewrite_model_calls(&self, input: &str, context: &Context) -> Result<String, Error> {
        let lowered = plugins::syntax::rewrite_models(
            input,
            crate::re!(r"(?i)\b[a-z_][a-z0-9_]*\s*\("),
            |name, arguments, position| {
                for plugin in &self.plugins {
                    if let Some(result) =
                        plugin.rewrite_call(name.trim(), arguments, context, position)
                    {
                        return Some(result);
                    }
                }
                None
            },
            |input, position| {
                self.plugins
                    .iter()
                    .find_map(|plugin| plugin.rewrite_model(input, context, position))
            },
        )
        .map_err(|error| {
            if error.0 == "invalid_expression" {
                diagnostics::classify(input)
            } else {
                error
            }
        })?;
        checked_expression(lowered)
    }
}
fn checked_expression(expression: String) -> Result<String, Error> {
    if expression.trim().is_empty() || expression.len() > 4096 {
        Err(Error("invalid_expression".into()))
    } else {
        Ok(expression)
    }
}
/// Byte offsets into the input; adapters can render these spans however they like.
pub fn highlights(input: &str) -> Vec<Span> {
    SyntaxHighlighter::default().highlight(input)
}
pub fn number(x: f64) -> String {
    if !x.is_finite() {
        return x.to_string();
    }
    if x != 0.0 && (x.abs() < 1e-6 || x.abs() >= 1e15) {
        let scientific = format!("{x:.10e}");
        let (mantissa, exponent) = scientific.split_once('e').unwrap();
        return format!(
            "{}e{}",
            mantissa.trim_end_matches('0').trim_end_matches('.'),
            exponent
        );
    }
    if x.abs() >= 1e12 && x.abs() < 1e15 {
        return format!("{}T", number(x / 1e12));
    }
    let x = if x == 0.0 { 0.0 } else { x };
    let s = format!("{x:.10}");
    let s = s.trim_end_matches('0').trim_end_matches('.');
    let (whole, frac) = s.split_once('.').unwrap_or((s, ""));
    let sign = if whole.starts_with('-') { "-" } else { "" };
    let digits = whole.trim_start_matches('-');
    let mut out = String::from(sign);
    for (i, c) in digits.chars().enumerate() {
        if i > 0 && (digits.len() - i) % 3 == 0 {
            out.push(',');
        }
        out.push(c);
    }
    if !frac.is_empty() {
        out.push('.');
        out.push_str(frac);
    }
    out
}

macro_rules! re {
    ($pattern:literal) => {{
        static RE: std::sync::LazyLock<regex::Regex> =
            std::sync::LazyLock::new(|| regex::Regex::new($pattern).unwrap());
        &*RE
    }};
}
pub(crate) use re;