use super::{Compositions, normalize_rate};
use crate::plugins::{finance, named_quantities, units};
use crate::{Context, Error, Outcome, Plugin, re};
pub struct StandardRates {
compositions: Compositions,
}
impl Default for StandardRates {
fn default() -> Self {
Self {
compositions: Compositions {
units: units::Units::default(),
},
}
}
}
impl Plugin for StandardRates {
fn evaluate(&self, input: &str, context: &Context) -> Outcome {
if invalid_percent_scale(input, &self.compositions.units) {
return Some(Err(Error("null_result".into())));
}
if let Some(error) = unknown_noun_operation(input, &self.compositions.units) {
return Some(Err(error));
}
if let Some(lowered) = standard_grouped_comments(input) {
return match lowered {
Ok(lowered)
if crate::plugins::statistics::comparison_operators(&lowered)
.is_ok_and(|operators| !operators.is_empty()) =>
{
None
}
Ok(lowered) => scalar_time_rate(&lowered, &self.compositions.units, context)
.or_else(|| finance::Finance.evaluate(&lowered, context))
.or_else(|| {
finance::amount(&lowered)
.filter(|(_, code)| !code.is_empty())
.and_then(|(value, code)| finance::render(value, code))
})
.or_else(|| self.compositions.units.evaluate(&lowered, context))
.or_else(|| crate::plugins::arithmetic::Arithmetic.evaluate(&lowered, context))
.or_else(|| {
self.compositions
.units
.expression(&lowered, 0)
.ok()
.filter(|q| q.unit.dimension == [0; 8])
.map(|q| Ok(crate::number(q.base)))
}),
Err(error) => Some(Err(error)),
};
}
if let Some(result) = scalar_time_rate(input, &self.compositions.units, context) {
return Some(result);
}
let conversion = super::syntax::split_last(input, super::syntax::CONVERSIONS);
let source = conversion.map_or(input, |(source, _)| source);
if re!(r"^(?:abs|sqrt|round)\(").is_match(source)
&& (conversion.is_none() || unknown_call(source, &self.compositions.units))
&& re!(r"[a-zA-Z]+|[$€£¥]|²|³").find_iter(input).any(|m| {
self.compositions.units.unit(m.as_str()).is_some()
|| finance::currency(m.as_str()).is_some()
|| matches!(m.as_str(), "square" | "mean" | "sum" | "max" | "²" | "³")
})
{
return Some(
StandardFunctions {
units: &self.compositions.units,
context,
}
.expression(source, 0)
.and_then(|q| q.ok_or_else(|| Error("null_result".into())))
.and_then(|q| {
if let Some((_, target)) = conversion {
if input.contains(" into ") {
return Err(Error("invalid_expression".into()));
}
let target = self
.compositions
.units
.unit(target)
.ok_or_else(|| Error("invalid_expression".into()))?;
if q.unit.dimension != [0; 8] && q.unit.dimension != target.dimension {
return Err(Error("internal_error".into()));
}
let value = if q.unit.dimension == [0; 8] {
q.base
} else {
(q.base - target.offset) / target.scale
};
return Ok(units::format_quantity(value, &target));
}
if q.unit.dimension == [0; 8] {
Ok(crate::number(q.base))
} else {
Ok(units::format_quantity(
(q.base - q.unit.offset) / q.unit.scale,
&q.unit,
))
}
}),
);
}
let input = input.replace('×', "*").replace('÷', "/");
let input = input.as_str();
if !input.contains(" for ")
&& let Some((source, target)) =
super::syntax::split_last(input, super::syntax::CONVERSIONS)
&& matches!(target, "cent" | "cents")
&& named_quantities::recognizes_expression(source)
{
return if input.contains(" into ") {
Some(Err(Error("invalid_expression".into())))
} else {
named_quantities::evaluate_standard(
&normalize_rate(input, &self.compositions.units),
&self.compositions.units,
context,
)
};
}
if (input.contains('/') || input.contains(" per "))
&& re!(r" (?:over|during|till) ").is_match(input)
{
return Some(Err(Error("invalid_expression".into())));
}
if !input.contains('/')
&& !(input.contains(" per ") && (input.contains('*') || input.contains(" for ")))
|| input.contains(" of ")
|| input.starts_with(char::is_alphabetic)
{
return None;
}
if !re!(r"[\p{L}]+").find_iter(input).any(|m| {
self.compositions.units.unit(m.as_str()).is_some()
|| named_quantities::recognizes(m.as_str())
}) {
return None;
}
if !input.contains('(')
&& re!(r"\s+per\s+([\p{L}]+)\b")
.captures_iter(input)
.any(|c| self.compositions.units.unit(&c[1]).is_none())
{
return None;
}
if re!(r"\*\s*[\d.]+ (?:pages?|words?|beats?)$").is_match(input) {
return Some(Err(Error("invalid_expression".into())));
}
if input.contains("until ") && !input.contains(" for (until ") {
if input.starts_with('(')
&& let Some((rate, endpoint)) = super::syntax::split_last(input, &[" until "])
&& crate::plugins::calendar::date(endpoint, context).is_some()
&& self
.compositions
.units
.expression(&normalize_rate(rate, &self.compositions.units), 0)
.is_ok_and(|quantity| {
quantity.unit.dimension[2] < 0
&& quantity
.unit
.dimension
.iter()
.enumerate()
.any(|(index, power)| index != 2 && *power != 0)
})
{
return self
.compositions
.units
.evaluate(&normalize_rate(rate, &self.compositions.units), context);
}
return None;
}
if let Some((distance, speed)) = input.split_once(" in ")
&& self.compositions.units.quantity(distance).is_some()
&& self.compositions.units.quantity(speed).is_some()
{
return Some(Err(Error("internal_error".into())));
}
if let Some(converter) = re!(r" (?:in|to|as) ").find(input)
&& !input.contains(" for ")
&& !re!(r"/\s*[a-zA-Z]+").is_match(&input[..converter.start()])
{
return None;
}
if !input.contains(" for ")
&& re!(r" (?:in|to|as) ").is_match(input)
&& let Some(result) = self
.compositions
.units
.evaluate(input, context)
.or_else(|| {
self.compositions.units.evaluate(
&normalize_rate(input, &self.compositions.units).replace('×', "*"),
context,
)
})
{
return Some(result);
}
if input.contains("/batch") {
return Some(Err(Error("invalid_expression".into())));
}
if input.contains(" for ") {
if input.contains(" into ") {
return Some(Err(Error("invalid_expression".into())));
}
if re!(r" (?:in|to|as) ").is_match(input) {
let money_conversion = named_quantities::recognizes_expression(input)
&& re!(r" (?:in|to|as) ([a-zA-Z]+)")
.captures_iter(input)
.all(|c| {
finance::currency(&c[1]).is_some() || matches!(&c[1], "cent" | "cents")
});
if !money_conversion {
return input
.contains('/')
.then(|| Err(Error("invalid_expression".into())));
}
}
if let Some((_, duration)) = input.split_once(" for ")
&& !duration.starts_with("(until ")
&& !duration.starts_with("(till ")
&& !super::syntax::ungroup(duration)
.starts_with(|c: char| c.is_ascii_digit() || c == '-' || c == '+')
{
return None;
}
if let Some(c) = re!(r"^(.+)/([a-z]+) for \((?:until|till) .+\)$").captures(input) {
let numerator = if let Some((n, code)) = finance::amount(&c[1])
&& !code.is_empty()
{
crate::plugins::money(n, code)
} else if let Some(q) = self.compositions.units.quantity(&c[1]) {
units::format_quantity(q.base / q.unit.scale, &q.unit)
} else {
let c = re!(r"^([\d.]+) [a-z]+$").captures(&c[1])?;
crate::number(c[1].parse().ok()?)
};
let unit = self.compositions.units.unit(&c[2])?;
let label = match unit.symbol.as_str() {
"hours" => "hour",
"days" => "day",
"months" => "month",
s => s,
};
return Some(Ok(format!("{numerator}/{label}")));
}
if let Some((_, duration)) = input.split_once(" for ") {
let duration = clause_operand(duration);
if self
.compositions
.units
.quantity(super::syntax::ungroup(duration))
.is_none()
&& self.compositions.units.expression(duration, 0).is_err()
{
return Some(Err(Error("invalid_expression".into())));
}
}
if !re!(r"[\d.]\s*[a-zA-Z]+(?:\^[23])?/(?:1 )?[a-zA-Z]+ for ")
.is_match(&normalize_rate(input, &self.compositions.units))
&& !re!(r"[$€£¥][+-]?[\d.]+/(?:1 )?[a-zA-Z]+ for ").is_match(input)
{
return None;
}
}
if !input.contains(" for ") && !input.contains(" in ") {
if input.contains('^') {
return self.compositions.units.evaluate(input, context);
}
if let Some(Ok(result)) = named_quantities::evaluate_standard(
&normalize_rate(input, &self.compositions.units),
&self.compositions.units,
context,
) && result.replace(',', "").parse::<f64>().is_ok()
{
return Some(Ok(result));
}
let named = re!(r"(?i)\b(?:dollars?|cents?|pages?|words?|beats?|batches|bottles?|items?|person|people)\b")
.is_match(input);
match if named {
Err(Error("invalid_expression".into()))
} else {
self.compositions
.units
.expression(&normalize_rate(input, &self.compositions.units), 0)
} {
Ok(q)
if input.contains('*')
&& !q.unit.symbol.contains('⋅')
&& q.unit.dimension.iter().filter(|d| **d != 0).count() > 2 =>
{
return Some(Err(Error("internal_error".into())));
}
Err(error) if error.0 == "internal_error" => return Some(Err(error)),
_ => {}
}
}
let rates = normalize_rate(input, &self.compositions.units);
let rates = re!(r"\s+per\s+([a-zA-Z]+)\b").replace_all(&rates, "/1 $1");
let normalized =
super::normalize_unit_powers(&rates.replace(" for ", " * "), &self.compositions.units);
let named = named_quantities::recognizes_expression(input);
let result = if named {
let result = named_quantities::evaluate_standard(
&normalized,
&self.compositions.units,
context,
)?;
if matches!(&result, Err(error) if error.0 == "invalid_expression") {
return None;
}
result.map_err(|_| Error("internal_error".into()))
} else {
let result = self.compositions.units.evaluate(&normalized, context)?;
if matches!(&result, Err(e) if matches!(e.0.as_str(), "invalid_expression" | "invalid_unit"))
{
return None;
}
result
};
Some(result.map(|display| {
if display == "Error: ∞"
&& let Some(c) = re!(r"/\(0 (hours?|days?|minutes?)\)$").captures(input)
{
return format!("Error: ∞/{}", c[1].trim_end_matches('s'));
}
if display.ends_with(" m/s²")
&& input.contains("/(")
&& let Some(Ok(converted)) = self
.compositions
.units
.evaluate(&format!("{display} in ft/s²"), context)
{
return converted;
}
if display.ends_with(" km/h") && re!(r"/\s*\d+ hours?").is_match(input) {
return display.replace(" km/h", " km/hour");
}
for noun in ["words", "pages", "beats"] {
if let Some(number) = display.strip_suffix(&format!(" {noun}")) {
return number.into();
}
}
display
}))
}
}
fn invalid_percent_scale(input: &str, units: &units::Units) -> bool {
let input = input.trim().trim_end_matches(['.', '?']);
let Some((source, target)) = super::syntax::split_last(input, super::syntax::CONVERSIONS)
else {
return false;
};
if !matches!(
target.to_ascii_lowercase().as_str(),
"%" | "percent" | "percentage"
) || super::syntax::groups(source).is_none()
|| source
.chars()
.any(|symbol| finance::currency(&symbol.to_string()).is_some())
|| re!(r"[a-zA-Z_]+").find_iter(source).any(|word| {
units.unit(word.as_str()).is_some()
|| finance::currency(word.as_str()).is_some()
|| named_quantities::recognizes(word.as_str())
})
{
return false;
}
let source = source.replace('−', "-");
re!(r"\b(?:10(?:\.0+)?\s*\^\s*([+-]?\d+)\b|(?:\d[\d,]*(?:\.\d+)?|\.\d+)[eE]([+-]?\d+)\b)")
.captures_iter(&source)
.any(|capture| {
let exponent = capture.get(1).or_else(|| capture.get(2)).unwrap().as_str();
exponent
.parse::<i32>()
.map_or(true, crate::plugins::decimal::scientific_scale_invalid)
})
}
fn clause_operand(input: &str) -> &str {
let mut depth = 0;
for (index, character) in input.char_indices() {
if depth == 0
&& ((character == ')' || index > 0 && "+*/^".contains(character))
|| super::syntax::CONVERSIONS
.iter()
.any(|phrase| input[index..].starts_with(phrase)))
{
return input[..index].trim();
}
match character {
'(' => depth += 1,
')' => {
depth -= 1;
if depth == 0 {
return input[..=index].trim();
}
}
_ => {}
}
}
input.trim()
}
struct StandardFunctions<'a> {
units: &'a units::Units,
context: &'a Context,
}
impl StandardFunctions<'_> {
fn scalar(&self, base: f64) -> units::Quantity {
units::Quantity {
base,
unit: units::Unit {
aliases: "",
symbol: String::new(),
dimension: [0; 8],
scale: 1.0,
offset: 0.0,
},
}
}
fn expression(&self, input: &str, depth: usize) -> Result<Option<units::Quantity>, Error> {
let error = || Error("internal_error".into());
if depth > 64 {
return Err(error());
}
let normalized = input.replace('−', "-").replace('×', "*").replace('÷', "/");
let s = super::syntax::ungroup(&normalized);
let duration = re!(r"\b(?:s|seconds?|minutes?|min|hours?|h)\b").is_match(s);
let normalized = if duration {
re!(r"\bm\b").replace_all(s, "minutes").into_owned()
} else {
s.into()
};
let s = normalized.as_str();
if !s.contains('(')
&& let Some(Ok(display)) = finance::Finance.evaluate(s, self.context)
&& let Some((n, code)) = finance::amount(&display).filter(|(_, code)| !code.is_empty())
{
let mut q = self.scalar(n);
q.unit.dimension[6] = 1;
q.unit.symbol = code.into();
return Ok(Some(q));
}
let operators = crate::plugins::arithmetic::operators(s).ok_or_else(error)?;
for level in ["+-", "*/", "^"] {
if let Some(&(at, op)) = operators.iter().rev().find(|(_, op)| level.contains(*op)) {
let Some(mut a) = self.expression(&s[..at], depth + 1)? else {
return Err(error());
};
let Some(b) = self.expression(&s[at + 1..], depth + 1)? else {
return Err(error());
};
if matches!(op, '+' | '-') {
let (a_scalar, b_scalar) =
(a.unit.dimension == [0; 8], b.unit.dimension == [0; 8]);
if a_scalar && !b_scalar {
a.base *= b.unit.scale;
a.unit = b.unit.clone();
}
if !b_scalar && a.unit.dimension != b.unit.dimension {
return Err(error());
}
a.base += (if b_scalar {
b.base * a.unit.scale
} else {
b.base
}) * if op == '+' { 1.0 } else { -1.0 };
return Ok(Some(a));
}
let left = units::format_quantity((a.base - a.unit.offset) / a.unit.scale, &a.unit);
let right =
units::format_quantity((b.base - b.unit.offset) / b.unit.scale, &b.unit);
return self
.units
.expression(&format!("({left}) {op} ({right})"), depth + 1)
.map(Some);
}
}
if let Some((name, tail)) = s.split_once('(')
&& tail.ends_with(')')
&& re!(r"^[a-zA-Z_][a-zA-Z_0-9]*$").is_match(name)
{
let inner = &tail[..tail.len() - 1];
if !matches!(name, "abs" | "sqrt" | "round" | "min") {
if !standard_function(name)
&& self.units.unit(name).is_none()
&& expression_group(inner, self.units)
{
return self.arguments(inner, depth + 1);
}
return Ok(None);
}
let Some(mut q) = self.arguments(inner, depth + 1)? else {
return Err(Error(
if name == "min" {
"internal_error"
} else {
"null_result"
}
.into(),
));
};
let magnitude = (q.base - q.unit.offset) / q.unit.scale;
match name {
"abs" => q = self.scalar(magnitude.abs()),
"round" => {
let zero_quantity = super::syntax::split_last(inner, &[", "])
.and_then(|(_, right)| self.expression(right, depth + 1).ok().flatten())
.is_some_and(|q| q.unit.dimension != [0; 8] && q.base == q.unit.offset);
if inner.contains(',')
&& q.unit.offset == 0.0
&& !zero_quantity
&& (q.unit.dimension == [0; 8]
|| q.unit.dimension == self.units.unit("minutes").unwrap().dimension)
&& !inner[..inner.rfind(',').unwrap()].trim_end().ends_with(')')
&& !inner[inner.rfind(',').unwrap() + 1..]
.trim_start()
.starts_with('-')
{
q = self.scalar(magnitude.round());
} else {
q.base = magnitude.round() * q.unit.scale + q.unit.offset;
}
}
"min" => {
let minutes = self.units.unit("minutes").unwrap();
if q.unit.dimension != minutes.dimension {
return Err(error());
}
q.unit = minutes;
}
"sqrt" => {
if q.base < 0.0 || q.unit.dimension.iter().any(|p| p % 2 != 0) {
return Err(error());
}
if q.unit.dimension == [0; 8] {
q = self.scalar(q.base.sqrt());
} else {
q = self.units.expression(
&format!("sqrt({})", units::format_quantity(magnitude, &q.unit)),
depth + 1,
)?;
}
}
_ => unreachable!(),
}
return if q.base.is_finite() {
Ok(Some(q))
} else {
Err(error())
};
}
if let Some((n, code)) = finance::amount(s).filter(|(_, code)| !code.is_empty()) {
let mut q = self.scalar(n);
q.unit.dimension[6] = 1;
q.unit.symbol = code.into();
return Ok(Some(q));
}
if let Some(Ok(display)) = finance::Finance.evaluate(s, self.context)
&& let Some((n, code)) = finance::amount(&display).filter(|(_, code)| !code.is_empty())
{
let mut q = self.scalar(n);
q.unit.dimension[6] = 1;
q.unit.symbol = code.into();
return Ok(Some(q));
}
if let Some(c) = re!(r"^([+-]?[\d.]+) ([a-zA-Z]+)[²³]$").captures(s)
&& self
.units
.unit(&c[2])
.is_none_or(|u| u.dimension != [1, 0, 0, 0, 0, 0, 0, 0])
{
return Ok(c[1].parse().ok().map(|n| self.scalar(n)));
}
if let Some(q) = self.units.quantity(s) {
return Ok(Some(q));
}
if let Some(n) = crate::plugins::arithmetic::eval(s) {
return Ok(Some(self.scalar(n)));
}
if let Some(inner) = s.strip_prefix('-') {
let mut q = self.expression(inner, depth + 1)?;
if let Some(q) = &mut q {
q.base = -q.base;
}
return Ok(q);
}
Ok(None)
}
fn arguments(&self, input: &str, depth: usize) -> Result<Option<units::Quantity>, Error> {
if let Some((left, right)) = super::syntax::split_last(input, &[", "]) {
if left.trim_end().ends_with(')') {
return self.expression(right, depth + 1);
}
let (Some(mut a), Some(b)) = (
self.arguments(left, depth + 1)?,
self.expression(right, depth + 1)?,
) else {
return Ok(None);
};
if b.unit.dimension == [0; 8] {
if right.starts_with('-') {
a.base += b.base * a.unit.scale;
return Ok(Some(a));
}
return Ok(None);
}
if a.unit.dimension == [0; 8] {
return Ok(None);
}
if a.unit.dimension != b.unit.dimension {
return Ok(None);
}
a.base += b.base - b.unit.offset;
return Ok(Some(a));
}
self.expression(input, depth + 1)
}
}
fn single_operation(input: &str) -> Option<(&str, char, &str)> {
let operators = crate::plugins::arithmetic::operators(input)?;
let [(at, operator)] = operators.as_slice() else {
return None;
};
Some((input[..*at].trim(), *operator, input[*at + 1..].trim()))
}
fn unknown_noun_operation(input: &str, units: &units::Units) -> Option<Error> {
let conversion = super::syntax::split_last(input, super::syntax::CONVERSIONS);
let source = conversion.map_or(input, |(source, _)| source).trim();
let (left, operator, right) = single_operation(source)?;
let noun =
re!(r"^[+-]?(?:\d[\d,]*(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?\s+([\p{L}]+)$").captures(left)?;
if units.quantity(left).is_some()
|| finance::amount(left).is_some()
|| crate::plugins::arithmetic::eval(left).is_some()
|| matches!(noun[1].to_ascii_lowercase().as_str(), "cent" | "cents")
{
return None;
}
if operator == '/'
&& conversion.is_none()
&& !named_quantities::recognizes(&noun[1])
&& units
.unit(right)
.is_some_and(|unit| unit.dimension == [0, 0, 1, 0, 0, 0, 0, 0])
{
return Some(Error("null_result".into()));
}
let grouped = super::syntax::ungroup(right) != right;
if operator == '/' && (grouped || units.quantity(right).is_some())
|| matches!(operator, '+' | '*') && grouped
{
Some(Error("invalid_expression".into()))
} else {
None
}
}
fn scalar_time_rate(input: &str, units: &units::Units, context: &Context) -> Outcome {
let (left, operator, right) = single_operation(input)?;
if operator != '/'
|| super::syntax::ungroup(right) == right
|| crate::plugins::arithmetic::eval(left).is_none()
{
return None;
}
let duration = units.quantity(super::syntax::ungroup(right))?;
if duration.unit.dimension != [0, 0, 1, 0, 0, 0, 0, 0] || !duration.base.is_finite() {
return None;
}
named_quantities::evaluate_standard(input, units, context).map(|result| {
result.map_err(|error| {
if error.0 == "division_by_zero" {
Error("internal_error".into())
} else {
error
}
})
})
}
pub(crate) fn standard_grouped_comments(input: &str) -> Option<Result<String, Error>> {
lower_comments(input, false)
}
pub(crate) fn standard_comparison_operand(
input: &str,
) -> Option<Result<Option<(String, bool)>, Error>> {
lower_comment_state(input, true).map(|result| {
result.and_then(|(value, list)| match value {
CommentOperand::Text(text) => Ok(Some((text, list))),
CommentOperand::DiscardComparison => Ok(None),
_ => Err(Error("internal_error".into())),
})
})
}
fn lower_comments(input: &str, comparison: bool) -> Option<Result<String, Error>> {
lower_comment_state(input, comparison).map(|result| {
result.and_then(|(value, _)| match value {
CommentOperand::Text(text) => Ok(text),
_ => Err(Error(
if comparison {
"internal_error"
} else {
"null_result"
}
.into(),
)),
})
})
}
pub(crate) fn standard_temporal_units(input: &str) -> String {
let temporal = re!(r"(?i)\b(?:seconds?|minutes?|hours?|days?|weeks?|s|min|ms)\b")
.find_iter(input)
.any(|word| !input[..word.start()].trim_end().ends_with('/'));
if !temporal {
return input.into();
}
re!(r"\bm\b")
.replace_all(input, |word: ®ex::Captures<'_>| {
let word = word.get(0).unwrap();
let after = input[word.end()..].trim_start();
if input[..word.start()].trim_end().ends_with('/')
|| after.starts_with(['/', '^', '²', '³'])
{
"m"
} else {
"min"
}
})
.into_owned()
}
fn lower_comment_state(
input: &str,
comparison: bool,
) -> Option<Result<(CommentOperand, bool), Error>> {
if !input.contains('(') {
return None;
}
let units = units::Units::default();
if unowned_assignment(input, &units) || unowned_declaration(input, &units) {
return None;
}
let (mut changed, mut list) = (false, false);
let input = standard_temporal_units(input);
let result = comment_expression(
&input,
false,
comparison,
0,
&units,
&mut changed,
&mut list,
);
changed.then(|| result.map(|value| (value, list)))
}
fn unowned_assignment(input: &str, units: &units::Units) -> bool {
let input = input.trim();
let Some(word) = re!(r"^[a-zA-Z_][a-zA-Z_0-9]*").find(input) else {
return false;
};
if owned_comment_prefix(word.as_str(), units) {
return false;
}
let mut clause = input;
while let Some((left, _)) = super::syntax::split_last(clause, &["="]) {
if !left.ends_with(['<', '>', '!', '='])
&& !input[left.len() + 1..].starts_with(['=', '<', '>'])
{
return true;
}
clause = left;
}
false
}
fn owned_comment_prefix(word: &str, units: &units::Units) -> bool {
standard_function(&word.to_ascii_lowercase())
|| units.unit(word).is_some()
|| finance::currency(word).is_some()
|| named_quantities::recognizes(word)
}
fn unowned_declaration(input: &str, units: &units::Units) -> bool {
let Some((prelude, instruction)) = super::syntax::split_last(input.trim(), &[". ", ";"]) else {
return false;
};
if !re!(r"(?is)^(?:calculate|evaluate|find)\s+\S.*$").is_match(instruction.trim()) {
return false;
}
let Some(declaration) =
re!(r"(?i)^(?:(?:a|an|the)\s+)?([a-z_][a-z_0-9]*)\s+is\s+\S").captures(prelude.trim())
else {
return false;
};
!owned_comment_prefix(&declaration[1], units)
}
enum CommentOperand {
Text(String),
Absent,
Empty,
DiscardComparison,
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum CommentUnit {
Physical([i8; 8]),
Currency,
}
fn standard_function(name: &str) -> bool {
matches!(
name,
"abs"
| "sqrt"
| "round"
| "floor"
| "ceil"
| "sin"
| "cos"
| "tan"
| "asin"
| "acos"
| "atan"
| "exp"
| "ln"
| "log"
| "min"
| "max"
| "sum"
| "mean"
| "average"
| "median"
| "clamp"
| "cbrt"
| "factorial"
)
}
fn unknown_call(input: &str, units: &units::Units) -> bool {
re!(r"([a-zA-Z_][a-zA-Z_0-9]*)\(")
.captures_iter(input)
.any(|c| !standard_function(&c[1]) && units.unit(&c[1]).is_none())
}
fn expression_group(input: &str, units: &units::Units) -> bool {
let timestamps = re!(r"\b\d{4}-\d{2}-\d{2} \d{1,2}:\d{2}(?::\d{2})?\b")
.find_iter(input)
.filter(|m| {
let (date, clock) = m.as_str().split_once(' ').unwrap();
chrono::NaiveDate::parse_from_str(date, "%Y-%m-%d").is_ok()
&& crate::plugins::time::clock(clock).is_some()
})
.map(|m| m.range())
.collect::<Vec<_>>();
crate::plugins::arithmetic::operators(input).is_some_and(|operators| {
operators.into_iter().any(|(at, op)| {
if timestamps.iter().any(|range| range.contains(&at)) {
return false;
}
if op != '/' {
return true;
}
let left = input[..at].rsplit(',').next().unwrap().trim();
let right = input[at + 1..].split(',').next().unwrap().trim();
units.quantity(left).is_none() || units.unit(right).is_none()
})
})
}
fn comment_expression(
input: &str,
grouped: bool,
comparison: bool,
depth: usize,
units: &units::Units,
changed: &mut bool,
list: &mut bool,
) -> Result<CommentOperand, Error> {
use CommentOperand::{Absent, DiscardComparison, Empty, Text};
let s = input.trim();
if depth > 64 {
return Err(Error("internal_error".into()));
}
let comparisons = crate::plugins::statistics::comparison_operators(s)?;
if !comparisons.is_empty() {
let mut left = comment_expression(
&s[..comparisons[0].0],
grouped,
true,
depth + 1,
units,
changed,
list,
)?;
for (index, (at, op)) in comparisons.iter().enumerate() {
let end = comparisons.get(index + 1).map_or(s.len(), |(at, _)| *at);
let right = comment_expression(
&s[at + op.len()..end],
grouped,
true,
depth + 1,
units,
changed,
list,
)?;
left = match (left, right) {
(DiscardComparison, other) | (other, DiscardComparison) => other,
(Text(left), Text(right)) => Text(format!("{left} {op} {right}")),
_ => return Err(Error("internal_error".into())),
};
}
return Ok(left);
}
if grouped && comparison && super::syntax::split_last(s, &[" and ", " or "]).is_some() {
let (atoms, dimensions, rate_divisions) = comment_atoms(s, units);
if let Some(operators) = crate::plugins::arithmetic::operators(s) {
let additive = operators.iter().any(|(_, op)| matches!(op, '+' | '-'));
let lexical_list = operators.iter().all(|(at, op)| {
matches!(op, '+' | '-') || *op == '/' && rate_divisions.contains(at)
});
let quantities = dimensions.iter().any(Option::is_some)
&& atoms.iter().zip(&dimensions).all(|(atom, dimension)| {
dimension.is_some() || crate::plugins::arithmetic::eval(atom).is_some()
});
if atoms.len() > 1
&& lexical_list
&& dimensions.iter().all(Option::is_none)
&& atoms
.iter()
.all(|atom| crate::plugins::arithmetic::eval(atom).is_some())
&& re!(r"[a-zA-Z_]+").find_iter(s).any(|word| {
!matches!(word.as_str(), "and" | "or")
&& units.unit(word.as_str()).is_none()
&& finance::currency(word.as_str()).is_none()
&& !named_quantities::recognizes(word.as_str())
&& !standard_function(word.as_str())
})
{
*changed = true;
return Err(Error("null_result".into()));
}
if atoms.len() > 1 && quantities {
*changed = true;
if !lexical_list {
return Err(Error("internal_error".into()));
}
if additive {
validate_comment_additions(s, depth + 1, units)?;
}
return Ok(DiscardComparison);
}
}
}
if grouped
&& re!(r"[a-zA-Z_]+").find_iter(s).all(|word| {
units.unit(word.as_str()).is_some()
|| finance::currency(word.as_str()).is_some()
|| named_quantities::recognizes(word.as_str())
|| matches!(
word.as_str(),
"for" | "of" | "on" | "off" | "choose" | "in" | "to" | "as"
)
})
{
return Ok(Text(s.into()));
}
if let Some((source, target)) = super::syntax::split_last(s, super::syntax::CONVERSIONS) {
return match comment_expression(
source,
grouped,
comparison,
depth + 1,
units,
changed,
list,
)? {
Text(lowered) => {
if *changed
&& let Some(target_unit) = units.unit(target.trim_end_matches('.'))
&& let Ok(source_quantity) = units.expression(&lowered, 0)
&& source_quantity.unit.dimension != target_unit.dimension
{
return Err(Error("internal_error".into()));
}
let separator = &s[source.len()..s.len() - target.len()];
Ok(Text(format!("{lowered}{separator}{target}")))
}
_ => Err(Error(
if comparison {
"internal_error"
} else {
"null_result"
}
.into(),
)),
};
}
if let Some(operators) = crate::plugins::arithmetic::operators(s) {
for level in ["+-", "*/", "^"] {
if let Some(&(at, op)) = operators.iter().rev().find(|(_, op)| level.contains(*op)) {
let left = comment_expression(
&s[..at],
grouped,
comparison,
depth + 1,
units,
changed,
list,
)?;
let right = comment_expression(
&s[at + 1..],
grouped,
comparison,
depth + 1,
units,
changed,
list,
)?;
return match (left, right) {
(Absent, other) | (other, Absent) => Ok(other),
(Empty, other) | (other, Empty) if matches!(op, '+' | '-') => Ok(other),
(Empty, _) | (_, Empty) | (DiscardComparison, _) | (_, DiscardComparison) => {
Err(Error("internal_error".into()))
}
(Text(left), Text(right)) => Ok(Text(format!("{left} {op} {right}"))),
};
}
}
}
let inner = super::syntax::ungroup(s);
if inner != s {
return comment_expression(inner, true, comparison, depth + 1, units, changed, list).map(
|value| match value {
Text(text) => Text(format!("({text})")),
other => other,
},
);
}
if let Some((name, _)) = s.split_once('(')
&& standard_function(name.trim())
{
return Ok(Text(s.into()));
}
if !grouped {
return Ok(Text(s.into()));
}
if let Some((value, code)) = finance::standard_percentage_span(s) {
*changed = true;
return Ok(Text(format!("({value} {code})")));
}
if re!(r"% (?:of|on|off) ").is_match(s)
|| re!(r"[a-zA-Z]+").find_iter(s).all(|word| {
units.unit(word.as_str()).is_some() || finance::currency(word.as_str()).is_some()
})
|| units.unit(s).is_some()
|| units.quantity(s).is_some()
|| finance::amount(s).is_some()
|| crate::plugins::arithmetic::eval(s).is_some()
{
return Ok(Text(s.into()));
}
if let Some((value, code)) = finance::standard_compound_span(s) {
*changed = true;
return Ok(Text(format!("({value} {code})")));
}
let mut leaf = s.to_string();
let mut retained_expression = false;
if let Some(groups) = super::syntax::groups(s) {
for group in groups.into_iter().rev() {
let before = &s[..group.start - 1];
let start = before
.rfind(|c: char| !c.is_alphanumeric() && c != '_')
.map_or(0, |at| at + 1);
let name = &before[start..];
if !name.is_empty() && !standard_function(name) && units.unit(name).is_none() {
if expression_group(&s[group.clone()], units) {
leaf.replace_range(start..group.start - 1, "");
retained_expression = true;
} else {
leaf.replace_range(start..group.end + 1, "");
}
*changed = true;
}
}
}
if retained_expression {
let value = comment_expression(&leaf, true, comparison, depth + 1, units, changed, list)?;
if leaf.contains(',')
&& let Text(text) = &value
&& units.expression(text, 0).is_err()
&& crate::plugins::arithmetic::eval(text).is_none()
{
return Err(Error("internal_error".into()));
}
return Ok(value);
}
if leaf.trim().is_empty() {
return Ok(Empty);
}
let (atoms, dimensions, _) = comment_atoms(&leaf, units);
if atoms.len() == 1 && leaf.trim() == atoms[0] {
return Ok(Text(s.into()));
}
if !re!(r"[a-zA-Z_?]").is_match(&leaf) && !*changed {
return Ok(Text(s.into()));
}
*changed = true;
*list |= atoms.len() > 1 && dimensions.iter().all(Option::is_some);
match atoms.as_slice() {
[] => Ok(Empty),
[atom] => Ok(Text(atom.clone())),
_ if dimensions.iter().all(Option::is_some)
&& dimensions
.iter()
.all(|dimension| *dimension == dimensions[0]) =>
{
Ok(Text(
atoms
.iter()
.map(|atom| format!("({atom})"))
.collect::<Vec<_>>()
.join(" + "),
))
}
[left, right]
if matches!(dimensions[0], Some(CommentUnit::Physical(_)))
&& matches!(dimensions[1], Some(CommentUnit::Physical(_)))
&& dimensions[0] != dimensions[1] =>
{
Ok(Text(format!("({left}) / ({right})")))
}
_ if comparison
&& atoms.iter().any(|atom| atom.ends_with('%'))
&& dimensions.contains(&Some(CommentUnit::Currency)) =>
{
Ok(DiscardComparison)
}
_ => Ok(Absent),
}
}
fn validate_comment_additions(
input: &str,
depth: usize,
units: &units::Units,
) -> Result<(), Error> {
if depth > 64 {
return Err(Error("internal_error".into()));
}
if let Some((left, right)) = super::syntax::split_last(input, &[" and ", " or "]) {
validate_comment_additions(left, depth + 1, units)?;
return validate_comment_additions(right, depth + 1, units);
}
if !crate::plugins::arithmetic::operators(input)
.is_some_and(|ops| ops.iter().any(|(_, op)| matches!(op, '+' | '-')))
{
return Ok(());
}
let (mut changed, mut list) = (false, false);
let CommentOperand::Text(lowered) = comment_expression(
input,
true,
false,
depth + 1,
units,
&mut changed,
&mut list,
)?
else {
return Err(Error("internal_error".into()));
};
let context = Context::default();
if units
.evaluate(&lowered, &context)
.is_some_and(|result| result.is_ok())
|| crate::plugins::arithmetic::eval(&lowered).is_some()
{
Ok(())
} else {
Err(Error("internal_error".into()))
}
}
fn comment_atoms(
leaf: &str,
units: &units::Units,
) -> (Vec<String>, Vec<Option<CommentUnit>>, Vec<usize>) {
let mut atoms = vec![];
let mut dimensions = vec![];
let mut rate_divisions = vec![];
for number in re!(r"(?i)(?:\d[\d,]*(?:\.\d+)?|\.\d+)(?:e[+-]?\d+)?").find_iter(leaf) {
let before = leaf[..number.start()].trim_end();
let after = &leaf[number.end()..];
let prefix = re!(r"(?i)(?:us\$|[$€£¥₿])$")
.find(before)
.map(|m| m.as_str());
let unit_start = after.trim_start();
let unit_limit = unit_start.find(['.', ';']).unwrap_or(unit_start.len());
let unit_end = super::syntax::unit_prefix(&unit_start[..unit_limit], |unit| {
units.unit(unit).is_some() || finance::currency(unit).is_some()
});
let tail = unit_end.map(|end| &unit_start[..end]);
if let Some(tail) = tail {
let start = number.end() + after.len() - unit_start.len();
rate_divisions.extend(
tail.char_indices()
.filter(|(_, character)| *character == '/')
.map(|(at, _)| start + at),
);
}
let atom = if let Some(prefix) = prefix {
format!("{prefix}{}", number.as_str())
} else if let Some(tail) = tail {
format!("{} {tail}", number.as_str())
} else if after.starts_with('%') {
format!("{}%", number.as_str())
} else {
number.as_str().into()
};
dimensions.push(
units
.quantity(&atom)
.map(|q| CommentUnit::Physical(q.unit.dimension))
.or_else(|| {
finance::amount(&atom)
.filter(|(_, code)| !code.is_empty())
.map(|_| CommentUnit::Currency)
}),
);
atoms.push(atom);
}
(atoms, dimensions, rate_divisions)
}