nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
//! Small, shared scans that keep phrase operators outside nested groups.
pub(crate) const CONVERSIONS: &[&str] = &[" in ", " to ", " into ", " as "];

pub(crate) fn split_last<'a>(input: &'a str, phrases: &[&str]) -> Option<(&'a str, &'a str)> {
    let mut depth = 0i32;
    let mut found = None;
    for (index, character) in input.char_indices() {
        match character {
            '(' => depth += 1,
            ')' => depth -= 1,
            _ if depth == 0 => {
                if let Some(phrase) = phrases
                    .iter()
                    .find(|phrase| input[index..].starts_with(**phrase))
                {
                    found = Some((&input[..index], &input[index + phrase.len()..]));
                }
            }
            _ => {}
        }
        if depth < 0 {
            return None;
        }
    }
    (depth == 0).then_some(found).flatten()
}

pub(crate) fn ungroup(input: &str) -> &str {
    let input = input.trim();
    if !input.starts_with('(') {
        return input;
    }
    let mut depth = 0;
    for (index, character) in input.char_indices() {
        match character {
            '(' => depth += 1,
            ')' => depth -= 1,
            _ => {}
        }
        if depth == 0 {
            return if index + 1 == input.len() {
                ungroup(&input[1..index])
            } else {
                input
            };
        }
    }
    input
}

pub(crate) fn word_operators(input: &str) -> String {
    input
        .replace(" plus ", " + ")
        .replace(" minus ", " - ")
        .replace(" divided by ", " / ")
        .replace(", multiplied by ", " * ")
        .replace(" multiplied by ", " * ")
        .replace(" times ", " * ")
        .replace('×', "*")
}

/// Longest complete unit at the beginning of a phrase, excluding following operators.
pub(crate) fn unit_prefix(input: &str, recognizes: impl Fn(&str) -> bool) -> Option<usize> {
    input
        .char_indices()
        .map(|(index, _)| index)
        .chain(std::iter::once(input.len()))
        .filter(|end| *end == input.len() || input[*end..].starts_with([' ', ',']))
        .rfind(|end| recognizes(input[..*end].trim()))
}

/// Inner ranges of outermost groups; callers can lower each without losing its scope.
pub(crate) fn groups(input: &str) -> Option<Vec<std::ops::Range<usize>>> {
    let (mut depth, mut start) = (0i32, 0);
    let mut groups = vec![];
    for (index, character) in input.char_indices() {
        match character {
            '(' => {
                if depth == 0 {
                    start = index + 1;
                }
                depth += 1;
            }
            ')' => {
                depth -= 1;
                if depth < 0 {
                    return None;
                }
                if depth == 0 {
                    groups.push(start..index);
                }
            }
            _ => {}
        }
    }
    (depth == 0).then_some(groups)
}

/// Make adjacent numeric/group coefficients explicit before power selection.
/// The owner decides which grouped operands use this multiplication rule.
pub(crate) fn group_products(
    input: &str,
    admits: impl Fn(&str) -> bool,
) -> Result<Option<String>, crate::Error> {
    let groups = groups(input).ok_or_else(|| crate::Error("invalid_expression".into()))?;
    let mut product = String::new();
    let mut start = 0;
    for group in groups {
        let opening = group.start - 1;
        let prefix = input[..opening].trim_end();
        if (prefix.ends_with(')')
            || crate::re!(r"(?:^|[^a-zA-Z0-9_.])(?:\d[\d,]*(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?$")
                .is_match(prefix))
            && admits(&input[group.clone()])
        {
            product.push_str(&input[start..opening]);
            product.push_str(" * ");
            start = opening;
        }
    }
    if start == 0 {
        return Ok(None);
    }
    product.push_str(&input[start..]);
    Ok(Some(product))
}

/// Lower named family calls inside ordinary arithmetic without parsing their values.
/// The supplied pattern ends at the opening parenthesis; arguments are visited first.
pub(crate) fn rewrite_calls(
    input: &str,
    calls: &regex::Regex,
    rewrite: impl Fn(&str, &str) -> Result<String, crate::Error>,
) -> Result<String, crate::Error> {
    fn visit(
        input: &str,
        calls: &regex::Regex,
        rewrite: &impl Fn(&str, &str) -> Result<String, crate::Error>,
        depth: usize,
    ) -> Result<String, crate::Error> {
        if depth > 64 {
            return Err(crate::Error("expression_too_deep".into()));
        }
        let mut output = String::new();
        let mut start = 0;
        for call in calls.find_iter(input) {
            if call.start() < start {
                continue;
            }
            let open = call.end() - 1;
            let (mut level, mut end) = (0, None);
            for (index, ch) in input[open..].char_indices() {
                match ch {
                    '(' => level += 1,
                    ')' => level -= 1,
                    _ => {}
                }
                if level == 0 {
                    end = Some(open + index);
                    break;
                }
            }
            let end = end.ok_or_else(|| crate::Error("invalid_expression".into()))?;
            let arguments = visit(&input[open + 1..end], calls, rewrite, depth + 1)?;
            output.push_str(&input[start..call.start()]);
            output.push_str(&rewrite(&input[call.start()..open], &arguments)?);
            start = end + 1;
        }
        output.push_str(&input[start..]);
        Ok(output)
    }
    visit(input, calls, &rewrite, 0)
}

