use super::{AlgebraQueries, integer_queries, syntax};
use crate::{Context, Error, ModelPosition, Outcome, Plugin, re};
use num_rational::BigRational;
use std::collections::{HashMap, HashSet};
const MAX_BINDINGS: usize = 16;
const MAX_TOKENS: usize = 128;
fn invalid() -> Error {
Error("invalid_expression".into())
}
#[derive(Clone, Copy, PartialEq, Eq)]
enum Model {
General,
RotatingDisk,
ThermalExpansion,
ElectricalRelation,
}
struct Binding<'a> {
name: &'a str,
role: String,
value: &'a str,
}
fn annotation(prefix: &str) -> Result<String, Error> {
let mut role = prefix.trim().trim_start_matches(',').trim();
if role
.get(..4)
.is_some_and(|prefix| prefix.eq_ignore_ascii_case("and "))
{
role = role[4..].trim();
}
if role.len() > 64 || !role.chars().all(|c| c.is_ascii_alphabetic() || c == ' ') {
return Err(invalid());
}
Ok(role.to_ascii_lowercase())
}
fn binding_separator(input: &str) -> Result<std::ops::Range<usize>, Error> {
let mut depth = 0usize;
for (index, character) in input.char_indices() {
if depth == 0
&& let Some(separator) = re!(r"(?i)^(?:,\s+|\s+and\s+)").find(&input[index..])
{
return Ok(index..index + separator.end());
}
match character {
'(' => {
depth += 1;
if depth > 32 {
return Err(Error("expression_too_deep".into()));
}
}
')' => depth = depth.checked_sub(1).ok_or_else(invalid)?,
_ => {}
}
}
Err(invalid())
}
fn bindings(input: &str) -> Result<Vec<Binding<'_>>, Error> {
let matches = re!(r"(?i)\b([A-Za-z][A-Za-z0-9_]*)\s*(?:=|is\b)")
.captures_iter(input)
.map(|c| (c.get(0).unwrap(), c.get(1).unwrap().as_str()))
.collect::<Vec<_>>();
if matches.is_empty() || matches.len() > MAX_BINDINGS {
return Err(invalid());
}
let mut parsed: Vec<Binding<'_>> = Vec::new();
for (index, (assignment, name)) in matches.iter().enumerate() {
let role = if index == 0 {
annotation(&input[..assignment.start()])?
} else {
let between = &input[matches[index - 1].0.end()..assignment.start()];
let delimiter = binding_separator(between)?;
let value = between[..delimiter.start].trim();
if value.is_empty() {
return Err(invalid());
}
parsed[index - 1].value = value;
annotation(&between[delimiter.start..])?
};
parsed.push(Binding {
name,
role,
value: "",
});
}
let last = input[matches.last().unwrap().0.end()..].trim();
if last.is_empty() {
return Err(invalid());
}
parsed.last_mut().unwrap().value = last;
let mut seen = HashSet::new();
if parsed.iter().any(|binding| !seen.insert(binding.name)) {
return Err(invalid());
}
Ok(parsed)
}
enum Goal<'a> {
Quantity(&'a str, &'a str),
Percentage(&'a str),
Duration(&'a str),
Scalar(&'a str),
Role(&'a str, &'a str),
}
fn goal(question: &str) -> Result<Goal<'_>, Error> {
if let Some(c) =
re!(r"(?i)^what (current|voltage|resistance) ([A-Za-z][A-Za-z0-9_]*) do i get$")
.captures(question)
{
return Ok(Goal::Role(
c.get(2).unwrap().as_str(),
c.get(1).unwrap().as_str(),
));
}
if let Some(c) = re!(r"(?i)^(?:tell me|calculate) ([A-Za-z][A-Za-z0-9_]*)$").captures(question)
{
return Ok(Goal::Scalar(c.get(1).unwrap().as_str()));
}
if let Some(c) =
re!(r"(?i)^what (?:[a-z ]+ )?([A-Za-z][A-Za-z0-9_]*) does the formula give in (.+)$")
.captures(question)
{
return Ok(Goal::Quantity(
c.get(1).unwrap().as_str(),
c.get(2).unwrap().as_str(),
));
}
if let Some(c) = re!(r"(?i)^what is ([A-Za-z][A-Za-z0-9_]*) in (.+)$").captures(question) {
return Ok(Goal::Quantity(
c.get(1).unwrap().as_str(),
c.get(2).unwrap().as_str(),
));
}
if let Some(c) =
re!(r"(?i)^what (?:[a-z ]+ )?([A-Za-z][A-Za-z0-9_]*) occurs in (.+)$").captures(question)
{
return Ok(Goal::Quantity(
c.get(1).unwrap().as_str(),
c.get(2).unwrap().as_str(),
));
}
if let Some(c) =
re!(r"(?i)^what is ([A-Za-z][A-Za-z0-9_]*) as a percentage$").captures(question)
{
return Ok(Goal::Percentage(c.get(1).unwrap().as_str()));
}
if let Some(c) = re!(r"(?i)^how many (seconds?) does transmission take$").captures(question) {
return Ok(Goal::Duration(c.get(1).unwrap().as_str()));
}
if let Some(c) = re!(r"(?i)^what is ([A-Za-z][A-Za-z0-9_]*)$").captures(question) {
return Ok(Goal::Scalar(c.get(1).unwrap().as_str()));
}
if let Some(c) = re!(r"(?i)^return ([A-Za-z][A-Za-z0-9_]*)$").captures(question) {
return Ok(Goal::Scalar(c.get(1).unwrap().as_str()));
}
if let Some(c) = re!(r"(?i)^what ([A-Za-z][A-Za-z0-9_]*) comes out$").captures(question) {
return Ok(Goal::Scalar(c.get(1).unwrap().as_str()));
}
Err(invalid())
}
fn degree_question(question: &str) -> (&str, bool) {
if let Some(goal) = question.strip_suffix(", with the angle explicitly interpreted in degrees")
{
(goal, true)
} else if let Some(goal) = question.strip_suffix(" with both angles measured in degrees") {
(goal, true)
} else {
(question, false)
}
}
fn clauses(input: &str) -> Option<(String, String)> {
if let Some(c) = re!(r"(?is)^(the electrical relation is [A-Za-z][A-Za-z0-9_]*\s*=.+?)\.\s*if (.+?),\s*(what\b.+)$").captures(input) {
return Some((c[1].into(), format!("with {}, {}", &c[2], &c[3])));
}
if let Some(c) = re!(r"(?is)^for ([A-Za-z][A-Za-z0-9_]*\s*=.+?),\s*(?:take|use) (.+?)(?:;|\s+and)\s*((?:tell me|calculate)\b.+)$").captures(input) {
return Some((format!("formula is {}", &c[1]), format!("with {}, {}", &c[2], &c[3])));
}
if let Some(c) =
re!(r"(?is)^using my formula (.+?),\s*with (.+),\s*(what\b.+)$").captures(input)
{
return Some((
format!("my formula is {}", &c[1]),
format!("with {}, {}", &c[2], &c[3]),
));
}
if let Some(c) =
re!(r"(?is)^my model says (.+?)\.\s*given (.+),\s*(return\b.+)$").captures(input)
{
return Some((
format!("my model is {}", &c[1]),
format!("with {}, {}", &c[2], &c[3]),
));
}
if let Some(c) = re!(r"(?is)^the rule is (.+?)\.\s*set (.+);\s*(what\b.+)$").captures(input) {
return Some((
format!("the rule is {}", &c[1]),
format!("with {}, {}", &c[2], &c[3]),
));
}
if let Some(c) = re!(r"(?is)^use formula (.+?)\s+with (.+);\s*(what\b.+)$").captures(input) {
return Some((
format!("formula is {}", &c[1]),
format!("with {}, {}", &c[2], &c[3]),
));
}
if let Some(c) = re!(r"(?is)^use (.+?)\s+with (.+);\s*(what\b.+)$").captures(input) {
return Some((
format!("formula is {}", &c[1]),
format!("with {}, {}", &c[2], &c[3]),
));
}
let (statement, tail) = input.split_once(';')?;
Some((statement.into(), tail.into()))
}
fn scalar_literal(value: &str) -> Result<String, Error> {
let value = value.trim();
if let Some(scalar) = value.strip_suffix('%') {
let (n, d) = integer_queries::ratio_value(scalar.trim())?;
let fraction = BigRational::new(n, d * 100);
return Ok(format!(
"rational({},{})",
fraction.numer(),
fraction.denom()
));
}
match integer_queries::ratio_value(value) {
Ok((n, d)) => Ok(format!("rational({n},{d})")),
Err(error)
if matches!(
error.0.as_str(),
"invalid_integer_expression" | "non_rational_expression"
) =>
{
Ok(value.into())
}
Err(error) => Err(error),
}
}
fn exact_integer(expression: &str) -> Result<Option<String>, Error> {
match integer_queries::ratio_value(expression) {
Ok((numerator, denominator)) if denominator == 1.into() => {
let display = integer_queries::decimal(&numerator);
if display.len() > 4096 {
return Err(Error("integer_limit".into()));
}
Ok(Some(display))
}
Ok(_) => Ok(None),
Err(error)
if matches!(
error.0.as_str(),
"invalid_integer_expression" | "non_rational_expression"
) =>
{
Ok(None)
}
Err(error) => Err(error),
}
}
#[derive(Clone)]
enum Token<'a> {
Number(&'a str),
Name(&'a str),
Symbol(char),
}
fn tokens<'a>(input: &'a str, values: &HashMap<&str, String>) -> Result<Vec<Token<'a>>, Error> {
let mut result = Vec::new();
let mut rest = input;
let mut calls = Vec::new();
while !rest.is_empty() {
rest = rest.trim_start();
if rest.is_empty() {
break;
}
if let Some(number) = re!(r"^(?:\d+(?:\.\d*)?|\.\d+)(?:[eE][+-]?\d+)?").find(rest) {
result.push(Token::Number(number.as_str()));
rest = &rest[number.end()..];
} else if let Some(name) = re!(r"^[A-Za-z][A-Za-z0-9_]*").find(rest) {
result.push(Token::Name(name.as_str()));
rest = &rest[name.end()..];
} else {
let symbol = rest.chars().next().ok_or_else(invalid)?;
if !matches!(symbol, '+' | '-' | '*' | '/' | '^' | '(' | ')' | ',') {
return Err(invalid());
}
if symbol == '(' {
calls.push(
matches!(result.last(), Some(Token::Name(name)) if !values.contains_key(name)),
);
if calls.len() > 32 {
return Err(Error("expression_too_deep".into()));
}
} else if symbol == ')' {
calls.pop().ok_or_else(invalid)?;
} else if symbol == ',' && calls.last() != Some(&true) {
return Err(invalid());
}
result.push(Token::Symbol(symbol));
rest = &rest[symbol.len_utf8()..];
}
if result.len() > MAX_TOKENS {
return Err(Error("integer_limit".into()));
}
}
if !calls.is_empty() || result.is_empty() {
return Err(invalid());
}
Ok(result)
}
fn multiply_before(
previous: &Token<'_>,
current: &Token<'_>,
values: &HashMap<&str, String>,
) -> bool {
let ends = matches!(
previous,
Token::Number(_) | Token::Name(_) | Token::Symbol(')')
);
let starts = matches!(current, Token::Name(_) | Token::Symbol('('));
ends && starts
&& !matches!((previous, current), (Token::Name(name), Token::Symbol('(')) if !values.contains_key(name))
}
fn declared_product<'a>(
name: &str,
values: &HashMap<&'a str, String>,
) -> Result<Vec<&'a str>, Error> {
let mut paths: Vec<Option<Vec<&'a str>>> = vec![None; name.len() + 1];
let mut ambiguous = vec![false; name.len() + 1];
paths[name.len()] = Some(Vec::new());
for index in (0..name.len()).rev() {
if !name.is_char_boundary(index) {
continue;
}
for &part in values.keys() {
if !name[index..].starts_with(part) {
continue;
}
let next = index + part.len();
if ambiguous[next] {
ambiguous[index] = true;
break;
}
if let Some(tail) = &paths[next] {
if paths[index].is_some() {
ambiguous[index] = true;
break;
}
let mut path = Vec::with_capacity(tail.len() + 1);
path.push(part);
path.extend(tail.iter().copied());
paths[index] = Some(path);
}
}
}
if ambiguous[0] {
return Err(invalid());
}
paths[0].take().ok_or_else(invalid)
}
fn substituted(rhs: &str, values: &HashMap<&str, String>) -> Result<String, Error> {
let tokens = tokens(rhs, values)?;
let mut used = HashSet::new();
let mut output = String::new();
for (index, token) in tokens.iter().enumerate() {
if index > 0
&& matches!(token, Token::Number(_))
&& matches!(
&tokens[index - 1],
Token::Number(_) | Token::Name(_) | Token::Symbol(')')
)
{
return Err(invalid());
}
if index > 0 && multiply_before(&tokens[index - 1], token, values) {
output.push('*');
}
match token {
Token::Number(number) => output.push_str(number),
Token::Symbol(symbol) => output.push(*symbol),
Token::Name(name)
if !values.contains_key(name)
&& matches!(tokens.get(index + 1), Some(Token::Symbol('('))) =>
{
output.push_str(name)
}
Token::Name(name) => {
let parts = if values.contains_key(name) {
vec![*name]
} else {
declared_product(name, values)?
};
for (part_index, part) in parts.iter().enumerate() {
if part_index != 0 {
output.push('*');
}
used.insert(*part);
output.push('(');
output.push_str(values.get(*part).ok_or_else(invalid)?);
output.push(')');
}
}
}
if output.len() > 4096 {
return Err(Error("integer_limit".into()));
}
}
if used.len() != values.len() {
return Err(invalid());
}
Ok(output)
}
fn scalar_output(expression: String, position: ModelPosition) -> String {
if position == ModelPosition::Operand {
format!("({expression})")
} else {
format!("algebra_declared_scalar({expression})")
}
}
fn quantity_output(expression: String, target: &str, position: ModelPosition) -> String {
if position == ModelPosition::Operand {
format!("(({expression}) in {target})")
} else {
format!("({expression}) in {target}")
}
}
fn facts_first(
algebra: &AlgebraQueries,
input: &str,
context: &Context,
position: ModelPosition,
) -> Outcome {
let c = re!(r"(?is)^(?:(?:use|let|given|set)\s+|(?:facts|values|measurements)(?:\s+are\s+|:\s*)|i\s+(?:have|recorded|measured|used)\s+)(.+?)(?:\s+to\s+|[,;]\s*|\.\s+|\s+and\s+)(?:calculate|evaluate|find)\s+(.+)$")
.captures(input)?;
if !re!(r"(?i)^[A-Za-z][A-Za-z0-9_]*\s*(?:=|is\b)").is_match(c[1].trim()) {
return None;
}
Some((|| {
let mut values = HashMap::new();
for binding in bindings(&c[1])? {
values.insert(binding.name, scalar_literal(binding.value)?);
}
let goal = c[2].trim();
let (goal, target) =
if let Some((expression, target)) = syntax::split_last(goal, syntax::CONVERSIONS) {
if expression.trim().is_empty() || target.trim().is_empty() {
return Err(invalid());
}
(expression.trim(), Some(target.trim()))
} else {
(goal, None)
};
let expression = substituted(goal, &values)?;
if let Some(target) = target {
algebra
.engine
.quantity_value(&expression, target, context)?;
return Ok(quantity_output(expression, target, position));
}
if exact_integer(&expression)?.is_some() {
return Ok(scalar_output(expression, position));
}
match algebra.engine.quantity_value(&expression, "1", context) {
Ok(_) => Ok(scalar_output(expression, position)),
Err(error) if error.0 == "incompatible_units" => {
algebra
.engine
.evaluate(&expression, context)
.ok_or_else(invalid)??;
Ok(if position == ModelPosition::Operand {
format!("({expression})")
} else {
expression
})
}
Err(error) => Err(error),
}
})())
}
pub(super) fn rewrite(
algebra: &AlgebraQueries,
input: &str,
context: &Context,
position: ModelPosition,
) -> Outcome {
if let Some(result) = facts_first(algebra, input, context, position) {
return Some(result);
}
let (statement, tail) = clauses(input)?;
let (header, rhs) = statement.split_once('=')?;
let (model, lhs) =
if let Some(c) = re!(r"(?i)^(.+?)\bis\s+([A-Za-z][A-Za-z0-9_]*)\s*$").captures(header) {
let model = match c[1].trim().to_ascii_lowercase().as_str() {
"the kinetic energy of a rotating disk" => Model::RotatingDisk,
"the electrical relation" => Model::ElectricalRelation,
_ => Model::General,
};
(model, c.get(2).unwrap().as_str())
} else {
let c = re!(r"(?i)^use thermal expansion\s+([A-Za-z][A-Za-z0-9_]*)\s*$")
.captures(header)?;
(Model::ThermalExpansion, c.get(1).unwrap().as_str())
};
if rhs.contains('=') {
return Some(Err(invalid()));
}
Some((|| {
let c = re!(
r"(?is)^\s*(?:with|using)\s+(.+),\s*((?:what|how|return|tell me|calculate)\b.+)\s*$"
)
.captures(&tail)
.ok_or_else(invalid)?;
let bindings = bindings(&c[1])?;
let (question, degrees) = degree_question(c[2].trim());
let goal = goal(question)?;
let (target, percentage, inferred_duration, scalar) = match goal {
Goal::Quantity(name, unit) => {
if name != lhs {
return Err(invalid());
}
(unit.trim(), false, false, false)
}
Goal::Percentage(name) => {
if name != lhs {
return Err(invalid());
}
("1", true, false, false)
}
Goal::Duration(unit) => (unit, false, true, false),
Goal::Scalar(name) => {
if name != lhs {
return Err(invalid());
}
("1", false, false, true)
}
Goal::Role(name, role) => {
if name != lhs || model != Model::ElectricalRelation {
return Err(invalid());
}
let unit = super::super::electrical_queries::supplied_formula_target(role)
.ok_or_else(invalid)?;
(unit, false, false, false)
}
};
let trig =
degrees && scalar && model == Model::General && re!(r"\b(?:sin|cos)\(").is_match(rhs);
if degrees && !trig {
return Err(invalid());
}
if inferred_duration {
if !header
.to_ascii_lowercase()
.contains("transmission time model")
{
return Err(invalid());
}
algebra
.engine
.quantity_value(&format!("1 {target}"), "s", context)?;
}
let mut values = HashMap::new();
let mut saw_angle = false;
for binding in bindings {
if binding.name == lhs {
return Err(invalid());
}
let normalized = match model {
Model::General if trig => {
match algebra.engine.quantity_value(binding.value, "rad", context) {
Ok(_) => {
saw_angle = true;
format!("({})", binding.value)
}
Err(error) if error.0 == "incompatible_units" => {
algebra.engine.quantity_value(binding.value, "1", context)?;
scalar_literal(binding.value)?
}
Err(error) => return Err(error),
}
}
Model::General => scalar_literal(binding.value)?,
Model::RotatingDisk => super::super::mechanics::supplied_formula_role(
&binding.role,
binding.value,
&algebra.engine,
context,
)?,
Model::ThermalExpansion => super::super::thermal_queries::supplied_formula_role(
&binding.role,
binding.value,
&algebra.engine,
context,
)?,
Model::ElectricalRelation => {
super::super::electrical_queries::supplied_formula_role(
&binding.role,
binding.value,
&algebra.engine,
context,
)?
}
};
values.insert(binding.name, normalized);
}
if trig && !saw_angle {
return Err(invalid());
}
let rhs = rhs.trim().replace('×', "*").replace('²', "^2");
let expression = substituted(&rhs, &values)?;
if !scalar || exact_integer(&expression)?.is_none() {
algebra
.engine
.quantity_value(&expression, target, context)?;
}
if scalar {
Ok(scalar_output(expression, position))
} else if percentage {
if position == ModelPosition::Operand {
Ok(format!("({expression})"))
} else {
Ok(format!("algebra_declared_percent({expression})"))
}
} else {
Ok(quantity_output(expression, target, position))
}
})())
}
pub(super) fn evaluate(algebra: &AlgebraQueries, input: &str, context: &Context) -> Outcome {
if let Some(inner) = input
.strip_prefix("algebra_declared_scalar(")
.and_then(|s| s.strip_suffix(')'))
{
return Some((|| {
if let Some(display) = exact_integer(inner)? {
return Ok(display);
}
let result = algebra.engine.quantity_value(inner, "1", context)?;
Ok(crate::number(result))
})());
}
let inner = input
.strip_prefix("algebra_declared_percent(")?
.strip_suffix(')')?;
Some((|| {
let result = algebra.engine.quantity_value(inner, "1", context)? * 100.0;
if !result.is_finite() {
return Err(Error("numeric_overflow".into()));
}
Ok(format!("{}%", crate::number(result)))
})())
}