nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
//! Parse compound unit factors independently of quantities and their dimensions.
//! Callers resolve each leaf through their own physical and named unit registry.
use super::syntax;

/// Join adjacent registered leaves only inside a caller-selected unit suffix.
/// Longest matching leaves preserve multiword aliases such as degrees Celsius.
pub(super) fn explicit_products(input: &str, recognizes: impl Fn(&str) -> bool) -> String {
    crate::re!(r"[^*/·⋅()^]+")
        .replace_all(input, |capture: &regex::Captures<'_>| {
            let mut remaining = capture[0].trim();
            let mut leaves = Vec::new();
            while !remaining.is_empty() {
                let Some(end) = syntax::unit_prefix(remaining, &recognizes) else {
                    return capture[0].to_string();
                };
                if end == 0 {
                    return capture[0].to_string();
                }
                leaves.push(remaining[..end].trim());
                remaining = remaining[end..].trim_start();
            }
            leaves.join("*")
        })
        .into_owned()
}

pub(super) fn factors(input: &str, recognizes: impl Fn(&str) -> bool) -> Option<Vec<(String, i8)>> {
    parse(input, &recognizes, 0)
}

fn parse(
    input: &str,
    recognizes: &impl Fn(&str) -> bool,
    depth: usize,
) -> Option<Vec<(String, i8)>> {
    if depth > 64 {
        return None;
    }
    let input = input.trim();
    if input == "1" {
        return Some(vec![]);
    }
    if recognizes(input) {
        return Some(vec![(input.into(), 1)]);
    }
    let inner = syntax::ungroup(input);
    if inner != input {
        return parse(inner, recognizes, depth + 1);
    }
    let mut nesting = 0i32;
    let mut product = None;
    let mut power = None;
    for (index, character) in input.char_indices() {
        match character {
            '(' => nesting += 1,
            ')' => nesting -= 1,
            '*' | '·' | '⋅' | '/' if nesting == 0 => product = Some((index, character)),
            '^' if nesting == 0 => power = Some(index),
            _ => {}
        }
        if nesting < 0 {
            return None;
        }
    }
    (nesting == 0).then_some(())?;
    if let Some((index, operator)) = product {
        let mut left = parse(&input[..index], recognizes, depth + 1)?;
        let right = parse(&input[index + operator.len_utf8()..], recognizes, depth + 1)?;
        for (unit, exponent) in right {
            left.push((
                unit,
                if operator == '/' {
                    exponent.checked_neg()?
                } else {
                    exponent
                },
            ));
        }
        return Some(left);
    }
    let (base, exponent) = if let Some(index) = power {
        (
            &input[..index],
            input[index + 1..].trim().parse::<i8>().ok()?,
        )
    } else if let Some(base) = input.strip_suffix('²') {
        (base, 2)
    } else {
        (input.strip_suffix('³')?, 3)
    };
    parse(base, recognizes, depth + 1)?
        .into_iter()
        .map(|(unit, power)| Some((unit, power.checked_mul(exponent)?)))
        .collect()
}