use super::super::{
arithmetic, integer_queries, syntax,
units::{Unit, Units},
};
use crate::{Context, Error, Outcome, re};
use num_bigint::BigInt;
use num_traits::{One, Signed, Zero};
use std::cmp::Ordering;
#[derive(Clone)]
enum Number {
Ratio(BigInt, BigInt),
InvalidDecimal,
}
#[derive(Clone)]
struct Value {
number: Number,
unit: Option<Unit>,
currency: Option<&'static str>,
boolean: bool,
date: Option<chrono::NaiveDate>,
date_result: bool,
comment_list: bool,
}
impl Value {
fn boolean(value: bool) -> Self {
Self {
number: Number::Ratio(BigInt::from(u8::from(value)), BigInt::one()),
unit: None,
currency: None,
boolean: true,
date: None,
date_result: false,
comment_list: false,
}
}
fn truth(&self) -> Result<bool, Error> {
match &self.number {
Number::Ratio(n, _) if !self.has_quantity() => Ok(!n.is_zero()),
_ => Err(Error("null_result".into())),
}
}
fn has_quantity(&self) -> bool {
self.unit.is_some() || self.currency.is_some()
}
}
pub(super) fn evaluate(input: &str, context: &Context) -> Outcome {
let admission = input.replace("<<", "").replace(">>", "");
if !re!(r"==|!=|<=|>=|=>|=<|<>|<|>|&&|\|\|").is_match(&admission) {
return None;
}
let head = syntax::ungroup(input.trim());
if head.starts_with(char::is_alphabetic)
&& !re!(r"^(?:true|false|not|abs|sqrt|round|floor|ceil|sin|cos|tan|asin|acos|atan|exp|ln|log|min|max|sum|mean|average|median|clamp|cbrt|factorial)\b").is_match(head)
{
let end = comparisons(head).ok()?.first().map_or(head.len(), |(at, _)| *at);
let left = head[..end].trim();
if super::super::calendar::date(left, context).is_none()
&& arithmetic::eval(left).is_none()
&& Units::default().expression(left, 0).is_err()
{
return None;
}
}
Some((|| {
let input = super::super::compositions::standard_temporal_units(input);
let value = expression(&input, &Units::default(), context, 0)?;
if value.boolean {
Ok(value.truth()?.to_string())
} else {
let Number::Ratio(n, d) = value.number else {
return Err(Error("internal_error".into()));
};
use num_traits::ToPrimitive;
let coordinate = n.to_f64().ok_or_else(invalid)? / d.to_f64().ok_or_else(invalid)?;
Ok(if let Some(code) = value.currency {
super::super::money(coordinate, code)
} else if let Some(unit) = value.unit {
super::super::units::format_quantity(coordinate, &unit)
} else {
crate::number(coordinate)
})
}
})())
}
fn invalid() -> Error {
Error("invalid_expression".into())
}
fn domain() -> Error {
Error("internal_error".into())
}
fn expression(input: &str, units: &Units, context: &Context, depth: usize) -> Result<Value, Error> {
if depth > 64 {
return Err(invalid());
}
let input = syntax::ungroup(input.trim());
for (phrases, and) in [(&["||", " or "][..], false), (&["&&", " and "][..], true)] {
if let Some((a, b)) = syntax::split_last(input, phrases) {
if !input.contains(['(', '<', '>', '='])
&& !input.contains("&&")
&& !input.contains("||")
{
return Err(invalid());
}
let a = expression(a, units, context, depth + 1)?.truth()?;
let b = expression(b, units, context, depth + 1)?.truth()?;
return Ok(Value::boolean(if and { a && b } else { a || b }));
}
}
let operations = comparisons(input)?;
if !operations.is_empty() {
let mut value = operand(&input[..operations[0].0], units, context, depth + 1)?;
for (index, (at, op)) in operations.iter().enumerate() {
let end = operations.get(index + 1).map_or(input.len(), |(at, _)| *at);
let right = &input[at + op.len()..end];
if right.trim().is_empty() && index + 1 == operations.len() {
return value.ok_or_else(domain);
}
let right = operand(right, units, context, depth + 1)?;
value = match (value, right) {
(None, other) | (other, None) => other,
(Some(left), Some(right)) => {
let date_result = left.date.is_some()
|| right.date.is_some()
|| left.date_result
|| right.date_result;
let mut result = Value::boolean(compare(&left, op, &right, context)?);
result.date_result = date_result;
Some(result)
}
};
}
return value.ok_or_else(domain);
}
if input == "true" || input == "false" {
return Ok(Value::boolean(input == "true"));
}
if let Some(date) = super::super::calendar::date(input, context) {
return Ok(Value {
number: Number::Ratio(BigInt::zero(), BigInt::one()),
unit: None,
currency: None,
boolean: false,
date: Some(date),
date_result: false,
comment_list: false,
});
}
let mut transformed = input.to_string();
for range in syntax::groups(input).ok_or_else(invalid)?.into_iter().rev() {
if re!(r"==|!=|<=|>=|<|>|&&|\|\|").is_match(&input[range.clone()]) {
let value = expression(&input[range.clone()], units, context, depth + 1)?.truth()?;
transformed.replace_range(range, if value { "1" } else { "0" });
}
}
if let Some(number) = scalar(&transformed)? {
return Ok(Value {
number,
unit: None,
currency: None,
boolean: false,
date: None,
date_result: false,
comment_list: false,
});
}
if let Some(c) =
re!(r"^([+-]?(?:\d[\d,]*(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?)\s*(.+)$").captures(&transformed)
&& let Some(unit) = units.unit(&c[2])
{
let number = scalar(&c[1])?.ok_or_else(invalid)?;
return Ok(Value {
number,
unit: Some(unit),
currency: None,
boolean: false,
date: None,
date_result: false,
comment_list: false,
});
}
let quantity = units.expression(&transformed, 0);
if quantity.is_err()
&& let Some((coordinate, code)) =
super::super::finance::expression(&transformed, context, 0)
&& !code.is_empty()
{
let number = scalar(&coordinate.to_string())?.ok_or_else(invalid)?;
return Ok(Value {
number,
unit: None,
currency: Some(code),
boolean: false,
date: None,
date_result: false,
comment_list: false,
});
}
let quantity = quantity.map_err(|e| {
if e.0 == "internal_error" || re!(r"\bfor\b").is_match(&transformed) {
domain()
} else {
invalid()
}
})?;
let nan = re!(r"(?:\d[\d,]*(?:\.\d+)?|\.\d+)[eE]([+-]?\d+)")
.captures_iter(&transformed)
.any(|c| {
c[1].parse::<i32>()
.ok()
.is_some_and(super::super::decimal::scientific_scale_invalid)
});
if nan && transformed.contains('/') {
return Err(domain());
}
let number = if nan {
Number::InvalidDecimal
} else {
scalar(&quantity.base.to_string())?.ok_or_else(invalid)?
};
let mut unit = quantity.unit;
unit.scale = 1.0;
unit.offset = 0.0;
Ok(Value {
number,
unit: (unit.dimension != [0; 8]).then_some(unit),
currency: None,
boolean: false,
date: None,
date_result: false,
comment_list: false,
})
}
fn operand(
input: &str,
units: &Units,
context: &Context,
depth: usize,
) -> Result<Option<Value>, Error> {
match super::super::compositions::standard_comparison_operand(input) {
Some(Ok(Some((lowered, list)))) => {
let mut value = expression(&lowered, units, context, depth)?;
value.comment_list |= list;
Ok(Some(value))
}
Some(Ok(None)) => Ok(None),
Some(Err(error)) => Err(error),
None => expression(input, units, context, depth).map(Some),
}
}
fn scalar(input: &str) -> Result<Option<Number>, Error> {
if let Some(inner) = input
.trim()
.strip_prefix("abs(")
.and_then(|s| s.strip_suffix(')'))
{
return scalar(inner).map(|value| {
value.map(|number| match number {
Number::Ratio(n, d) => Number::Ratio(n.abs(), d),
other => other,
})
});
}
if !re!(r"^[0-9eE.,\s()+*/^−-]+$").is_match(input) {
return Ok(None);
}
let mut nan = false;
let normalized = re!(r"(?:\d[\d,]*(?:\.\d+)?|\.\d+)(?:[eE][+-]?\d+)?").replace_all(
input,
|c: ®ex::Captures| {
let raw = if c[0].contains(',') {
if re!(r"^\d{1,3}(?:,\d{3})+(?:\.\d*)?(?:[eE][+-]?\d+)?$").is_match(&c[0]) {
c[0].replace(',', "")
} else {
c[0].split(',').next().unwrap_or("").into()
}
} else {
c[0].into()
};
if raw.split_once(['e', 'E']).is_some_and(|(_, exponent)| {
exponent
.parse::<i32>()
.ok()
.is_some_and(super::super::decimal::scientific_scale_invalid)
}) {
nan = true;
"1".into()
} else {
raw
}
},
);
match integer_queries::ratio_value(&normalized) {
Ok((n, d)) => Ok(Some(if nan {
Number::InvalidDecimal
} else {
Number::Ratio(n, d)
})),
Err(e) if e.0 == "division_by_zero" => Err(domain()),
Err(_) => Ok(arithmetic::eval(input)
.and_then(|n| integer_queries::ratio_value(&n.to_string()).ok())
.map(|(n, d)| Number::Ratio(n, d))),
}
}
fn order(a: &Number, b: &Number) -> Ordering {
match (a, b) {
(Number::Ratio(a, ad), Number::Ratio(b, bd)) => (a * bd).cmp(&(b * ad)),
(Number::InvalidDecimal, Number::InvalidDecimal) => Ordering::Equal,
(Number::InvalidDecimal, _) => Ordering::Less,
(_, Number::InvalidDecimal) => Ordering::Greater,
}
}
fn base(value: &Value, context: &Context) -> Result<Number, Error> {
let (scale, offset) = if let Some(unit) = &value.unit {
(unit.scale, unit.offset)
} else if let Some(code) = value.currency {
let rate = context
.rates
.get(code)
.copied()
.filter(|rate| rate.is_finite() && *rate > 0.0)
.ok_or_else(domain)?;
(1.0 / rate, 0.0)
} else {
return Ok(value.number.clone());
};
let Number::Ratio(n, d) = &value.number else {
return Ok(Number::InvalidDecimal);
};
let Some(Number::Ratio(scale, sd)) = scalar(&scale.to_string())? else {
return Err(domain());
};
let Some(Number::Ratio(offset, od)) = scalar(&offset.to_string())? else {
return Err(domain());
};
Ok(Number::Ratio(
n * scale * &od + offset * d * &sd,
d * sd * od,
))
}
fn compare(a: &Value, op: &str, b: &Value, context: &Context) -> Result<bool, Error> {
if let Some((a, b)) = a.date.zip(b.date) {
return apply(a.cmp(&b), op);
}
if a.date.is_some()
|| b.date.is_some()
|| (a.date_result && b.has_quantity())
|| (b.date_result && a.has_quantity())
{
return Err(domain());
}
if (a.boolean && b.has_quantity()) || (b.boolean && a.has_quantity()) {
return Err(Error("null_result".into()));
}
if a.currency.is_some() && b.unit.is_some()
|| b.currency.is_some() && a.unit.is_some()
|| a.unit
.as_ref()
.zip(b.unit.as_ref())
.is_some_and(|(a, b)| a.dimension != b.dimension)
{
if a.comment_list || b.comment_list {
return Err(domain());
}
return match op {
"==" => Ok(false),
"!=" => Ok(true),
_ => Err(domain()),
};
}
let mut a = a.clone();
let mut b = b.clone();
if !a.has_quantity() {
a.unit = b.unit.clone();
a.currency = b.currency;
} else if !b.has_quantity() {
b.unit = a.unit.clone();
b.currency = a.currency;
}
let order = if a.currency.is_some() && a.currency == b.currency {
order(&a.number, &b.number)
} else {
order(&base(&a, context)?, &base(&b, context)?)
};
apply(order, op)
}
fn apply(order: Ordering, op: &str) -> Result<bool, Error> {
Ok(match op {
"==" => order == Ordering::Equal,
"!=" => order != Ordering::Equal,
"<" => order == Ordering::Less,
">" | "<>" => order == Ordering::Greater,
"<=" | "=<" => order != Ordering::Greater,
">=" | "=>" => order != Ordering::Less,
_ => return Err(invalid()),
})
}
pub(crate) fn comparisons(input: &str) -> Result<Vec<(usize, &str)>, Error> {
let mut depth = 0i32;
let mut skip = 0;
let mut found = vec![];
for (at, c) in input.char_indices() {
if at < skip {
continue;
}
match c {
'(' => depth += 1,
')' => depth -= 1,
'<' | '>' | '=' | '!' if depth == 0 => {
if input[at..].starts_with("<<") || input[at..].starts_with(">>") {
skip = at + 2;
continue;
}
if let Some(op) = ["==", "!=", "<=", ">=", "=>", "=<", "<>", "<", ">"]
.into_iter()
.find(|op| input[at..].starts_with(op))
{
found.push((at, &input[at..at + op.len()]));
skip = at + op.len();
}
}
_ => {}
}
if depth < 0 {
return Err(invalid());
}
}
if depth != 0 {
return Err(invalid());
}
Ok(found)
}