use crate::{plugins::units::Units, re};
pub(super) fn rewrite(s: &str, units: &Units) -> String {
if let Some(c) = re!(r"^(\(.+\)) / a (day|hour|minute|second|week) in (.+)$").captures(s) {
return format!("{} / (1 {}) in {}", &c[1], &c[2], &c[3]);
}
if let Some(c) = re!(r"^(?:take )?(?:the )?sum of (.+) and (.+), multiply by their difference in absolute value, (?:and )?reduce the result$").captures(s) {
return format!("((({}) + ({})) * abs(({}) - ({}))) in reduced fraction", &c[1], &c[2], &c[1], &c[2]);
}
if let Some(base) = s.strip_suffix(" using ordinary order of operations") {
return base.to_string();
}
if let Some(base) = s.strip_suffix(" using standard order of operations") {
return base.to_string();
}
if let Some(expression) = sequence(s) {
return expression;
}
if let Some(base) = s
.strip_prefix("start with ")
.or_else(|| s.strip_prefix("starting with "))
.or_else(|| s.strip_prefix("take "))
{
return base.to_string();
}
if let Some(c) = re!(
r"^(?:the )?(square root|cube root) of (.+?) \+ (?:the )?(square root|cube root) of (.+)$"
)
.captures(s)
{
let root = |kind: &str| {
if kind == "square root" {
"sqrt"
} else {
"cbrt"
}
};
return format!("{}({}) + {}({})", root(&c[1]), &c[2], root(&c[3]), &c[4]);
}
if let Some(c) = re!(r"^(?:the )?(square root|cube root|square|cube) of (.+)$").captures(s) {
return match &c[1] {
"square root" => format!("sqrt({})", &c[2]),
"cube root" => format!("cbrt({})", &c[2]),
"square" => format!("({})^2", &c[2]),
_ => format!("({})^3", &c[2]),
};
}
if let Some(c) = re!(r"^(\(.+\)) (squared|cubed)$").captures(s) {
return format!("{}^{}", &c[1], if &c[2] == "squared" { 2 } else { 3 });
}
let normalized =
re!(r"(?P<count>[+-]?(?:\d+(?:\.\d*)?|\.\d+)|\([^()]+\))\s+(?:a )?workweeks?\b")
.replace_all(s, |c: ®ex::Captures| {
crate::plugins::arithmetic::eval(crate::plugins::syntax::ungroup(&c["count"]))
.map(|count| count * 5.0)
.filter(|count| count.is_finite())
.map_or_else(
|| c[0].to_string(),
|count| format!("{count} business days"),
)
});
let s = normalized.as_ref();
if let Some(c) = re!(r"^round (.+) to the nearest (.+)$").captures(s) {
let increment =
if units.unit(&c[2]).is_some() || crate::plugins::named_quantities::recognizes(&c[2]) {
format!("1 {}", &c[2])
} else {
c[2].to_string()
};
return format!("round({}, {increment})", &c[1]);
}
if let Some(c) =
re!(r"^(.+),? then convert (?:the result|it) (?:to|into|as|in) (.+)$").captures(s)
{
return format!(
"({}) in {}",
c[1].trim_end_matches(',').trim_start_matches("convert "),
&c[2]
);
}
if let Some(c) = re!(r"^add (.+) to (.+)$").captures(s)
&& crate::plugins::calendar::date(&c[2], &crate::Context::default()).is_some()
{
let duration = c[1].trim_end_matches(',');
let parts = re!(r",? then |,? and |,\s*")
.split(duration)
.collect::<Vec<_>>();
if parts.iter().all(|part| {
units
.quantity(part.trim())
.is_some_and(|q| q.unit.dimension == [0, 0, 1, 0, 0, 0, 0, 0])
|| re!(r"^\d+ (?:business days?|workdays?|weekdays?|quarters?)$")
.is_match(part.trim())
}) {
return format!("({}) + ({})", &c[2], parts.join(" + "));
}
}
if let Some(c) =
re!(r"^(?:the )?(sum|total|combined price|product) of (.+) and (.+)$").captures(s)
{
return format!(
"({}) {} ({})",
&c[2],
if &c[1] == "product" { "*" } else { "+" },
&c[3]
);
}
if let Some(c) = re!(r"^(?:the )?sum of (.+)$").captures(s)
&& c[1].contains(',')
{
return format!("sum({})", &c[1]);
}
if let Some(c) = re!(r"^(?:add|sum) the first (\d+) positive integers$").captures(s) {
return format!("{} * ({} + 1) / 2", &c[1], &c[1]);
}
if let Some(c) = re!(r"^sum the squares of (.+)$").captures(s) {
return c[1]
.split(',')
.map(|value| format!("({})^2", value.trim()))
.collect::<Vec<_>>()
.join(" + ");
}
if let Some((left, right)) = crate::plugins::syntax::split_last(s, &[" * ", " / "])
&& (sum_phrase(right) || right.starts_with("the difference between "))
{
let operator = s[left.len()..s.len() - right.len()].trim();
return format!("{left} {operator} ({right})");
}
if let Some(c) = re!(r"^subtract (.+) from (.+)$").captures(s) {
return format!("({}) - ({})", &c[2], &c[1]);
}
if let Some(c) = re!(r"^(?:the )?difference between (.+) and (.+)$").captures(s) {
return format!("({}) - ({})", &c[1], &c[2]);
}
if let Some(c) = re!(r"^(?:the )?reciprocal of (.+)$").captures(s) {
return format!("1 / ({})", &c[1]);
}
if let Some(c) = re!(r"^(?:the )?quotient of (.+)$").captures(s) {
return c[1].to_owned();
}
if let Some(c) = re!(r"^add (.+?) to (.+)$").captures(s) {
return format!("({}) + ({})", &c[2], &c[1]);
}
if let Some(c) = re!(r"^(add) (.+?) and (.+)$|^(multiply|divide) (.+?) by (.+)$").captures(s) {
let (operation, left, right) = if c.get(1).is_some() {
(&c[1], &c[2], &c[3])
} else {
(&c[4], &c[5], &c[6])
};
return format!(
"({}) {} ({})",
left,
match operation {
"add" => "+",
"multiply" => "*",
_ => "/",
},
right
);
}
if let Some(c) = re!(r"^(.+), then ([+-]) (.+)$").captures(s) {
return format!("({}) {} ({})", &c[1], &c[2], &c[3]);
}
if let Some((left, right)) =
crate::plugins::syntax::split_last(s, &[" less ", " subtract ", " add "])
{
let operation = s[left.len()..s.len() - right.len()].trim();
return format!(
"({}) {} ({})",
left,
if operation == "add" { "+" } else { "-" },
right
);
}
re!(r"\b([\d.]+) (squared|cubed)\b")
.replace_all(s, |c: ®ex::Captures| {
format!("({})^{}", &c[1], if &c[2] == "squared" { 2 } else { 3 })
})
.into_owned()
}
pub(super) fn fractions(input: &str) -> String {
let calendar =
crate::plugins::syntax::split_last(input, &[" after ", " before ", " from ", " to "])
.is_some_and(|(_, date)| {
crate::plugins::calendar::date(date, &crate::Context::default()).is_some()
});
let normalized = if calendar {
re!(r"\b(\d+) quarters?\b")
.replace_all(input, |c: ®ex::Captures| {
format!(
"{} months",
c[1].parse::<u64>()
.ok()
.and_then(|n| n.checked_mul(3))
.map_or_else(|| c[1].to_string(), |n| n.to_string())
)
})
.into_owned()
} else {
input.to_string()
};
let input = normalized.as_str();
let fractions = re!(r"\b(\d+|a|an) (half|halves|thirds?|quarters?|fifths?|sixths?|sevenths?|eighths?|ninths?|tenths?|twelfths?)\b|\b(half)\b")
.replace_all(input, |c: ®ex::Captures| {
let name = c.get(2).map_or("half", |m| m.as_str());
let denominator = match name.trim_end_matches('s') {
"half" | "halve" => 2, "third" => 3, "quarter" => 4, "fifth" => 5,
"sixth" => 6, "seventh" => 7, "eighth" => 8, "ninth" => 9, "tenth" => 10, _ => 12,
};
let numerator = c.get(1).map_or("1", |m| m.as_str());
let numerator = if matches!(numerator, "a" | "an") { "1" } else { numerator };
format!("({numerator}/{denominator})")
});
let mixed = re!(r"\b(\d+) and \((\d+/\d+)\)").replace_all(&fractions, "($1 + ($2))");
let mixed = re!(r"\b(\d+) (\d+/\d+)\b").replace_all(&mixed, "($1 + ($2))");
let of = re!(r"\((\d+/\d+)\) (?:of (?:a )?|the )").replace_all(&mixed, "($1) * ");
re!(r"\b(\d+/\d+) of ")
.replace_all(&of, "($1) * ")
.into_owned()
}
pub(super) fn sum_phrase(input: &str) -> bool {
re!(r"^(?:the )?(?:sum|total|combined price) of ").is_match(input)
}
pub(super) fn sequence(s: &str) -> Option<String> {
let groups = crate::plugins::syntax::groups(s).unwrap_or_default();
if let Some(c) = re!(r"(?:, (?:and then |then |and )?| then | and (?:then )?)(?:(add|subtract|subtracting) |(multiply|divide)(?: (?:it|the result|the total))? by |(square|cube) (?:it|the result|the sum|their sum)|convert (?:the total|the result|the sum|it) (?:to|into) )")
.captures_iter(s)
.filter(|c| !groups.iter().any(|group| group.contains(&c.get(0).unwrap().start())))
.last()
{
let instruction = c.get(0).unwrap();
let left = s[..instruction.start()].trim_start_matches("convert ");
let mut right = &s[instruction.end()..];
if c.get(1).is_some_and(|operation| matches!(operation.as_str(), "subtract" | "subtracting")) {
for suffix in [" from the quotient", " from the result", " from the total", " from the sum"] {
if let Some(operand) = right.strip_suffix(suffix) {
right = operand;
break;
}
}
}
if let Some(unary) = c.get(3) {
return if right.trim().is_empty() {
Some(format!("({left})^{}", if unary.as_str() == "square" { 2 } else { 3 }))
} else {
None
};
}
let operator = match c.get(1).or_else(|| c.get(2)).map(|m| m.as_str()) {
Some("add") => "+",
Some("subtract" | "subtracting") => "-",
Some("multiply") => "*",
Some("divide") => "/",
_ => return Some(format!("({left}) in {right}")),
};
return Some(format!("({left}) {operator} ({right})"));
}
None
}
pub(super) fn annotation(s: &str) -> Option<String> {
if let Some(c) = re!(r"^(.+), then express the result as a (?:percentage|%)$").captures(s) {
return Some(format!("({}) is what % of 1", &c[1]));
}
if let Some(c) =
re!(r"^(.+?)(?:; give (?:the )?simplified fraction|, expressed as a reduced fraction|(?:,? and |, )(?:give (?:the answer as )?|express (?:the )?result as )(?:a |the )?(?:reduced|simplified) fraction|(?:,? and |, )(?:give|express|report) (?:the )?(?:result|answer) as (?:a |the )?fraction)$")
.captures(s)
{
return Some(format!("({}) in reduced fraction", &c[1]));
}
if let Some(c) = re!(r"^(.+?)(?:,? and |, )(?:give|report|express) (?:the )?(?:remainder|result|answer) (?:in|as|to) (.+)$").captures(s) {
return Some(format!("({}) in {}", &c[1], &c[2]));
}
if let Some(c) = re!(r"^(.+), expressing (?:the )?answer in (.+)$").captures(s) {
return Some(format!("({}) in {}", &c[1], &c[2]));
}
None
}
pub(super) fn division_operands(input: &str) -> String {
re!(r"(?:,)? divided by ([+-]?(?:\d(?:[\d,]*\d)?(?:\.\d+)?|\.\d+)/[+-]?(?:\d(?:[\d,]*\d)?(?:\.\d+)?|\.\d+))")
.replace_all(input, |c: ®ex::Captures| {
let tail = input[c.get(0).unwrap().end()..].trim_start();
let complete = tail.is_empty()
|| tail.starts_with([')', '+', '-', '*', ',', ';'])
|| re!(r"^(?:plus|minus|times|multiplied by|divided by|and|then|in|to|as|using)\b")
.is_match(tail);
if complete {
format!(" / ({})", &c[1])
} else {
c[0].to_owned()
}
})
.into_owned()
}