/// Visit original groups and complete calls once, lowering their children first.
/// Model replacements are terminal; ordinary SDK wording hooks are not invoked.
pub(crate) fn rewrite_models(
    input: &str,
    calls: &regex::Regex,
    call: impl Fn(&str, &str, crate::ModelPosition) -> crate::Outcome,
    model: impl Fn(&str, crate::ModelPosition) -> crate::Outcome,
) -> Result<String, crate::Error> {
    fn checked(value: String) -> Result<String, crate::Error> {
        if value.trim().is_empty() || value.len() > 4096 {
            Err(crate::Error("invalid_expression".into()))
        } else {
            Ok(value)
        }
    }
    fn visit(
        input: &str,
        calls: &regex::Regex,
        call: &impl Fn(&str, &str, crate::ModelPosition) -> crate::Outcome,
        model: &impl Fn(&str, crate::ModelPosition) -> crate::Outcome,
        position: crate::ModelPosition,
        depth: usize,
    ) -> Result<String, crate::Error> {
        use crate::ModelPosition::{Operand, Standalone};
        if depth > 64 {
            return Err(crate::Error("expression_too_deep".into()));
        }
        if input.trim().is_empty() {
            return Ok(input.into());
        }
        let ranges = groups(input).ok_or_else(|| crate::Error("invalid_expression".into()))?;
        let mut output = String::new();
        let mut cursor = 0;
        let mut terminal_whole = false;
        for range in ranges {
            let open = range.start - 1;
            let callee = calls
                .find_iter(&input[..range.start])
                .last()
                .filter(|found| found.end() == range.start && found.start() >= cursor);
            let start = callee.as_ref().map_or(open, |found| found.start());
            let whole =
                input[..start].trim().is_empty() && input[range.end + 1..].trim().is_empty();
            let child_position = if callee.is_none() && whole {
                position
            } else {
                Operand
            };
            let inner = visit(
                &input[range.clone()],
                calls,
                call,
                model,
                child_position,
                depth + 1,
            )?;
            let replacement = if let Some(callee) = callee {
                let call_position = if whole { position } else { Operand };
                match call(&input[callee.start()..open], &inner, call_position) {
                    Some(result) => {
                        terminal_whole |= whole;
                        let value = checked(result?)?;
                        let original = format!("{}({inner})", &input[callee.start()..open]);
                        if call_position == Standalone || value == original {
                            value
                        } else {
                            format!("({value})")
                        }
                    }
                    None => format!("{}({inner})", &input[start..open]),
                }
            } else if whole && position == Standalone && inner != input[range.clone()] {
                terminal_whole = true;
                inner
            } else {
                format!("({inner})")
            };
            output.push_str(&input[cursor..start]);
            output.push_str(&replacement);
            if output.len() > 4096 {
                return Err(crate::Error("invalid_expression".into()));
            }
            cursor = range.end + 1;
        }
        output.push_str(&input[cursor..]);
        let output = checked(output)?;
        if terminal_whole {
            return Ok(output);
        }
        match model(&output, position) {
            Some(result) => checked(result?),
            None => Ok(output),
        }
    }
    visit(
        input,
        calls,
        &call,
        &model,
        crate::ModelPosition::Standalone,
        0,
    )
}

/// Lower whole family requests, then visit only original parenthesized slices.
/// A successful replacement is final for this walk: its generated formula must
/// be handled by the normal expression evaluator, rather than scanned as prose.
pub(crate) fn rewrite_groups(
    input: &str,
    rewrite: impl Fn(&str) -> crate::Outcome,
) -> crate::Outcome {
    fn visit(
        input: &str,
        rewrite: &impl Fn(&str) -> crate::Outcome,
        depth: usize,
    ) -> crate::Outcome {
        if depth > 64 {
            return Some(Err(crate::Error("expression_too_deep".into())));
        }
        if let Some(result) = rewrite(input) {
            return Some(result);
        }
        let mut output = String::new();
        let mut cursor = 0;
        for range in groups(input)? {
            match visit(&input[range.clone()], rewrite, depth + 1) {
                Some(Ok(replacement)) => {
                    output.push_str(&input[cursor..range.start]);
                    output.push_str(&replacement);
                    cursor = range.end;
                }
                Some(Err(error)) => return Some(Err(error)),
                None => {}
            }
        }
        if cursor == 0 {
            return None;
        }
        output.push_str(&input[cursor..]);
        Some(Ok(output))
    }
    visit(input, &rewrite, 0)
}