use super::{calendar, compositions::Compositions, integer_queries, syntax};
use crate::{Context, Error, Outcome, Plugin, re};
use num_bigint::BigInt;
use std::cmp::Ordering;
#[derive(Default)]
pub struct Predicates {
engine: Compositions,
}
impl Plugin for Predicates {
fn rewrite(&self, input: &str, _: &Context) -> Outcome {
let original = input.trim().trim_end_matches(['?', '.']);
let input = re!(r"(?i)^(?:evaluate |is it true that )").replace(original, "");
if !recognized(&input) {
return None;
}
wording(&input, 0).or_else(|| (input != original).then(|| Ok(input.into_owned())))
}
fn evaluate(&self, input: &str, context: &Context) -> Outcome {
let input = input.trim().trim_end_matches('?');
recognized(input).then(|| self.condition(input, context, 0).map(|v| v.to_string()))
}
}
impl Predicates {
fn condition(&self, input: &str, context: &Context, depth: usize) -> Result<bool, Error> {
if depth > 64 {
return Err(Error("expression_too_deep".into()));
}
let input = syntax::ungroup(input);
for (phrases, conjunction) in [(&[" or ", "||"][..], false), (&[" and ", "&&"][..], true)] {
if let Some((left, right)) = split_folded(input, phrases) {
let a = self.condition(left, context, depth + 1)?;
let b = self.condition(right, context, depth + 1)?;
return Ok(if conjunction { a && b } else { a || b });
}
}
let folded = input.to_ascii_lowercase();
if folded.starts_with("not ") {
return self.condition(&input[4..], context, depth + 1).map(|v| !v);
}
if matches!(folded.as_str(), "true" | "false") {
return Ok(folded == "true");
}
let comparisons = comparisons(input).ok_or_else(|| Error("invalid_expression".into()))?;
if comparisons.is_empty() {
return Err(Error("invalid_expression".into()));
}
let mut from = 0;
let mut result = true;
for (index, (at, operation)) in comparisons.iter().enumerate() {
let end = comparisons
.get(index + 1)
.map_or(input.len(), |(at, _)| *at);
result &= self.compare(
&input[from..*at],
operation,
&input[at + operation.len()..end],
context,
)?;
from = at + operation.len();
}
Ok(result)
}
fn compare(
&self,
left: &str,
operation: &str,
right: &str,
context: &Context,
) -> Result<bool, Error> {
let left = left.trim();
let right = right.trim();
if left.is_empty() || right.is_empty() {
return Err(Error("invalid_expression".into()));
}
let a = calendar::date(left, context);
let b = calendar::date(right, context);
let order = if a.is_some() || b.is_some() {
let (a, b) = a.zip(b).ok_or_else(|| Error("incompatible_units".into()))?;
a.cmp(&b)
} else if let (Some(a), Some(b)) = (exact_scalar(left)?, exact_scalar(right)?) {
exact_order(a, b)
} else {
self.engine.quantity_order(left, right, context)?
};
Ok(match operation {
"=" | "==" => order == Ordering::Equal,
"!=" | "<>" => order != Ordering::Equal,
"<" => order == Ordering::Less,
">" => order == Ordering::Greater,
"<=" => order != Ordering::Greater,
">=" => order != Ordering::Less,
_ => return Err(Error("invalid_expression".into())),
})
}
}
pub(crate) fn recognized(input: &str) -> bool {
recognizes_condition(input, 0)
}
fn recognizes_condition(input: &str, depth: usize) -> bool {
if depth > 64 {
return true;
}
let inner = syntax::ungroup(input);
if comparisons(inner).is_some_and(|v| v.first().is_some_and(|(at,_)| operand_shape(&inner[..*at])))
|| re!(r"(?i)^(?:true\b|false\b|not\b)|^(?:is|are) .+ (?:less than|greater than|equal to|at most|at least|before|after) ").is_match(inner)
{ return true; }
if re!(r"(?i)^(?:is .+ (?:even|odd)|.+ is (?:even|odd))$").is_match(inner) {
return true;
}
if syntax::groups(inner).is_some_and(|groups| {
groups
.into_iter()
.any(|range| recognizes_condition(&inner[range], depth + 1))
}) {
return true;
}
for phrases in [&[" and ", "&&"][..], &[" or ", "||"][..]] {
if let Some((a, b)) = split_folded(inner, phrases) {
return recognizes_condition(a, depth + 1) && recognizes_condition(b, depth + 1);
}
}
false
}
fn operand_shape(input: &str) -> bool {
let input = input.trim();
input.starts_with(|c: char| c.is_ascii_digit() || "(+-−$€£¥".contains(c))
|| re!(r"(?i)^(?:abs|sqrt|square|sum|mean|min|max|round|pow|factorial|choose|gcd|lcm|real|rational)\s*\(")
.is_match(input)
|| re!(r"(?i)^(?:today|tomorrow|yesterday|now|true|false)$").is_match(input)
}
fn wording(input: &str, depth: usize) -> Outcome {
if depth > 64 {
return Some(Err(Error("expression_too_deep".into())));
}
syntax::rewrite_groups(input, |part| {
for phrases in [&[" or ", "||"][..], &[" and ", "&&"][..]] {
if let Some((a, b)) = split_folded(part, phrases) {
let left = wording(a, depth + 1);
let right = wording(b, depth + 1);
if left.is_some() || right.is_some() {
let separator = &part[a.len()..part.len() - b.len()];
return Some(left.unwrap_or_else(|| Ok(a.into())).and_then(|a| {
right
.unwrap_or_else(|| Ok(b.into()))
.map(|b| format!("{a}{separator}{b}"))
}));
}
return None;
}
}
if part.to_ascii_lowercase().starts_with("not ") {
return wording(&part[4..], depth + 1)
.map(|result| result.map(|expression| format!("not ({expression})")));
}
if let Some(c) =
re!(r"(?i)^(?:is (.+) (even|odd)|(.+) is (even|odd))$").captures(part.trim())
{
let value = c.get(1).or_else(|| c.get(3)).unwrap().as_str();
let kind = c.get(2).or_else(|| c.get(4)).unwrap().as_str();
let operation = if kind.eq_ignore_ascii_case("even") {
"=="
} else {
"!="
};
return Some(Ok(format!("({value}) mod 2 {operation} 0")));
}
let c = re!(r"(?i)^(?:is|are) (.+?) (less than or equal to|greater than or equal to|not equal to|equal to|less than|greater than|at most|at least|before|after) (.+)$").captures(part.trim())?;
let operation = match c[2].to_ascii_lowercase().as_str() {
"less than or equal to" | "at most" => "<=",
"greater than or equal to" | "at least" => ">=",
"not equal to" => "!=",
"equal to" => "==",
"less than" | "before" => "<",
_ => ">",
};
Some(Ok(format!("({}) {operation} ({})", &c[1], &c[3])))
})
}
fn split_folded<'a>(input: &'a str, phrases: &[&str]) -> Option<(&'a str, &'a str)> {
let folded = input
.to_ascii_lowercase()
.replace(" or equal to ", " __ equal to ");
let (left, right) = syntax::split_last(&folded, phrases)?;
Some((&input[..left.len()], &input[input.len() - right.len()..]))
}
fn comparisons(input: &str) -> Option<Vec<(usize, &str)>> {
let mut depth = 0i32;
let mut found = vec![];
let mut skip = 0;
for (at, c) in input.char_indices() {
if at < skip {
continue;
}
match c {
'(' => depth += 1,
')' => depth -= 1,
'<' | '>' | '=' | '!' if depth == 0 => {
let tail = &input[at..];
if tail.starts_with("<<") || tail.starts_with(">>") {
skip = at + 2;
continue;
}
if let Some(op) = ["<=", ">=", "==", "!=", "<>", "<", ">", "="]
.into_iter()
.find(|op| tail.starts_with(op))
{
found.push((at, &input[at..at + op.len()]));
skip = at + op.len();
}
}
_ => {}
}
if depth < 0 {
return None;
}
}
(depth == 0).then_some(found)
}
fn exact_scalar(input: &str) -> Result<Option<(BigInt, BigInt)>, Error> {
let input = syntax::ungroup(input).trim();
let normalized = if re!(r"^[+-]?\d{1,3}(?:,\d{3})+(?:\.\d*)?(?:[eE][+-]?\d+)?$").is_match(input)
{
input.replace(',', "")
} else {
input.into()
};
match integer_queries::ratio_value(&normalized) {
Ok(value) => Ok(Some(value)),
Err(e)
if matches!(
e.0.as_str(),
"invalid_integer_expression" | "non_rational_expression"
) =>
{
Ok(None)
}
Err(e) => Err(e),
}
}
fn exact_order((a, ad): (BigInt, BigInt), (b, bd): (BigInt, BigInt)) -> Ordering {
(a * bd).cmp(&(b * ad))
}