mod calendar_wording;
mod endpoint;
use super::{
compositions::Compositions, finance, integer_queries, model_coordinates, named_quantities,
syntax,
};
use crate::{Context, Error, ModelPosition, Outcome, Plugin, re};
use num_rational::BigRational;
use num_traits::{Signed, ToPrimitive, Zero};
use std::cmp::Ordering;
#[derive(Default)]
pub struct AccumulationQueries {
engine: Compositions,
}
impl Plugin for AccumulationQueries {
fn rewrite_call(
&self,
name: &str,
arguments: &str,
context: &Context,
_: ModelPosition,
) -> Outcome {
if !name.eq_ignore_ascii_case("accumulate_between") {
return None;
}
self.rewrite(&format!("{name}({arguments})"), context)
}
fn rewrite_model(&self, input: &str, context: &Context, _: ModelPosition) -> Outcome {
Request {
engine: &self.engine,
context,
}
.wording(input)
}
fn rewrite(&self, input: &str, context: &Context) -> Outcome {
let request = Request {
engine: &self.engine,
context,
};
let expression = match syntax::rewrite_groups(input, |part| request.wording(part)) {
Some(Ok(expression)) => expression,
Some(Err(error)) => return Some(Err(error)),
None => input.into(),
};
let lowered = syntax::rewrite_calls(
&expression,
re!(r"(?i)\baccumulate_between\s*\("),
|_, arguments| {
let args = named_quantities::function_arguments(arguments, false)?;
if args.len() != 3 {
return Err(invalid());
}
request
.window(args[0], args[1], args[2], context)
.map(|window| window.total)
},
);
match lowered {
Ok(lowered) if lowered != input => Some(bounded(lowered)),
Err(error) => Some(Err(error)),
_ => None,
}
}
fn evaluate(&self, input: &str, context: &Context) -> Outcome {
let input = syntax::ungroup(input);
if let Some(result) = calendar_wording::evaluate(input) {
return Some(result);
}
if let Some(inner) = input
.strip_prefix("elapsed_clock_components(")
.and_then(|s| s.strip_suffix(')'))
{
return Some((|| {
let seconds: i64 = inner.parse().ok().filter(|s| *s >= 0).ok_or_else(invalid)?;
Ok(format!(
"{} days; {} hours; {} minutes",
seconds / 86_400,
seconds / 3_600 % 24,
crate::number((seconds % 3_600) as f64 / 60.0)
))
})());
}
if input.starts_with("elapsed_components(") {
return Some((|| {
let seconds: i64 = input
.strip_prefix("elapsed_components(")
.and_then(|s| s.strip_suffix(')'))
.and_then(|s| s.parse().ok())
.filter(|s| *s >= 0)
.ok_or_else(invalid)?;
Ok(format!(
"{} days; {} remaining hours",
seconds / 86_400,
crate::number((seconds % 86_400) as f64 / 3_600.0)
))
})());
}
if !input.contains("accumulation_summary(") {
return None;
}
Some((|| {
let inner = input
.strip_prefix("accumulation_summary(")
.and_then(|s| s.strip_suffix(')'))
.ok_or_else(invalid)?;
let fields = inner.split(';').collect::<Vec<_>>();
if !(2..=4).contains(&fields.len()) {
return Err(invalid());
}
let mut output = Vec::new();
for field in fields {
let parts = field.split('|').collect::<Vec<_>>();
if parts.len() != 3 {
return Err(invalid());
}
let (label, target, expression) = (parts[0], parts[1], parts[2]);
validate_field(&self.engine, label, target, expression, context)?;
let display = self
.engine
.evaluate(&format!("({expression}) in {target}"), context)
.ok_or_else(invalid)??;
output.push(format!("{label}: {display}"));
}
Ok(output.join("; "))
})())
}
}
fn invalid() -> Error {
Error("invalid_expression".into())
}
fn bounded(expression: String) -> Result<String, Error> {
if expression.len() > 4096 {
Err(invalid())
} else {
Ok(expression)
}
}
fn validate_field(
engine: &Compositions,
label: &str,
target: &str,
expression: &str,
context: &Context,
) -> Result<(), Error> {
let reference = match label {
"elapsed hours" => "hours",
"duration" => "minutes",
"charge" => "coulombs",
"total units" => "units",
"average rate" => "units/hour",
"volume" | "total volume" | "volume per container" => "L",
"total mass" | "remaining mass" => "kg",
"energy" => "J",
"amount" | "converted amount" | "cost" => finance::currency(target).ok_or_else(invalid)?,
_ => return Err(invalid()),
};
engine.quantity_value(&format!("1 {target}"), reference, context)?;
engine.quantity_value(expression, target, context)?;
Ok(())
}
struct Field<'a> {
label: &'static str,
unit: &'a str,
expression: String,
}
fn field<'a>(label: &'static str, unit: &'a str, expression: impl Into<String>) -> Field<'a> {
Field {
label,
unit,
expression: expression.into(),
}
}
struct Window {
rate: String,
duration: String,
total: String,
}
struct Request<'a> {
engine: &'a Compositions,
context: &'a Context,
}
impl Request<'_> {
fn endpoint(
&self,
input: &str,
context: &Context,
) -> Result<chrono::DateTime<chrono::Utc>, Error> {
endpoint::resolve(input, context)
}
fn elapsed_seconds(
&self,
start: &str,
end: &str,
context: &Context,
signed: bool,
) -> Result<i64, Error> {
let (start, end) = (self.endpoint(start, context)?, self.endpoint(end, context)?);
if !signed && end < start {
return Err(Error("invalid_interval".into()));
}
Ok((end - start).num_seconds())
}
fn elapsed_wording(&self, input: &str) -> Outcome {
let query = endpoint::wording(input)?;
if !re!(r"^\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}").is_match(&query.start) {
return None;
}
Some((|| {
let seconds = endpoint::elapsed(&query.start, &query.end, self.context, query.signed)?;
if query.target == "days hours minutes" {
return bounded(format!("elapsed_clock_components({seconds})"));
}
if query.target == "full days and remaining hours" {
return bounded(format!("elapsed_components({seconds})"));
}
if query.target == "hours and minutes" {
if seconds == 0 {
bounded("0 seconds in minutes".into())
} else {
bounded(format!("{seconds} seconds in hours and minutes"))
}
} else {
self.engine.quantity_value(
&format!("1 {}", query.target),
"seconds",
self.context,
)?;
self.scalar(&format!("{seconds} seconds"), &query.target)
}
})())
}
fn window(
&self,
rate: &str,
start: &str,
end: &str,
context: &Context,
) -> Result<Window, Error> {
let seconds = self.elapsed_seconds(start, end, context, false)?;
let duration = format!("{seconds} seconds");
let rate = normalize_rate(rate);
named_quantities::validate_rate(&rate, "1 second", &self.engine.units, context)?;
let total = bounded(format!("(({rate}) * ({duration}))"))?;
Ok(Window {
rate,
duration,
total,
})
}
fn report(&self, fields: &[Field<'_>]) -> Result<String, Error> {
for field in fields {
validate_field(
self.engine,
field.label,
field.unit,
&field.expression,
self.context,
)?;
}
bounded(format!(
"accumulation_summary({})",
fields
.iter()
.map(|field| format!("{}|{}|{}", field.label, field.unit, field.expression))
.collect::<Vec<_>>()
.join(";")
))
}
fn scalar(&self, expression: &str, unit: &str) -> Result<String, Error> {
self.engine.quantity_value(expression, unit, self.context)?;
bounded(format!("({expression}) in {unit}"))
}
fn retained_fraction(&self, percentage: &str) -> Result<String, Error> {
let coordinate = model_coordinates::read(percentage, "1", self.engine, self.context)?;
let hundred = BigRational::from_integer(100.into());
if coordinate.value.is_negative() || coordinate.value > hundred {
return Err(Error("invalid_physical_quantity".into()));
}
let retained = model_coordinates::bounded((&hundred - coordinate.value) / hundred)?;
let expression = if coordinate.authored {
format!("rational({},{})", retained.numer(), retained.denom())
} else {
let value = retained
.to_f64()
.filter(|value| value.is_finite())
.ok_or_else(|| Error("numeric_overflow".into()))?;
if value == 0.0 && !retained.is_zero() {
return Err(Error("numeric_underflow".into()));
}
format!("real({value:e})")
};
self.engine.quantity_value(&expression, "1", self.context)?;
bounded(expression)
}
fn supplied_exchange(&self, left: &str, right: &str) -> Result<(), Error> {
let financial_error = || Error("invalid_financial_rate".into());
let left = currency_amount(left);
let right = currency_amount(right);
let left_code = finance::amount(&left)
.map(|(_, code)| code)
.filter(|code| !code.is_empty())
.ok_or_else(financial_error)?;
let right_code = finance::amount(&right)
.map(|(_, code)| code)
.filter(|code| !code.is_empty())
.ok_or_else(financial_error)?;
let a = self
.engine
.quantity_value(&left, left_code, self.context)
.map_err(|_| financial_error())?;
let b = self
.engine
.quantity_value(&right, right_code, self.context)
.map_err(|_| financial_error())?;
if a <= 0.0
|| b <= 0.0
|| self
.engine
.quantity_order(&left, &right, self.context)
.map_err(|_| financial_error())?
!= Ordering::Equal
{
return Err(financial_error());
}
Ok(())
}
fn common_base_quote(&self, source: &str, target: &str, quote: &str) -> Result<(), Error> {
let c = re!(r"(?i)^([a-z]{3}) (.+?)(?: per common-base unit)? and ([a-z]{3}) (.+?) per common-base unit$")
.captures(quote).ok_or_else(invalid)?;
let codes = [finance::currency(&c[1]), finance::currency(&c[3])];
if codes != [Some(source), Some(target)] {
return Err(Error("invalid_financial_rate".into()));
}
for (code, coefficient) in [(source, &c[2]), (target, &c[4])] {
let coordinate = model_coordinates::read(coefficient, "1", self.engine, self.context)?;
if coordinate.value <= BigRational::zero() {
return Err(Error("invalid_financial_rate".into()));
}
finance::validate_supplied_rate(code, coefficient, self.engine, self.context)?;
}
Ok(())
}
fn wording(&self, input: &str) -> Outcome {
let input = input.trim().trim_end_matches(['.', '?']);
if let Some(c) = re!(r"(?i)^a log contains timestamps every (.+?) for (.+?), including both the first timestamp at time zero and the final timestamp; how many timestamps are recorded$").captures(input) {
return Some((|| {
let step = model_coordinates::read(&c[1], "s", self.engine, self.context)?;
let duration = model_coordinates::read(&c[2], "s", self.engine, self.context)?;
if step.value <= BigRational::zero() || duration.value < BigRational::zero() {
return Err(Error("invalid_interval".into()));
}
let intervals = duration.value / step.value;
if !intervals.is_integer() {
return Err(Error("invalid_interval".into()));
}
let intervals = integer_queries::bounded(&intervals.to_integer(), 1_000_000)?;
Ok((intervals + 1).to_string())
})());
}
if let Some(result) = calendar_wording::rewrite(self.engine, input, self.context) {
return Some(result);
}
if let Some(result) = self.elapsed_wording(input) {
return Some(result);
}
if re!(r"(?i)^(?:calculate|compute) accumulated [a-z]+ at .+ between .+; no exact dates or endpoint times are supplied$")
.is_match(input) {
return Some(Err(Error("invalid_endpoint".into())));
}
let c = re!(r"(?i)^(.+?) (?:from|between) (\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(?::\d{2})?)(?: ([^\s;,]+))? (?:to|through|until|and) (\d{4}-\d{2}-\d{2}[ T]\d{2}:\d{2}(?::\d{2})?)(?: ([^\s;,]+))?(.*)$")
.captures(input)?;
let prefix = &c[1];
let (rate, material) = natural_rate(prefix)?;
Some((|| {
let end_zone = c.get(5).filter(|zone| endpoint::zone_token(zone.as_str()));
let endpoint = |date: &str, zone: Option<regex::Match<'_>>| {
zone.map_or_else(
|| date.to_string(),
|zone| format!("{date} {}", zone.as_str()),
)
};
let window = self.window(
&rate,
&endpoint(&c[2], c.get(3).or(end_zone)),
&endpoint(&c[4], end_zone),
self.context,
)?;
let (duration, total, rate) = (&window.duration, &window.total, &window.rate);
let tail = if c.get(5).is_some() && end_zone.is_none() {
format!("{}{}", &c[5], &c[6])
} else {
c[6].to_string()
};
let tail = tail.trim();
if tail.is_empty() && re!(r"(?i)^at .+?, how much liquid accumulates$").is_match(prefix)
{
return self.scalar(total, "L");
}
if re!(r"(?i)^; report total units$").is_match(tail) {
return self.scalar(total, "units");
}
if let Some(goal) = re!(r"(?i)^; find accumulated energy in (.+)$").captures(tail) {
self.engine.quantity_value(total, "J", self.context)?;
return self.scalar(total, &goal[1]);
}
if let Some(goal) =
re!(r"(?i)^, then convert (?:the )?result to ([a-z]{3}) at (.+)$").captures(tail)
{
let source = rate_currency(rate).ok_or_else(invalid)?;
let target = finance::currency(&goal[1]).ok_or_else(invalid)?;
self.common_base_quote(source, target, &goal[2])?;
return self.scalar(total, target);
}
if let Some(goal) = re!(r"(?i)^; calculate (?:the )?amount in ([a-z]{3}) and convert it to ([a-z]{3}) using (.+)$").captures(tail) {
let source = finance::currency(&goal[1]).ok_or_else(invalid)?;
let target = finance::currency(&goal[2]).ok_or_else(invalid)?;
if rate_currency(rate) != Some(source) { return Err(Error("invalid_financial_rate".into())); }
self.common_base_quote(source, target, &goal[3])?;
return self.report(&[field("amount", source, total), field("converted amount", target, total)]);
}
if re!(r"(?i)^; count elapsed time between endpoints, exclude any extra inclusive day, and find accumulated units$")
.is_match(tail) {
return self.scalar(total, "units");
}
if material && re!(r"(?i)^, using exact elapsed endpoint time$").is_match(tail) {
let numerator = syntax::split_last(rate, &["/"])
.map(|(left, _)| syntax::ungroup(left))
.ok_or_else(invalid)?;
let unit = self
.engine
.units
.quantity(numerator)
.map(|quantity| quantity.unit)
.ok_or_else(invalid)?;
self.engine.quantity_value(total, "kg", self.context)?;
return self.scalar(total, &unit.symbol);
}
if re!(r"(?i)^using elapsed endpoint duration; report hours and litres$").is_match(tail)
{
return self.report(&[
field("elapsed hours", "hours", duration),
field("volume", "L", total),
]);
}
if re!(r"(?i)^; report elapsed hours and charge$").is_match(tail) {
return self.report(&[
field("elapsed hours", "hours", duration),
field("charge", "coulombs", total),
]);
}
if re!(r"(?i)^; give hours and amount, with no compounding$").is_match(tail) {
let currency = rate_currency(rate).ok_or_else(invalid)?;
return self.report(&[
field("elapsed hours", "hours", duration),
field("amount", currency, total),
]);
}
if re!(r"(?i)^; report elapsed hours, total units, and average rate over the interval$")
.is_match(tail)
{
if self
.engine
.quantity_value(duration, "seconds", self.context)?
== 0.0
{
return Err(Error("division_by_zero".into()));
}
return self.report(&[
field("elapsed hours", "hours", duration),
field("total units", "units", total),
field(
"average rate",
"units/hour",
format!("({total}) / ({duration})"),
),
]);
}
if let Some(c) = re!(r"(?i)^; report elapsed hours, total mass, and the mass remaining after removing (.+)%$")
.captures(tail) {
let retained = self.retained_fraction(&c[1])?;
return self.report(&[field("elapsed hours", "hours", duration), field("total mass", "kg", total),
field("remaining mass", "kg", format!("({total}) * ({retained})"))]);
}
if let Some(c) =
re!(r"(?i)^; report duration, total volume, and volume in (.+)$").captures(tail)
{
return self.report(&[
field("duration", "minutes", duration),
field("total volume", "L", total),
field("volume", &c[1], total),
]);
}
if let Some(c) = re!(r"(?i)^; give elapsed hours and ([a-z]{3}) amount, then convert it to ([a-z]{3}) using (.+?)\s*=\s*(.+)$")
.captures(tail) {
let source = finance::currency(&c[1]).ok_or_else(invalid)?;
let target = finance::currency(&c[2]).ok_or_else(invalid)?;
self.supplied_exchange(&c[3], &c[4])?;
return self.report(&[field("elapsed hours", "hours", duration), field("amount", source, total),
field("converted amount", target, total)]);
}
if let Some(c) =
re!(r"(?i)^; find elapsed hours and energy in (.+?), then cost at (.+)$")
.captures(tail)
{
let tariff = normalize_rate(&c[2]);
let currency = rate_currency(&tariff).ok_or_else(invalid)?;
self.engine
.quantity_value(&tariff, &format!("{currency}/kWh"), self.context)?;
return self.report(&[
field("elapsed hours", "hours", duration),
field("energy", &c[1], total),
field("cost", currency, format!("({total}) * ({tariff})")),
]);
}
if let Some(c) = re!(r"(?i)^; report elapsed hours, litres, and millilitres, then divide the volume equally among (.+) containers$")
.captures(tail) {
self.engine.quantity_value(&c[1], "1", self.context)?;
let (n, d) = integer_queries::ratio_value(&c[1])?;
if n.is_zero() || n.is_negative() { return Err(Error("invalid_physical_quantity".into())); }
if d != num_bigint::BigInt::from(1) { return Err(Error("integer_required".into())); }
return self.report(&[field("elapsed hours", "hours", duration), field("volume", "L", total),
field("volume", "mL", total), field("volume per container", "L", format!("({total}) / ({})", &c[1]))]);
}
if re!(r"(?i)^, while also requiring a positive total volume; assess consistency$")
.is_match(tail)
{
self.engine.quantity_value(total, "L", self.context)?;
return Ok((self.engine.quantity_order(total, "0 L", self.context)?
== Ordering::Greater)
.to_string());
}
Err(invalid())
})())
}
}
fn currency_amount(input: &str) -> String {
let input = input.trim();
if finance::amount(input).is_some_and(|(_, code)| !code.is_empty()) {
return input.into();
}
if let Some(c) = re!(r"(?i)^([a-z]{3}|us\$|[$€£¥₿])\s*(.+)$").captures(input)
&& let Some(code) = finance::currency(&c[1])
{
return format!("{} {code}", &c[2]);
}
input.into()
}
fn normalize_rate(input: &str) -> String {
let input = re!(r"(?i)\s+per\s+").replace_all(input.trim(), "/");
if let Some((amount, denominator)) = syntax::split_last(&input, &["/"]) {
let denominator = syntax::ungroup(denominator.trim());
let bare_unit = denominator.starts_with(char::is_alphabetic) && !denominator.contains('(');
let denominator = if bare_unit {
format!("1 {denominator}")
} else {
denominator.into()
};
format!("({}) / ({denominator})", currency_amount(amount))
} else {
currency_amount(&input)
}
}
fn rate_currency(rate: &str) -> Option<&'static str> {
let numerator = syntax::split_last(rate, &["/"]).map(|(left, _)| syntax::ungroup(left))?;
finance::amount(numerator)
.map(|(_, code)| code)
.filter(|code| !code.is_empty())
}
fn natural_rate(prefix: &str) -> Option<(String, bool)> {
if let Some(c) = re!(r"(?i)^(?:a lab grows a culture at|accumulate(?: output at| savings at| revenue at)?|a sensor accumulates charge at|a stream is added at|a process adds) (.+)$")
.captures(prefix) {
return Some((c[1].to_string(), false));
}
if let Some(c) = re!(r"(?i)^at (.+?), accumulation runs$").captures(prefix) {
return Some((c[1].to_string(), false));
}
if let Some(c) = re!(r"(?i)^at (.+?), how much material accumulates$").captures(prefix) {
return Some((c[1].to_string(), true));
}
if let Some(c) =
re!(r"(?i)^at (.+?), (?:how much liquid accumulates|accumulate)$").captures(prefix)
{
return Some((c[1].to_string(), false));
}
if let Some(c) = re!(r"(?i)^(?:a rate of (.+?) applies|a [a-z]+ saves (.+))$").captures(prefix)
{
return Some((c.get(1).or_else(|| c.get(2))?.as_str().to_string(), false));
}
if let Some(c) = re!(r"(?i)^a (.+?) device runs$").captures(prefix) {
return Some((c[1].to_string(), false));
}
re!(r"(?i)^at a rate of (.+?), accumulate [a-z]+$")
.captures(prefix)
.map(|c| (c[1].to_string(), false))
}