use super::{finance::Finance, syntax, units::Units};
mod registry;
mod standard;
use crate::{Context, Error, Outcome, Plugin, re};
use chrono::TimeZone;
pub use standard::StandardRates;
pub(crate) use standard::standard_comparison_operand;
pub(crate) use standard::standard_grouped_comments;
pub(crate) use standard::standard_temporal_units;
pub struct Compositions {
pub(super) units: Units,
}
impl Default for Compositions {
fn default() -> Self {
Self {
units: registry::extended(Units::default()),
}
}
}
impl Plugin for Compositions {
fn evaluate(&self, input: &str, context: &Context) -> Outcome {
if input
.get(..10)
.is_some_and(|date| chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d").is_ok())
&& super::time::Time::default()
.evaluate(input, context)
.is_some()
{
return None;
}
if let Some(operators) = super::arithmetic::operators(input)
&& operators.iter().any(|(index, operator)| {
matches!(operator, '*' | '/')
&& super::calendar::date(&input[..*index], context).is_some()
})
{
return Some(Err(Error("invalid_expression".into())));
}
if let Some((source, target)) = syntax::split_last(input, syntax::CONVERSIONS)
&& matches!(target, "percent" | "percentage" | "%")
&& super::named_quantities::has_function(source)
{
return Some(self.quantity_value(source, "1", context).and_then(|value| {
let percent = value * 100.0;
if percent.is_finite() {
Ok(format!("{}%", crate::number(percent)))
} else {
Err(Error("numeric_overflow".into()))
}
}));
}
if let Some(c) = re!(r"^(.+) is what % of (.+)$").captures(input)
&& (super::named_quantities::has_function(&c[1])
|| super::named_quantities::has_function(&c[2]))
{
return Some((|| {
let a = self.quantity_value(&c[1], "1", context)?;
let b = self.quantity_value(&c[2], "1", context)?;
if b == 0.0 {
return Err(Error("division_by_zero".into()));
}
let percent = a / b * 100.0;
if !percent.is_finite() {
return Err(Error("numeric_overflow".into()));
}
Ok(format!("{}%", crate::number(percent)))
})());
}
if input.contains(" is what % ") || input.ends_with(" as %") {
return super::percentages::Percentages.evaluate(input, context);
}
if let Some((_, target)) = syntax::split_last(input, syntax::CONVERSIONS)
&& matches!(
target,
"fraction" | "frac" | "a fraction" | "percent" | "percentage" | "%"
)
{
return None;
}
if let Some(c) = re!(r"^(.+) in hours and minutes$").captures(input)
&& let Some(seconds) = super::time::Time::default().seconds(&c[1])
{
return Some(Ok(super::time::span(seconds, 3600.0)));
}
let input = self.normalize_expression(input);
let input = input.as_str();
if let Some(c) = re!(r"(?i)^convert (.+)$").captures(input) {
let expression = self.prepare(&c[1], context, 0);
return Some(expression.and_then(|s| {
self.calculate(&s, context).unwrap_or_else(|| {
Finance
.evaluate(&s, context)
.unwrap_or_else(|| Err(Error("invalid_expression".into())))
})
}));
}
if let Some(c) = re!(r"(?i)^([a-z]{3}) from (.+)$").captures(input) {
return Finance.evaluate(&format!("{} to {}", &c[2], &c[1]), context);
}
if !input.contains('/')
&& (!re!(r" (?:for|over|during|until|till|between) ").is_match(input)
|| re!(r"^(?:(?:days?|weeks?|months?|years?)(?: and (?:days?|weeks?|months?|years?))?|workdays?|weekdays?|business days?|duration) (?:between|from|until|till) ")
.is_match(input))
&& let Some(result) = super::calendar::Calendar.evaluate_expression(input, context)
{
return Some(result);
}
let has_quantity = re!(r"[a-zA-Z]+|[$€£¥]").find_iter(input).any(|m| {
self_unit(&self.units, m.as_str()) || matches!(m.as_str(), "$" | "€" | "£" | "¥")
});
let scalar_expression = re!(r"^[0-9eE.,\s()+*/^−-]+$").is_match(input);
let typed_arithmetic = scalar_expression
|| super::named_quantities::has_function(input)
|| syntax::split_last(input, syntax::CONVERSIONS).is_some_and(|(source, target)| {
self_unit(&self.units, target)
&& super::named_quantities::recognizes_quantity(source, &self.units, context)
})
|| has_quantity
&& (input.contains(['*', '+', '-', '(']) || syntax::ungroup(input) != input);
if let Some((unit, _)) = syntax::split_last(input, &[" until ", " till "])
&& self.units.unit(unit).is_some()
{
return None;
}
if !input.contains(['/', '·', '⋅'])
&& !typed_arithmetic
&& !re!(r" (?:for|over|during|until|till) ").is_match(input)
{
return standard_grouped_comments(input)
.map(|_| Err(Error("invalid_expression".into())));
}
if let Some((distance, speed)) = syntax::split_last(input, &[" in "])
&& let Some(a) = self.units.quantity(distance)
&& let Some(b) = self.units.quantity(speed)
&& a.unit.dimension == [1, 0, 0, 0, 0, 0, 0, 0]
&& b.unit.dimension == [1, 0, -1, 0, 0, 0, 0, 0]
{
if b.base == 0.0 {
return Some(Err(Error("division_by_zero".into())));
}
return Some(Ok(super::time::span(a.base / b.base, 3600.0)));
}
match self.prepare(input, context, 0) {
Ok(expression) => self.calculate(&expression, context),
Err(error) => Some(Err(error)),
}
}
}
impl Compositions {
pub(crate) fn quantity_order(
&self,
left: &str,
right: &str,
context: &Context,
) -> Result<std::cmp::Ordering, Error> {
let left = self.prepare(&self.normalize_expression(left), context, 0)?;
let right = self.prepare(&self.normalize_expression(right), context, 0)?;
super::named_quantities::quantity_order(&left, &right, &self.units, context)
}
pub(crate) fn quantity_value(
&self,
input: &str,
reference: &str,
context: &Context,
) -> Result<f64, Error> {
let expression = self.prepare(&self.normalize_expression(input), context, 0)?;
super::named_quantities::quantity_value(&expression, reference, &self.units, context)
}
pub(crate) fn evaluate_money(&self, input: &str, context: &Context) -> Result<String, Error> {
let expression = self.prepare(&self.normalize_expression(input), context, 0)?;
super::named_quantities::validate_money(&expression, &self.units, context)?;
self.calculate(&expression, context)
.ok_or_else(|| Error("invalid_expression".into()))?
}
fn normalize_expression(&self, input: &str) -> String {
let input = syntax::word_operators(&input.split_whitespace().collect::<Vec<_>>().join(" "))
.replace("work hours", "hours")
.replace("work hour", "hour")
.replace(" per ", " / ")
.replace(" starting at ", " from ")
.replace(" starting ", " from ")
.replace(" beginning ", " from ");
normalize_unit_powers(&input, &self.units)
}
fn calculate(&self, expression: &str, context: &Context) -> Outcome {
let named = super::named_quantities::recognizes_expression(expression)
|| re!(r"[a-zA-Z]+")
.find_iter(expression)
.any(|word| super::named_quantities::extended_count(word.as_str()));
let result = super::named_quantities::evaluate_any(expression, &self.units, context);
if !named && matches!(&result, Some(Err(error)) if error.0 == "division_by_zero") {
return Some(Ok("Error: ∞".into()));
}
if !named && matches!(&result, Some(Err(error)) if error.0 == "unsupported_compound_unit") {
return self
.units
.evaluate(expression, context)
.filter(|result| result.is_ok());
}
result
}
fn prepare(&self, input: &str, context: &Context, depth: usize) -> Result<String, Error> {
if depth > 64 {
return Err(Error("expression_too_deep".into()));
}
let input = input.trim();
if input.ends_with(" until") || input.ends_with(" till") {
return Err(Error("invalid_endpoint".into()));
}
if let Some(endpoint) = input
.strip_prefix("until ")
.or_else(|| input.strip_prefix("till "))
{
return Ok(format!(
"{} seconds",
endpoint_seconds(syntax::ungroup(endpoint), context)?
));
}
if super::calendar::date(input, context).is_some()
|| super::named_quantities::recognizes_quantity(input, &self.units, context)
|| input.starts_with(char::is_alphabetic) && self_unit(&self.units, input)
{
return Ok(input.into());
}
let inner = syntax::ungroup(input);
if inner != input {
return Ok(format!("({})", self.prepare(inner, context, depth + 1)?));
}
if let Some((source, target)) = syntax::split_last(input, syntax::CONVERSIONS)
&& self_unit(&self.units, target)
{
return Ok(format!(
"{} in {target}",
self.prepare(source, context, depth + 1)?
));
}
if let Some((name, tail)) = input.split_once('(')
&& matches!(
name,
"abs" | "min" | "max" | "mean" | "sum" | "square" | "sqrt" | "round"
)
&& syntax::groups(input)
.is_some_and(|groups| groups.len() == 1 && groups[0].end + 1 == input.len())
&& let Some(arguments) = tail.strip_suffix(')')
{
let arguments = super::named_quantities::function_arguments(
arguments,
matches!(name, "abs" | "square" | "sqrt"),
)?
.into_iter()
.map(|argument| self.prepare(argument, context, depth + 1))
.collect::<Result<Vec<_>, _>>()?;
return Ok(format!("{name}({})", arguments.join(", ")));
}
if let Some((left, right)) = syntax::split_last(input, &[" from "]) {
if let Some((start, end)) =
syntax::split_last(right, &[" until ", " till ", " to ", " through "])
{
return self.window(left, start, end, context, depth);
}
if let Some((rate, end)) = syntax::split_last(left, &[" until ", " till "]) {
return self.window(rate, right, end, context, depth);
}
if let Some((rate, duration)) =
syntax::split_last(left, &[" for ", " over ", " during "])
{
let start = at_offset(context, endpoint_seconds(right, context)?)?;
return self.accumulate(rate, duration, &start, depth);
}
if let Some((start, duration)) = syntax::split_last(right, &[" for "]) {
let start = at_offset(context, endpoint_seconds(start, context)?)?;
return self.accumulate(left, duration, &start, depth);
}
}
if let Some((rate, window)) = syntax::split_last(input, &[" between "])
&& let Some((start, end)) = syntax::split_last(window, &[" and "])
{
return self.window(rate, start, end, context, depth);
}
if let Some((rate, endpoint)) = syntax::split_last(input, &[" until ", " till "]) {
let seconds = endpoint_seconds(syntax::ungroup(endpoint), context)?;
let rate = self.prepare(rate, context, depth + 1)?;
super::named_quantities::validate_rate(&rate, "1 second", &self.units, context)?;
return Ok(format!("({rate}) * ({seconds} seconds)"));
}
if let Some(&(index, operator)) = super::arithmetic::operators(input)
.ok_or_else(|| Error("invalid_expression".into()))?
.iter()
.rev()
.find(|(index, op)| "+-".contains(*op) && !input[..*index].trim_end().ends_with(','))
{
return Ok(format!(
"{} {operator} {}",
self.prepare(&input[..index], context, depth + 1)?,
self.prepare(&input[index + 1..], context, depth + 1)?
));
}
if let Some((rate, duration)) = syntax::split_last(input, &[" for ", " over ", " during "])
{
return self.accumulate(rate, duration, context, depth);
}
if let Some((duration, rate)) = syntax::split_last(input, &[" of "])
&& self
.units
.quantity(duration)
.is_some_and(|q| q.unit.dimension == [0, 0, 1, 0, 0, 0, 0, 0])
{
return Ok(format!(
"({}) * ({duration})",
self.prepare(rate, context, depth + 1)?
));
}
let mut output = String::new();
let mut start = 0;
for group in syntax::groups(input).ok_or_else(|| Error("invalid_expression".into()))? {
output.push_str(&input[start..group.start]);
output.push_str(&self.prepare(&input[group.clone()], context, depth + 1)?);
start = group.end;
}
output.push_str(&input[start..]);
Ok(normalize_rate(&output, &self.units))
}
fn accumulate(
&self,
rate: &str,
duration: &str,
context: &Context,
depth: usize,
) -> Result<String, Error> {
let duration =
self.prepare(&duration_expression(duration, context)?, context, depth + 1)?;
super::named_quantities::validate_quantity(&duration, &self.units, context)
.map_err(|_| Error("invalid_duration".into()))?;
let rate = self.prepare(rate, context, depth + 1)?;
super::named_quantities::validate_rate(&rate, &duration, &self.units, context)?;
Ok(format!("({rate}) * ({duration})"))
}
fn window(
&self,
rate: &str,
start: &str,
end: &str,
context: &Context,
depth: usize,
) -> Result<String, Error> {
let start_seconds = endpoint_seconds(start, context)?;
let end_seconds = if clock_expression(end)
|| end.contains("later")
|| end == "the same local time tomorrow"
{
start_seconds + endpoint_seconds(end, &at_offset(context, start_seconds)?)?
} else {
endpoint_seconds(end, context)?
};
if end_seconds < start_seconds {
return Err(Error("invalid_interval".into()));
}
let rate = rate
.trim_end_matches(" for the time")
.trim_end_matches(" for");
self.accumulate(
rate,
&format!("{} seconds", end_seconds - start_seconds),
context,
depth,
)
}
}
fn normalize_rate(input: &str, units: &Units) -> String {
for converter in [" in ", " to ", " as ", " into "] {
if let Some((source, target)) = input.rsplit_once(converter)
&& standard_unit(units, target)
{
return format!("{}{converter}{target}", normalize_rate(source, units));
}
}
re!(r"(?:/\s*|\s+per\s+)([a-zA-Z][a-zA-Z ]*)")
.replace_all(input, |c: ®ex::Captures| {
let unit_text = &c[1];
let end = syntax::unit_prefix(unit_text, |name| standard_unit(units, name));
end.map_or_else(
|| c[0].to_string(),
|end| format!("/1 {}{}", unit_text[..end].trim(), &unit_text[end..]),
)
})
.into_owned()
}
fn self_unit(units: &Units, name: &str) -> bool {
super::compound_units::factors(name, |part| {
units.unit(part).is_some()
|| units
.units
.iter()
.any(|unit| unit.symbol.eq_ignore_ascii_case(part))
|| super::named_quantities::recognizes(part)
|| super::named_quantities::extended_count(part)
})
.is_some()
}
fn standard_unit(units: &Units, name: &str) -> bool {
units.unit(name).is_some()
|| name
.split('/')
.all(|part| units.unit(part).is_some() || super::named_quantities::recognizes(part))
}
fn clock_expression(input: &str) -> bool {
let mut input = syntax::ungroup(input);
for _ in 0..64 {
if super::time::clock(input).is_some() {
return true;
}
let Some(operators) = super::arithmetic::operators(input) else {
return false;
};
let Some(&(index, _)) = operators.iter().rev().find(|(_, op)| "+-".contains(*op)) else {
return false;
};
if super::time::Time::default()
.seconds(&input[index + 1..])
.is_none()
{
return false;
}
input = syntax::ungroup(&input[..index]);
}
false
}
fn at_offset(context: &Context, seconds: f64) -> Result<Context, Error> {
let now = context
.now
.checked_add_signed(chrono::Duration::milliseconds((seconds * 1000.0) as i64))
.ok_or_else(|| Error("invalid_endpoint".into()))?;
Ok(Context {
now,
..context.clone()
})
}
fn local_instant(
naive: chrono::NaiveDateTime,
context: &Context,
) -> Result<chrono::DateTime<chrono::Utc>, Error> {
match context.timezone.from_local_datetime(&naive) {
chrono::LocalResult::Single(time) => Ok(time.with_timezone(&chrono::Utc)),
chrono::LocalResult::Ambiguous(_, _) => Err(Error("ambiguous_endpoint".into())),
chrono::LocalResult::None => Err(Error("nonexistent_endpoint".into())),
}
}
fn calendar_seconds(count: f64, unit: &str, context: &Context) -> Result<f64, Error> {
let start = context.now.with_timezone(&context.timezone);
let day = super::calendar::add(start.date_naive(), count, unit)
.ok_or_else(|| Error("invalid_duration".into()))?;
let end = local_instant(day.and_time(start.time()), context)?;
Ok((end - context.now).num_milliseconds() as f64 / 1000.0)
}
fn duration_expression(input: &str, context: &Context) -> Result<String, Error> {
let input = input
.trim_start_matches("the literal next ")
.trim_start_matches("literal next ")
.trim_start_matches("the next ")
.trim_start_matches("next ")
.trim_start_matches("another ")
.replace(" elapsed ", " ")
.replace("half an hour", "30 minutes")
.replace("half hour", "30 minutes");
if let Some(c) = re!(r"^(?:([\d.]+) )?calendar (days?|weeks?|months?|years?)$").captures(&input)
{
let count = c
.get(1)
.map_or(Ok(1.0), |m| m.as_str().parse::<f64>())
.map_err(|_| Error("invalid_duration".into()))?;
if count.fract() != 0.0 || count < 0.0 {
return Err(Error("invalid_duration".into()));
}
return Ok(format!(
"{} seconds",
calendar_seconds(count, &c[2], context)?
));
}
Ok(input)
}
fn endpoint_seconds(input: &str, context: &Context) -> Result<f64, Error> {
let input = syntax::ungroup(input);
if input == "the same local time tomorrow" {
return calendar_seconds(1.0, "day", context);
}
if let Some(c) = re!(r"^(?:exactly )?(.+) later$").captures(input) {
let seconds = super::time::Time::default()
.seconds(&c[1])
.ok_or_else(|| Error("invalid_endpoint".into()))?;
return if seconds < 0.0 {
Err(Error("endpoint_in_past".into()))
} else {
Ok(seconds)
};
}
if let Some(seconds) = super::time::clock(input) {
let local = context.now.with_timezone(&context.timezone);
let clock = chrono::NaiveTime::from_hms_opt(
(seconds / 3600) as u32,
(seconds % 3600 / 60) as u32,
(seconds % 60) as u32,
)
.ok_or_else(|| Error("invalid_endpoint".into()))?;
let date = if clock < local.time() {
local
.date_naive()
.succ_opt()
.ok_or_else(|| Error("invalid_endpoint".into()))?
} else {
local.date_naive()
};
let endpoint = local_instant(date.and_time(clock), context)?;
return Ok((endpoint - context.now).num_milliseconds() as f64 / 1000.0);
}
let mut endpoint = resolve_endpoint(input, context, 0)?;
if clock_expression(input) && endpoint < context.now {
let day = context
.now
.with_timezone(&context.timezone)
.date_naive()
.succ_opt()
.ok_or_else(|| Error("invalid_endpoint".into()))?;
let next = Context {
now: local_instant(day.and_hms_opt(0, 0, 0).unwrap(), context)?,
..context.clone()
};
endpoint = resolve_endpoint(input, &next, 0)?;
}
if endpoint < context.now {
return Err(Error("endpoint_in_past".into()));
}
Ok((endpoint - context.now).num_milliseconds() as f64 / 1000.0)
}
pub(crate) fn resolve_endpoint(
input: &str,
context: &Context,
depth: usize,
) -> Result<chrono::DateTime<chrono::Utc>, Error> {
if depth > 64 {
return Err(Error("expression_too_deep".into()));
}
let input = syntax::ungroup(input)
.trim()
.to_lowercase()
.replace("midnight tonight", "tomorrow at midnight");
if let Some(&(index, operator)) = super::arithmetic::operators(&input)
.ok_or_else(|| Error("invalid_endpoint".into()))?
.iter()
.rev()
.find(|(_, op)| "+-".contains(*op))
&& let Some(seconds) = super::time::Time::default().seconds(&input[index + 1..])
{
let endpoint = resolve_endpoint(&input[..index], context, depth + 1)?;
return endpoint
.checked_add_signed(chrono::Duration::milliseconds(
(seconds * 1000.0 * if operator == '+' { 1.0 } else { -1.0 }) as i64,
))
.ok_or_else(|| Error("invalid_endpoint".into()));
}
let input = re!(r"^(\d{4}-\d{2}-\d{2}) ((?:\d|noon|midnight).+)$").replace(&input, "$1 at $2");
let input = if let Some(c) = re!(r"^(.+) (today|tomorrow)$").captures(&input) {
format!("{} at {}", &c[2], &c[1])
} else {
input.to_string()
};
if input == "now" {
return Ok(context.now);
}
let (date, seconds) = if let Some(seconds) = super::time::clock(&input) {
(
context.now.with_timezone(&context.timezone).date_naive(),
seconds,
)
} else {
let (day, clock) = input.split_once(" at ").unwrap_or((&input, "midnight"));
(
super::calendar::date(day, context).ok_or_else(|| Error("invalid_endpoint".into()))?,
super::time::clock(clock).ok_or_else(|| Error("invalid_endpoint".into()))?,
)
};
let naive = date
.and_hms_opt(
(seconds / 3600) as u32,
(seconds % 3600 / 60) as u32,
(seconds % 60) as u32,
)
.ok_or_else(|| Error("invalid_endpoint".into()))?;
local_instant(naive, context)
}
pub(super) fn normalize_unit_powers(input: &str, units: &Units) -> String {
let input = re!(r"\b([a-zA-Z]+)\^([23])\b").replace_all(input, |c: ®ex::Captures| {
let unit = format!("{}{}", &c[1], if &c[2] == "2" { "²" } else { "³" });
if units.unit(&unit).is_some() {
unit
} else {
c[0].to_string()
}
});
let input = input.as_ref();
let input =
re!(r"\b([a-zA-Z]+) (squared|cubed)\b").replace_all(input, |c: ®ex::Captures| {
let unit = format!(
"{} {}",
if &c[2] == "squared" {
"square"
} else {
"cubic"
},
&c[1]
);
if units.unit(&unit).is_some() {
unit
} else {
c[0].to_string()
}
});
let input = input.as_ref();
input.to_string()
}