nlcalc 0.1.0

Plugin-based natural language calculator for Rust and the command line
Documentation
use crate::plugins::units::Units;
use crate::{Span, re};
/// A presentation adapter returns UTF-8 byte ranges into the unchanged source.
pub trait Highlighter: Send + Sync {
    fn highlight(&self, input: &str) -> Vec<Span>;
}
#[derive(Default)]
pub struct SyntaxHighlighter {
    pub units: Units,
}
impl Highlighter for SyntaxHighlighter {
    fn highlight(&self, input: &str) -> Vec<Span> {
        let mut spans = vec![];
        let mut pos = 0;
        while pos < input.len() {
            let rest = &input[pos..];
            if let Some(c) = re!(r"^([a-zA-Z]+)\^[23]\b").captures(rest)
                && self
                    .units
                    .unit(&c[1])
                    .is_some_and(|unit| unit.dimension == [1, 0, 0, 0, 0, 0, 0, 0])
            {
                let end = c.get(0).unwrap().end();
                spans.push(Span {
                    start: pos,
                    end: pos + end,
                });
                pos += end;
                continue;
            }
            if let Some(m) = re!(r"(?i)^utc[+-]\d{1,2}\b").find(rest) {
                spans.push(Span {
                    start: pos,
                    end: pos + m.end(),
                });
                pos += m.end();
                continue;
            }
            if let Some(m) = re!(r"^\d+(?:\.\d+)?[kKMGТT]\b").find(rest) {
                spans.push(Span {
                    start: pos,
                    end: pos + m.end(),
                });
                pos += m.end();
                continue;
            }

            if let Some(c) =
                re!(r"^(?:sqrt|ln|log|sin|cos|tan|abs|exp)\(([a-z]+)(?:\^[\d.]+)?\)").captures(rest)
                && !word(&c[1], &self.units, input, pos)
            {
                pos += c.get(0).unwrap().end();
                continue;
            }
            if let Some(m) = re!(r"(?i)^\d{1,2}:\d{2}:\d{2} (?:am|pm)").find(rest) {
                spans.push(Span {
                    start: pos,
                    end: pos + m.end(),
                });
                pos += m.end();
                continue;
            }
            // Standard date components include a complete clock following a
            // space-separated ISO date. Standalone durations and frame clocks
            // keep their existing separate numeric tokens.
            if re!(r"\b\d{4}-\d{2}-\d{2} +$").is_match(&input[..pos])
                && let Some(m) = re!(r"^\d{1,2}:\d{2}:\d{2}(?:\.\d+)?\b").find(rest)
                && !rest[m.end()..].starts_with(':')
                && chrono::NaiveTime::parse_from_str(m.as_str(), "%H:%M:%S%.f").is_ok()
            {
                spans.push(Span {
                    start: pos,
                    end: pos + m.end(),
                });
                pos += m.end();
                continue;
            }
            if input[..pos]
                .trim_end()
                .chars()
                .last()
                .is_none_or(|c| "()+-*/^".contains(c))
                && let Some(m) = re!(r"(?i)^minus \d+(?:\.\d+)?").find(rest)
            {
                spans.push(Span {
                    start: pos,
                    end: pos + m.end(),
                });
                pos += m.end();
                continue;
            }
            let ch = rest.chars().next().unwrap();
            if ch.is_whitespace() {
                pos += ch.len_utf8();
                continue;
            }
            if matches!(ch, 'x' | 'X') && input[..pos].ends_with(|c: char| c.is_ascii_digit()) {
                pos += 1;
                continue;
            }
            if ch == '"' && input.matches('"').count() >= 2 {
                pos += 1;
                continue;
            }
            if ch == '-'
                && rest[1..].starts_with(' ')
                && (input[..pos].ends_with('-') || input[..pos].trim_end().ends_with(')'))
                && !re!(r"(?i)^- +\d{1,2} (?:january|february|march|april|may|june|july|august|september|october|november|december)\b").is_match(rest)
                && let Some(m) = re!(r"^- +\d+").find(rest)
            {
                spans.push(Span {
                    start: pos,
                    end: pos + m.end(),
                });
                pos += m.end();
                continue;
            }
            if input[..pos].ends_with('\'') && rest.chars().all(|c| c.is_ascii_digit() || c == '.')
            {
                break;
            }
            // Standard decimal tokens retain compact comma groups even when their
            // lengths are invalid for thousands grouping; evaluation owns validity.
            if let Some(m) = re!(r"^[+−-]?(?:0x[\da-fA-F]{1,16}\b|0b[01]+|0o[0-7]+|\d[\d_]*(?:,\d+)*(?:\.\d+)?(?:[eE][+-]?\d+)?|\.\d+|[½¼¾π])").find(rest) {
                let end = pos + m.end();
                let mut start = pos;
                if matches!(ch, '-' | '−' | '+') {
                    let before = &input[..pos];
                    let previous = before.trim_end().chars().last();
                    let zero = rest[..m.end()]
                        .trim_start_matches(['-', '−', '+'])
                        .parse::<f64>()
                        .is_ok_and(|n| n == 0.0);
                    // Standard treats a minus following a group as the next signed value.
                    let binary = previous.is_some_and(|c| c.is_ascii_digit() || (c == ')' && ch != '-'));
                    if binary
                        || before.ends_with(char::is_alphabetic)
                        || zero
                        || rest[m.end()..].starts_with(':')
                        || (ch == '+' && before.ends_with("after "))
                    {
                        start += ch.len_utf8();
                    }
                }
                spans.push(Span { start, end });
                pos = end;
                continue;
            }
            let mut matched = None;
            for (end, _) in rest
                .char_indices()
                .skip(1)
                .chain(std::iter::once((rest.len(), ' ')))
                .take_while(|(end, _)| *end <= 64)
            {
                let text = &rest[..end];
                let next = rest[end..].chars().next();
                if next.is_some_and(|c| c.is_alphabetic() || c == '²' || c == '³' || c == '\\') {
                    continue;
                }
                if word(text, &self.units, input, pos) {
                    matched = Some(end);
                }
            }
            if let Some(end) = matched {
                spans.push(Span {
                    start: pos,
                    end: pos + end,
                });
                pos += end;
                continue;
            }
            if ch == '%'
                && !rest[1..]
                    .trim_start()
                    .starts_with(|c: char| c.is_ascii_digit() || c == '(' || c == '-')
            {
                spans.push(Span {
                    start: pos,
                    end: pos + 1,
                });
            }
            if ch.is_alphabetic() {
                let end = rest
                    .find(|c: char| !c.is_alphanumeric())
                    .unwrap_or(rest.len());
                pos += end;
            } else {
                pos += ch.len_utf8();
            }
        }
        spans
    }
}
fn word(text: &str, units: &Units, input: &str, pos: usize) -> bool {
    if text.trim() != text || text.starts_with("decimal ") || text.starts_with("square nautical ") {
        return false;
    }
    if input[..pos].trim_end().to_lowercase().ends_with("into")
        && !re!(r"(?i)^convert ").is_match(input.trim_start())
    {
        // Standard treats an unprefixed `into` target as a comment.
        return false;
    }
    let s = text.to_lowercase();
    if let Some(base) = text.strip_suffix(['²', '³'])
        && units
            .unit(base)
            .is_some_and(|unit| unit.dimension != [1, 0, 0, 0, 0, 0, 0, 0])
        && !units.units.iter().any(|unit| {
            unit.aliases
                .split('|')
                .any(|alias| alias.eq_ignore_ascii_case(text))
        })
    {
        return false;
    }
    if input[..pos].trim_end().ends_with("calendar")
        && matches!(
            s.as_str(),
            "day" | "days" | "week" | "weeks" | "month" | "months" | "year" | "years"
        )
        && !input[pos + text.len()..].trim_start().starts_with("to ")
    {
        return false;
    }
    if matches!(
        s.as_str(),
        "monday" | "tuesday" | "wednesday" | "thursday" | "friday" | "saturday" | "sunday" | "now"
    ) || re!(r"^(next|last|this) (week|month|year)$").is_match(&s)
    {
        return true;
    }
    if crate::plugins::holidays::holiday(&s, 2000).is_some() {
        return true;
    }
    if s == "time" && re!(r"(?:unix |lap )$").is_match(&input[..pos]) {
        return false;
    }
    if matches!(s.as_str(), "dpi" | "weekday" | "weekdays") {
        return true;
    }
    if s == "min" && pos == 0 {
        return false;
    }
    if let Some(u) = units.unit(text)
        && (u.symbol == "L/100km"
            || u.dimension == [1, 0, -2, 0, 0, 0, 0, 0]
            || u.dimension == [0, 0, -1, 0, 0, 0, 0, 1]
            || (u.dimension == [0, 0, -1, 0, 1, 0, 0, 0] && s.contains(" per ")))
    {
        return true;
    }
    if s.contains('/') || s.contains(" per ") {
        return matches!(
            s.as_str(),
            "m/s"
                | "km/h"
                | "kilometers per hour"
                | "meters per second"
                | "feet per second"
                | "miles per hour"
        );
    }
    if re!(r"\s\d").is_match(text) {
        return false;
    }
    if s == "in" {
        let scope = input[..pos].rsplit(['(', ')']).next().unwrap_or("");
        let imperial = re!(r"(?i)(?:^|[^a-z])(?:ft|foot|feet)\b").is_match(scope);
        return input[..pos]
            .trim_end()
            .ends_with(|c: char| c.is_ascii_digit())
            && (input[pos + text.len()..].trim_start().starts_with("to ")
                || input[pos + text.len()..].trim_start().starts_with("in ")
                || imperial
                    && input[pos + text.len()..]
                        .trim_start()
                        .chars()
                        .next()
                        .is_none_or(|ch| matches!(ch, '+' | '-' | '*' | '/' | ')')));
    }
    if units.unit(text).is_some() {
        if input.trim_start().starts_with("convert ")
            && input[..pos].contains(" into ")
            && super::plugins::syntax::word_operators(input).contains(['+', '*', '/'])
        {
            return false;
        }
        return true;
    }
    if matches!(
        s.as_str(),
        "pixels"
            | "rpm"
            | "fps"
            | "frame"
            | "frames"
            | "business days"
            | "workdays"
            | "rem"
            | "px"
            | "ppi"
            | "aud"
            | "usd"
            | "eur"
            | "gbp"
            | "jpy"
            | "btc"
            | "$"
            | "€"
            | "£"
            | "¥"
            | "₿"
            | "australian dollars"
            | "us dollars"
            | "dollars"
            | "euros"
            | "yen"
            | "n"
            | "s"
            | "′"
            | "″"
            | "'"
            | "\""
    ) {
        return true;
    }
    if matches!(
        s.as_str(),
        "january"
            | "february"
            | "march"
            | "april"
            | "may"
            | "june"
            | "july"
            | "august"
            | "september"
            | "october"
            | "november"
            | "december"
            | "am"
            | "pm"
            | "midnight"
            | "noon"
            | "today"
            | "tomorrow"
            | "yesterday"
            | "time"
    ) {
        return true;
    }
    if matches!(
        s.as_str(),
        "one"
            | "two"
            | "three"
            | "four"
            | "five"
            | "six"
            | "seven"
            | "eight"
            | "nine"
            | "ten"
            | "one hundred"
            | "twenty-one"
            | "pi"
    ) {
        return s == "pi" || !input.contains(" times ");
    }
    if s == "dollar" {
        return true;
    }
    if matches!(s.as_str(), "cent" | "cents") {
        return !input[..pos].ends_with("per ");
    }
    (!s.ends_with(" time") && crate::plugins::time::zone(&s).is_some())
        || crate::plugins::time::abbreviation(&s).is_some()
        || s == "tokyo time"
}