use super::syntax;
mod operations;
mod questions;
mod rates;
mod reports;
mod transactions;
mod travel;
use crate::{Calculator, Context, Error, Outcome, Plugin, number, re};
pub struct Language {
fuel_calculator: Calculator,
units: super::units::Units,
}
impl Default for Language {
fn default() -> Self {
let compositions = super::compositions::Compositions::default();
let units = compositions.units.clone();
let fuel_calculator =
super::standard(Calculator::empty(Context::default()).with_plugin(compositions));
Self {
units,
fuel_calculator,
}
}
}
impl Plugin for Language {
fn rewrite(&self, input: &str, context: &Context) -> Outcome {
if let Some(result) = reports::rewrite(input) {
return Some(result);
}
let folded = re!(r"[a-zA-ZµμΩω]+").replace_all(input, |c: ®ex::Captures| {
let lower = c[0].to_ascii_lowercase();
let after = input[c.get(0).unwrap().end()..].trim_start();
let article = &c[0] == "A"
&& !after.is_empty()
&& !after.starts_with(['+', '-', '*', '/', '^', ')', ','])
&& !re!(r"(?i)^(?:in|to|into|as|per)\b").is_match(after);
if !article && self.units.units.iter().any(|unit| unit.symbol == c[0]) {
return c[0].to_string();
}
match (self.units.unit(&c[0]), self.units.unit(&lower)) {
(Some(_), None) => c[0].to_string(),
(Some(a), Some(b)) if a.dimension != b.dimension || a.scale != b.scale => {
c[0].to_string()
}
_ => lower,
}
});
let mut expression = folded.trim_end_matches(['?', '.']).to_string();
let quantity_output = operations::annotation(&expression).is_some_and(|formatted| {
formatted
.rsplit_once(" in ")
.is_some_and(|(_, target)| self.units.unit(target).is_some())
});
if super::integer_queries::IntegerQueries::recognizes(input)
&& !super::predicates::recognized(input)
&& !quantity_output
{
return None;
}
if re!(r"^square root of (?:negative |-)\d").is_match(&expression) {
return Some(Err(Error("internal_error".into())));
}
let fuel_request = re!(r"^(?:a )?\w+ travels (.+) on (.+); what's its fuel use per (.+)$")
.is_match(&expression)
|| re!(r"^how many (.+) per (.+) if (.+) covers (.+)$").is_match(&expression);
if !fuel_request {
expression = match lower(&expression, &self.units, 0) {
Ok(expression) => expression,
Err(error) => return Some(Err(error)),
};
}
if re!(r"^(?:mean|average|median|mode|range|standard deviation) (?:of )?.*[,;]\s*(?:and)?$")
.is_match(&expression)
{
return Some(Err(Error("invalid_expression".into())));
}
if let Some(c) = re!(r"^(?:mean|average|median|mode|range|sum|total|min|max|standard deviation)(?: of |\()([^()]+)\)?$").captures(&expression)
&& c[1].replace(" and ", ", ").split(',').any(|argument| {
super::calendar::date(argument.trim(), context).is_some()
})
{
return Some(Err(Error("invalid_expression".into())));
}
if expression == input {
return None;
}
if super::arithmetic::operators(&expression).is_none()
|| expression.trim_end().ends_with(['+', '-', '*', '/', '^'])
{
return Some(Err(Error("invalid_expression".into())));
}
Some(Ok(expression))
}
fn evaluate(&self, input: &str, context: &Context) -> Outcome {
if let Some(result) = reports::evaluate(input) {
return Some(result);
}
if let Some(c) =
re!(r"^(?:a )?\w+ travels (.+) on (.+); what's its fuel use per (.+)$").captures(input)
{
let units = super::units::Units::default();
let volume = units.quantity(&c[2])?;
let calculation = format!(
"({}) / ({}) * ({}) in {}",
&c[2], &c[1], &c[3], volume.unit.symbol
);
return Some(
self.fuel_calculator
.evaluate_with(&calculation, context)
.map(|answer| format!("{}/{}", answer.display, &c[3])),
);
}
if let Some(c) = re!(r"^how many (.+) per (.+) if (.+) covers (.+)$").captures(input) {
let calculation = format!("({}) / ({}) * ({}) in {}", &c[3], &c[4], &c[2], &c[1]);
return Some(
self.fuel_calculator
.evaluate_with(&calculation, context)
.map(|answer| format!("{}/{}", answer.display, &c[2])),
);
}
if let Some(result) = list(input) {
return Some(result);
}
if let Some(c) = re!(r"^(?:workdays|weekdays) (?:between|from) (.+) (and|to|through) (.+)$")
.captures(input)
{
use chrono::{Datelike, Days, Weekday};
let mut start = super::calendar::date(&c[1], context)?;
let mut end = super::calendar::date(&c[3], context)?;
if &c[2] == "through" {
end = end.checked_add_days(Days::new(1))?;
}
let sign = if start > end {
std::mem::swap(&mut start, &mut end);
-1
} else {
1
};
if (end - start).num_days() > 100000 {
return Some(Err(Error("interval_too_large".into())));
}
let mut count: i64 = 0;
while start < end {
if !matches!(start.weekday(), Weekday::Sat | Weekday::Sun) {
count += sign;
}
start = start.checked_add_days(Days::new(1))?;
}
return Some(Ok(format!(
"{count} workday{}",
if count.abs() == 1 { "" } else { "s" }
)));
}
None
}
}
fn superscript_digits(input: &str) -> String {
input
.chars()
.map(|ch| {
let index = "⁻⁺⁰¹²³⁴⁵⁶⁷⁸⁹".chars().position(|c| c == ch).unwrap();
"-+0123456789".as_bytes()[index] as char
})
.collect()
}
fn rewrite(input: &str, units: &super::units::Units) -> String {
let mut s = input.split_whitespace().collect::<Vec<_>>().join(" ");
s = re!(r"^(?:please )?(?:what is (?:the date )?|what temperature is |how much is |calculate |evaluate |compute |work out |express |turn |what date (?:is|falls) |when is |find (?:the )?value of |find (?:the )?)(?:the )?")
.replace(&s, "")
.into_owned();
s = operations::division_operands(&s);
s = s
.replace("per cent", "%")
.replace(", divided by ", " / ")
.replace("negative ", "-")
.replace("take away", "minus")
.replace('÷', "/")
.replace(", expressed in ", " in ")
.replace(" expressed in ", " in ");
s = re!(r"\bpercent(?:age)?\b")
.replace_all(&s, "%")
.into_owned();
s = re!(r"([+-]?(?:[0-9]+(?:\.[0-9]+)?|\.[0-9]+))\s*[×*]\s*10([⁻⁺⁰¹²³⁴⁵⁶⁷⁸⁹]+)")
.replace_all(&s, |c: ®ex::Captures| {
let exponent = superscript_digits(&c[2]);
format!("{}e{exponent}", &c[1])
})
.into_owned();
s = re!(r"(\b[0-9]+(?:\.[0-9]+)?|\.[0-9]+|\))([⁻⁺]?[⁰¹²³⁴⁵⁶⁷⁸⁹]+)")
.replace_all(&s, |c: ®ex::Captures| {
format!("{}^({})", &c[1], superscript_digits(&c[2]))
})
.into_owned();
s = re!(r"(\d)\s+%").replace_all(&s, "$1%").into_owned();
s = syntax::word_operators(&s);
s = re!(r"\b(january|february|march|april|may|june|july|august|september|october|november|december) (\d{1,2})\b(?:, (\d{4}))?")
.replace_all(&s, "$2 $1 $3").into_owned();
s = s.split_whitespace().collect::<Vec<_>>().join(" ");
s = re!(r"\b(?:monday|tuesday|wednesday|thursday|friday|saturday|sunday) (\d)")
.replace_all(&s, "$1")
.into_owned();
s = s.replace(", and ", ", ").replace(" an hour", "/hour");
s = re!(r"^(mean|median|average|range|mode) for ")
.replace(&s, "$1 of ")
.into_owned();
for (word, value) in [
("zero", "0"),
("one", "1"),
("two", "2"),
("three", "3"),
("four", "4"),
("five", "5"),
("six", "6"),
("seven", "7"),
("eight", "8"),
("nine", "9"),
("ten", "10"),
] {
s = s
.split_whitespace()
.map(|token| if token == word { value } else { token })
.collect::<Vec<_>>()
.join(" ");
}
s = operations::fractions(&s);
s = re!(r"\b(?:the )?(?:entire amount|whole quantity|combined amount|combined distance|total duration|full mass|total price|whole volume|total distance|whole bill of|full combined cost of|quantity|whole|entire) ")
.replace_all(&s, "").into_owned();
s = re!(r"(?P<currency>[$€£¥][\d.,]+) balance\b")
.replace_all(&s, "$currency")
.into_owned();
if let Some(expression) = operations::annotation(&s) {
return expression;
}
for family in [
rates::rewrite,
transactions::rewrite,
operations::rewrite,
questions::rewrite,
travel::rewrite,
] {
let next = family(&s, units);
if next != s {
return next;
}
}
if let Some(c) = re!(r"^(.+), in (.+)$").captures(&s)
&& units.unit(&c[2]).is_some()
{
return format!("({}) in {}", &c[1], &c[2]);
}
let s = re!(r"(?P<currency>[$€£¥][\d.,]+) bill\b").replace_all(&s, "$currency");
percentage(&s, units)
}
fn list(input: &str) -> Option<Result<String, Error>> {
let c = re!(r"^(mode|range)(?: of)? (.+)$").captures(input)?;
let tail = c[2].replace(" and ", ",");
let mut values = tail
.split(',')
.map(|s| super::arithmetic::eval(s.trim()))
.collect::<Option<Vec<_>>>();
let result = (|| {
let values = values.as_mut().filter(|v| !v.is_empty())?;
values.sort_by(f64::total_cmp);
if &c[1] == "range" {
return Some(number(values.last()? - values.first()?));
}
let mut groups: Vec<(f64, usize)> = vec![];
for value in values.iter() {
if let Some((last, count)) = groups.last_mut()
&& last == value
{
*count += 1;
} else {
groups.push((*value, 1));
}
}
let most = groups.iter().map(|(_, n)| *n).max()?;
Some(
groups
.iter()
.filter(|(_, n)| *n == most)
.map(|(v, _)| number(*v))
.collect::<Vec<_>>()
.join(", "),
)
})();
Some(result.ok_or_else(|| Error("invalid_expression".into())))
}
fn lower(input: &str, units: &super::units::Units, depth: usize) -> Result<String, Error> {
if depth > 64 {
return Err(Error("expression_too_deep".into()));
}
let mut expression = input.to_string();
for _ in 0..32 {
let next = rewrite(&expression, units);
if next == expression {
break;
}
expression = next;
}
let mut output = String::new();
let mut start = 0;
for group in syntax::groups(&expression).ok_or_else(|| Error("invalid_expression".into()))? {
output.push_str(&expression[start..group.start]);
output.push_str(&lower(&expression[group.clone()], units, depth + 1)?);
start = group.end;
}
output.push_str(&expression[start..]);
Ok(output)
}
fn percentage(input: &str, units: &super::units::Units) -> String {
let mut output = String::new();
let mut start = 0;
let groups = syntax::groups(input).unwrap_or_default();
for c in re!(r"([+-]?(?:\d[\d,]*(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?)% (of|off|on|added to) ")
.captures_iter(input)
{
let m = c.get(0).unwrap();
if m.start() < start || groups.iter().any(|group| group.contains(&m.start())) {
continue;
}
let mut percent_start = m.start();
let mut rate = &c[1];
if rate.starts_with(['+', '-'])
&& input[..percent_start]
.trim_end()
.chars()
.next_back()
.is_some_and(|c| c.is_alphanumeric() || matches!(c, ')' | '%'))
{
percent_start += 1;
rate = &rate[1..];
}
let Ok(p) = rate.replace(',', "").parse::<f64>() else {
continue;
};
let p = p / 100.0;
let multiplier = match &c[2] {
"off" => 1.0 - p,
"on" | "added to" => 1.0 + p,
_ => p,
};
let rest = &input[m.end()..];
if operations::sum_phrase(rest) {
output.push_str(&input[start..percent_start]);
output.push_str(&format!("({}) * ({rest})", number(multiplier)));
start = input.len();
break;
}
let operand = if rest.starts_with('(') {
syntax::groups(rest)
.and_then(|groups| groups.into_iter().next())
.map(|range| range.end + 1)
} else if let Some(number) =
re!(r"^[$€£¥]?[+-]?(?:\d[\d,]*(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?").find(rest)
{
let tail = &rest[number.end()..];
let unit = syntax::unit_prefix(tail, |unit| {
units.unit(unit).is_some() || super::named_quantities::recognizes(unit)
})
.unwrap_or(0);
Some(number.end() + unit)
} else {
None
};
let Some(end) = operand else {
continue;
};
output.push_str(&input[start..percent_start]);
output.push_str(&format!("({}) * ({})", number(multiplier), &rest[..end]));
start = m.end() + end;
}
output.push_str(&input[start..]);
output
}