Dezio/src/calc.rs
astar76 709f9b707a Dezio: an all-in-one Discord bot in Rust
Music with a live player, Last.fm, video downloads, games, AI chat, moderation, logging,
a web dashboard and a Game Boy Activity.

Co-Authored-By: Claude Sonnet 5.5 <[email protected]>
2026-10-24 11:47:43 -05:00

657 lines
22 KiB
Rust

This file contains ambiguous Unicode characters

This file contains Unicode characters that might be confused with other characters. If you think that this is intentional, you can safely ignore this warning. Use the Escape button to reveal them.

//! The calculator's brain: real expressions (`2^10`, `sqrt(16)`, `sin 30`, `5!`), plus the old
//! `calc 16 sqrt` / `calc 5 add 3` word style. Numbers are exact big integers until a division or a
//! function makes them decimals, like Python's.
use num_bigint::BigInt;
use num_traits::{Signed, ToPrimitive, Zero, One};
use regex::Regex;
use std::fmt;
use std::sync::OnceLock;
#[derive(Debug, Clone, PartialEq)]
pub struct CalcError(pub String);
impl fmt::Display for CalcError {
fn fmt(&self, f: &mut fmt::Formatter<'_>) -> fmt::Result {
f.write_str(&self.0)
}
}
fn err<T>(s: &str) -> Result<T, CalcError> {
Err(CalcError(s.to_string()))
}
#[derive(Debug, Clone, PartialEq)]
pub enum Num {
Int(BigInt),
Float(f64),
}
impl Num {
fn f(&self) -> f64 {
match self {
Num::Int(i) => i.to_f64().unwrap_or(f64::INFINITY * if i.is_negative() { -1.0 } else { 1.0 }),
Num::Float(f) => *f,
}
}
}
// ---- normalising what people type ------------------------------------------------------------
const NUMBER: &str = r"-?\d+(?:\.\d+)?";
fn old_binary(op: &str) -> Option<&'static str> {
Some(match op {
"+" | "add" | "plus" | "addition" => "+",
"-" | "sub" | "subtract" | "minus" => "-",
"*" | "x" | "×" | "mult" | "multiply" | "times" => "*",
"/" | "÷" | "div" | "divide" => "/",
"%" | "mod" | "modulo" => "%",
"^" | "**" | "pow" | "power" | "exp" | "exponent" => "**",
_ => return None,
})
}
fn old_unary(op: &str) -> Option<&'static str> {
Some(match op {
"sqrt" | "√" => "sqrt",
"sin" | "sine" => "sin",
"cos" | "cosine" => "cos",
"tan" | "tangent" => "tan",
"abs" | "absolute" => "abs",
"round" => "round",
"ceil" | "ceiling" => "ceil",
"floor" => "floor",
"log" | "logarithm" => "log",
"ln" => "ln",
"factorial" | "!" => "factorial",
_ => return None,
})
}
struct Res {
number: Regex,
times: Regex,
root: Regex,
fact: Regex,
func: Regex,
implicit: Regex,
paren: Regex,
comma: Regex,
}
fn res() -> &'static Res {
static R: OnceLock<Res> = OnceLock::new();
R.get_or_init(|| Res {
number: Regex::new(&format!("^{NUMBER}$")).unwrap(),
times: Regex::new(r"([\d)])\s*x\s*([\d(])").unwrap(),
root: Regex::new(r"√\s*(\d+(?:\.\d+)?|\([^()]*\))").unwrap(),
fact: Regex::new(r"(\d+(?:\.\d+)?|\))\s*!").unwrap(),
func: Regex::new(r"\b(sin|cos|tan|sqrt|ln|log|abs)\s+(-?\d+(?:\.\d+)?)").unwrap(),
implicit: Regex::new(r"(\d)\s*(pi|π|tau|phi|\()").unwrap(),
paren: Regex::new(r"\)\s*(\(|\d)").unwrap(),
comma: Regex::new(r",\s*").unwrap(),
})
}
pub fn normalise(expr: &str) -> String {
let r = res();
let text = expr.trim().trim_matches('`').to_lowercase();
let words: Vec<&str> = text.split_whitespace().collect();
if (2..=3).contains(&words.len()) && r.number.is_match(words[0]) {
let op = words[1];
if words.len() == 2 {
if let Some(f) = old_unary(op) {
return format!("{f}({})", words[0]);
}
} else if r.number.is_match(words[2]) {
if op == "log" || op == "logarithm" {
return format!("log({}, {})", words[0], words[2]);
}
if let Some(b) = old_binary(op) {
return format!("{} {b} {}", words[0], words[2]);
}
}
}
let mut t = text.replace('×', "*").replace('÷', "/").replace('−', "-").replace('^', "**");
t = r.comma.replace_all(&t, ", ").into_owned();
t = r.times.replace_all(&t, "$1*$2").into_owned(); // 5 x 3
t = r.root.replace_all(&t, "sqrt($1)").into_owned(); // √16, √(9+7)
t = r.fact.replace_all(&t, "factorial($1)").into_owned(); // 5!
t = r.func.replace_all(&t, "$1($2)").into_owned(); // sin 30
t = r.implicit.replace_all(&t, "$1*$2").into_owned(); // 2pi, 3(4)
t = r.paren.replace_all(&t, ")*$1").into_owned(); // (2)(3)
t.replace('π', "pi")
}
// ---- parsing and evaluating ------------------------------------------------------------------
#[derive(Debug, Clone, PartialEq)]
enum Tok {
Num(String),
Name(String),
Op(&'static str),
LParen,
RParen,
Comma,
}
fn tokenize(s: &str) -> Result<Vec<Tok>, CalcError> {
let c: Vec<char> = s.chars().collect();
let mut out = vec![];
let mut i = 0;
while i < c.len() {
let ch = c[i];
if ch.is_whitespace() {
i += 1;
} else if ch.is_ascii_digit() || (ch == '.' && c.get(i + 1).is_some_and(char::is_ascii_digit)) {
let start = i;
while i < c.len() && (c[i].is_ascii_digit() || c[i] == '.') {
i += 1;
}
if i < c.len() && (c[i] == 'e') && c.get(i + 1).is_some_and(|d| d.is_ascii_digit() || *d == '-' || *d == '+') {
i += 2;
while i < c.len() && c[i].is_ascii_digit() {
i += 1;
}
}
out.push(Tok::Num(c[start..i].iter().collect()));
} else if ch.is_alphabetic() || ch == '_' {
let start = i;
while i < c.len() && (c[i].is_alphanumeric() || c[i] == '_') {
i += 1;
}
out.push(Tok::Name(c[start..i].iter().collect()));
} else {
i += 1;
out.push(match ch {
'(' => Tok::LParen,
')' => Tok::RParen,
',' => Tok::Comma,
'+' => Tok::Op("+"),
'-' => Tok::Op("-"),
'%' => Tok::Op("%"),
'*' if c.get(i) == Some(&'*') => {
i += 1;
Tok::Op("**")
}
'*' => Tok::Op("*"),
'/' if c.get(i) == Some(&'/') => {
i += 1;
Tok::Op("//")
}
'/' => Tok::Op("/"),
_ => return err("only numbers, + - * / % ^ and math functions are allowed"),
});
}
}
Ok(out)
}
struct Parser {
toks: Vec<Tok>,
pos: usize,
/// The first name that isn't a constant; reported only if the rest reads fine (like Python's SyntaxError first).
unknown: Option<String>,
}
impl Parser {
fn peek(&self) -> Option<&Tok> {
self.toks.get(self.pos)
}
fn next(&mut self) -> Option<Tok> {
self.pos += 1;
self.toks.get(self.pos - 1).cloned()
}
fn expr(&mut self) -> Result<Num, CalcError> {
let mut left = self.term()?;
while let Some(Tok::Op(op @ ("+" | "-"))) = self.peek().cloned() {
self.pos += 1;
let right = self.term()?;
left = binary(op, left, right)?;
}
Ok(left)
}
fn term(&mut self) -> Result<Num, CalcError> {
let mut left = self.factor()?;
while let Some(Tok::Op(op @ ("*" | "/" | "//" | "%"))) = self.peek().cloned() {
self.pos += 1;
let right = self.factor()?;
left = binary(op, left, right)?;
}
Ok(left)
}
fn factor(&mut self) -> Result<Num, CalcError> {
match self.peek() {
Some(Tok::Op("-")) => {
self.pos += 1;
Ok(match self.factor()? {
Num::Int(i) => Num::Int(-i),
Num::Float(f) => Num::Float(-f),
})
}
Some(Tok::Op("+")) => {
self.pos += 1;
self.factor()
}
_ => self.power(),
}
}
fn power(&mut self) -> Result<Num, CalcError> {
let base = self.atom()?;
if let Some(Tok::Op("**")) = self.peek() {
self.pos += 1;
let exp = self.factor()?;
return binary("**", base, exp);
}
Ok(base)
}
fn atom(&mut self) -> Result<Num, CalcError> {
match self.next() {
Some(Tok::Num(n)) => {
if n.chars().all(|c| c.is_ascii_digit()) {
Ok(Num::Int(n.parse().map_err(|_| CalcError("I couldn't read that expression".into()))?))
} else {
n.parse::<f64>().map(Num::Float).map_err(|_| CalcError("I couldn't read that expression".into()))
}
}
Some(Tok::LParen) => {
let v = self.expr()?;
match self.next() {
Some(Tok::RParen) => Ok(v),
_ => err("I couldn't read that expression"),
}
}
Some(Tok::Name(name)) => {
if self.peek() == Some(&Tok::LParen) {
self.pos += 1;
let mut args = vec![];
if self.peek() != Some(&Tok::RParen) {
loop {
args.push(self.expr()?);
match self.next() {
Some(Tok::Comma) => continue,
Some(Tok::RParen) => break,
_ => return err("I couldn't read that expression"),
}
}
} else {
self.pos += 1;
}
call(&name, args)
} else {
match name.as_str() {
"pi" => Ok(Num::Float(std::f64::consts::PI)),
"e" => Ok(Num::Float(std::f64::consts::E)),
"tau" => Ok(Num::Float(std::f64::consts::TAU)),
"phi" => Ok(Num::Float((1.0 + 5f64.sqrt()) / 2.0)),
_ => {
self.unknown.get_or_insert(name);
Ok(Num::Int(BigInt::zero()))
}
}
}
}
_ => err("I couldn't read that expression"),
}
}
}
fn is_zero(n: &Num) -> bool {
match n {
Num::Int(i) => i.is_zero(),
Num::Float(f) => *f == 0.0,
}
}
fn floor_div_mod(a: &BigInt, b: &BigInt) -> (BigInt, BigInt) {
let (mut q, mut r) = (a / b, a % b);
if !r.is_zero() && (r.is_negative() != b.is_negative()) {
q -= 1;
r += b;
}
(q, r)
}
fn binary(op: &str, l: Num, r: Num) -> Result<Num, CalcError> {
use Num::*;
if op == "**" {
let (lf, rf) = (l.f(), r.f());
if rf.abs() > 10_000.0 || (lf.abs() > 1.0 && rf * lf.abs().log10() > 4000.0) {
return err("that number is too big");
}
return Ok(match (&l, &r) {
(Int(a), Int(b)) if !b.is_negative() => Int(num_traits::pow::Pow::pow(a, b.to_u32().unwrap_or(0))),
_ => {
let v = lf.powf(rf);
if v.is_nan() {
return err("the answer isn't a real number");
}
Float(v)
}
});
}
if matches!(op, "/" | "//" | "%") && is_zero(&r) {
return err("can't divide by zero");
}
Ok(match (op, l, r) {
("+", Int(a), Int(b)) => Int(a + b),
("-", Int(a), Int(b)) => Int(a - b),
("*", Int(a), Int(b)) => Int(a * b),
("//", Int(a), Int(b)) => Int(floor_div_mod(&a, &b).0),
("%", Int(a), Int(b)) => Int(floor_div_mod(&a, &b).1),
("/", a, b) => Float(a.f() / b.f()),
("+", a, b) => Float(a.f() + b.f()),
("-", a, b) => Float(a.f() - b.f()),
("*", a, b) => Float(a.f() * b.f()),
("//", a, b) => Float((a.f() / b.f()).floor()),
("%", a, b) => {
let (x, y) = (a.f(), b.f());
Float(x - y * (x / y).floor())
}
_ => return err("only numbers, + - * / % ^ and math functions are allowed"),
})
}
fn log_base(x: f64, base: f64) -> Result<f64, CalcError> {
if x <= 0.0 {
return err("log is only defined for positive numbers");
}
if base <= 0.0 || base == 1.0 {
return err("the log base must be positive and not 1");
}
Ok(x.ln() / base.ln())
}
/// Python's round(): halves go to the even neighbour.
fn round_half_even(x: f64, digits: i32) -> f64 {
let m = 10f64.powi(digits);
let y = x * m;
let r = y.round();
let r = if (y - y.trunc()).abs() == 0.5 && r % 2.0 != 0.0 { r - y.signum() } else { r };
r / m
}
fn whole(n: &Num) -> Result<BigInt, CalcError> {
match n {
Num::Int(i) => Ok(i.clone()),
Num::Float(f) if f.fract() == 0.0 => Ok(BigInt::from(*f as i128)),
_ => err("needs a whole number"),
}
}
fn gcd(a: BigInt, b: BigInt) -> BigInt {
let (mut a, mut b) = (a.abs(), b.abs());
while !b.is_zero() {
let t = &a % &b;
a = b;
b = t;
}
a
}
fn call(name: &str, args: Vec<Num>) -> Result<Num, CalcError> {
use Num::*;
let one = |args: &[Num]| -> Result<f64, CalcError> {
match args {
[a] => Ok(a.f()),
_ => Err(CalcError(format!("`{name}` takes one number"))),
}
};
let rad = f64::to_radians;
let float = |v: f64| -> Result<Num, CalcError> {
if v.is_nan() { err("the answer isn't a real number") } else { Ok(Float(v)) }
};
match name {
"sqrt" => {
let x = one(&args)?;
if x < 0.0 { err("can't take the square root of a negative number") } else { float(x.sqrt()) }
}
"cbrt" => float(one(&args)?.cbrt()),
"abs" => match args.as_slice() {
[Int(i)] => Ok(Int(i.abs())),
_ => float(one(&args)?.abs()),
},
"log" => match args.as_slice() {
[x] => float(log_base(x.f(), 10.0)?),
[x, b] => float(log_base(x.f(), b.f())?),
_ => err("`log` takes a number and an optional base"),
},
"ln" => float(log_base(one(&args)?, std::f64::consts::E)?),
"log2" => float(log_base(one(&args)?, 2.0)?),
"log10" => float(log_base(one(&args)?, 10.0)?),
"sin" => float(rad(one(&args)?).sin()),
"cos" => float(rad(one(&args)?).cos()),
"tan" => {
let x = one(&args)?;
if ((x.abs() % 180.0) - 90.0).abs() < 1e-9 { err("tan is undefined at that angle") } else { float(rad(x).tan()) }
}
"asin" => float(one(&args)?.asin().to_degrees()),
"acos" => float(one(&args)?.acos().to_degrees()),
"atan" => float(one(&args)?.atan().to_degrees()),
"round" => match args.as_slice() {
[x] => float(round_half_even(x.f(), 0)),
[x, n] => float(round_half_even(x.f(), n.f() as i32)),
_ => err("`round` takes a number and optional digits"),
},
"ceil" => Ok(Int(BigInt::from(one(&args)?.ceil() as i128))),
"floor" => Ok(Int(BigInt::from(one(&args)?.floor() as i128))),
"factorial" | "fact" => {
let n = match args.as_slice() {
[a] => whole(a).map_err(|_| CalcError("factorial needs a whole number ≥ 0".into()))?,
_ => return err("`factorial` takes one number"),
};
if n.is_negative() {
return err("factorial needs a whole number ≥ 0");
}
if n > BigInt::from(3000) {
return err("that factorial is too big");
}
let mut acc = BigInt::one();
for i in 2..=n.to_u32().unwrap_or(0) {
acc *= i;
}
Ok(Int(acc))
}
"exp" => float(one(&args)?.exp()),
"max" | "min" if !args.is_empty() => {
let pick = args.iter().cloned().reduce(|a, b| {
let less = a.f() < b.f();
if (name == "max") == less { b } else { a }
});
pick.ok_or_else(|| CalcError("needs at least one number".into()))
}
"hypot" => match args.as_slice() {
[a, b] => float(a.f().hypot(b.f())),
_ => err("`hypot` takes two numbers"),
},
"gcd" | "lcm" => match args.as_slice() {
[a, b] => {
let (a, b) = (whole(a)?, whole(b)?);
let g = gcd(a.clone(), b.clone());
Ok(Int(if name == "gcd" { g } else if g.is_zero() { BigInt::zero() } else { (&a * &b).abs() / g }))
}
_ => Err(CalcError(format!("`{name}` takes two numbers"))),
},
"rad" => float(one(&args)?.to_radians()),
"deg" => float(one(&args)?.to_degrees()),
_ => Err(CalcError(format!("I don't know the function `{name}`"))),
}
}
/// (normalised text, value)
pub fn evaluate(expr: &str) -> Result<(String, Num), CalcError> {
let text = normalise(expr);
if text.chars().count() > 300 {
return err("that expression is too long");
}
let toks = tokenize(&text).map_err(|e| if e.0.starts_with("only") { e } else { CalcError("I couldn't read that expression".into()) })?;
let mut p = Parser { toks, pos: 0, unknown: None };
let value = p.expr();
if p.pos != p.toks.len() || (value.is_err() && p.unknown.is_some() && p.pos < p.toks.len()) {
return err("I couldn't read that expression");
}
let value = value?;
if let Some(name) = p.unknown {
return Err(CalcError(format!("I don't know `{name}`")));
}
if let Num::Float(f) = &value {
if f.is_infinite() {
return err("that number is too big");
}
}
Ok((text, value))
}
// ---- showing numbers -------------------------------------------------------------------------
fn group(int_part: &str) -> String {
crate::converters::thousands(int_part.parse().unwrap_or(0))
}
/// Python's `f"{x:.10e}"`: 1.2345678900e+15
fn sci(v: f64) -> String {
let s = format!("{v:.10e}");
match s.split_once('e') {
Some((m, e)) => {
let n: i32 = e.parse().unwrap_or(0);
format!("{m}e{}{:02}", if n < 0 { '-' } else { '+' }, n.abs())
}
None => s,
}
}
pub fn fmt_number(v: &Num) -> String {
match v {
Num::Float(f) => {
if f.is_nan() {
return "nan".into();
}
if f.is_infinite() {
return if *f < 0.0 { "-inf".into() } else { "inf".into() };
}
if f.fract() == 0.0 && f.abs() < 1e15 {
let i = *f as i64;
return format!("{}{}", if i < 0 { "-" } else { "" }, group(&i.abs().to_string()));
}
if f.abs() >= 1e15 || (*f != 0.0 && f.abs() < 1e-6) {
return sci(*f);
}
let s = format!("{:.10}", f.abs());
let (int, frac) = s.split_once('.').unwrap_or((&s, ""));
let frac = frac.trim_end_matches('0');
format!("{}{}{}{}", if *f < 0.0 { "-" } else { "" }, group(int), if frac.is_empty() { "" } else { "." }, frac)
}
Num::Int(i) => {
let text = i.abs().to_string();
let sign = if i.is_negative() { "-" } else { "" };
if text.len() > 30 {
return format!("{sign}{}.{}e+{} ({} digits)", &text[..1], &text[1..11], text.len() - 1, crate::converters::thousands(text.len() as u64));
}
// group with commas by hand (can exceed u64)
let mut out = String::new();
for (n, c) in text.chars().enumerate() {
if n > 0 && (text.len() - n) % 3 == 0 {
out.push(',');
}
out.push(c);
}
format!("{sign}{out}")
}
}
}
pub fn pretty(text: &str) -> String {
text.replace("**", "^").replace('*', "×").replace('/', "÷").replace("pi", "π")
}
#[cfg(test)]
mod tests {
use super::*;
fn calc(s: &str) -> String {
match evaluate(s) {
Ok((_, v)) => fmt_number(&v),
Err(e) => format!("ERR {e}"),
}
}
#[test]
fn arithmetic_and_precedence() {
assert_eq!(calc("5 * (3 + 2)"), "25");
assert_eq!(calc("2+3*4"), "14");
assert_eq!(calc("-2**2"), "-4");
assert_eq!(calc("2**3**2"), "512");
assert_eq!(calc("7 // 2"), "3");
assert_eq!(calc("-7 // 2"), "-4");
assert_eq!(calc("-7 % 3"), "2");
assert_eq!(calc("10 / 4"), "2.5");
assert_eq!(calc("1/3"), "0.3333333333");
}
#[test]
fn friendly_syntax() {
assert_eq!(calc("2^10"), "1,024");
assert_eq!(calc("sqrt(16)"), "4");
assert_eq!(calc("√16"), "4");
assert_eq!(calc("sin 30"), "0.5");
assert_eq!(calc("5!"), "120");
assert_eq!(calc("5 x 3"), "15");
assert_eq!(calc("2pi"), "6.2831853072");
assert_eq!(calc("(2)(3)"), "6");
assert_eq!(calc("3(4)"), "12");
assert_eq!(calc("1,000 + 1"), "ERR I couldn't read that expression");
}
#[test]
fn old_word_style() {
assert_eq!(calc("16 sqrt"), "4");
assert_eq!(calc("5 add 3"), "8");
assert_eq!(calc("100 log 10"), "2");
assert_eq!(calc("10 times 4"), "40");
}
#[test]
fn big_numbers_stay_exact() {
assert_eq!(calc("2^99"), "633,825,300,114,114,700,748,351,602,688");
assert!(calc("2^200").contains("digits"));
assert_eq!(calc("2^100"), "1.2676506002e+30 (31 digits)");
assert_eq!(calc("20!"), "2,432,902,008,176,640,000");
}
#[test]
fn errors_are_friendly() {
assert_eq!(calc("1/0"), "ERR can't divide by zero");
assert_eq!(calc("sqrt(-1)"), "ERR can't take the square root of a negative number");
assert_eq!(calc("log(0)"), "ERR log is only defined for positive numbers");
assert_eq!(calc("foo"), "ERR I don't know `foo`");
assert_eq!(calc("bar(1)"), "ERR I don't know the function `bar`");
assert_eq!(calc("9^99999"), "ERR that number is too big");
assert_eq!(calc("2 +"), "ERR I couldn't read that expression");
assert_eq!(calc("import os"), "ERR I couldn't read that expression");
assert_eq!(calc("tan(90)"), "ERR tan is undefined at that angle");
}
#[test]
fn functions() {
assert_eq!(calc("max(1, 5, 3)"), "5");
assert_eq!(calc("gcd(12, 18)"), "6");
assert_eq!(calc("lcm(4, 6)"), "12");
assert_eq!(calc("round(2.5)"), "2");
assert_eq!(calc("round(3.14159, 2)"), "3.14");
assert_eq!(calc("floor(2.7)"), "2");
assert_eq!(calc("abs(-3)"), "3");
}
#[test]
fn number_formats() {
assert_eq!(fmt_number(&Num::Float(1e20)), "1.0000000000e+20");
assert_eq!(fmt_number(&Num::Float(0.0000001)), "1.0000000000e-07");
assert_eq!(fmt_number(&Num::Float(-1234.5)), "-1,234.5");
assert_eq!(pretty("2 ** 3 * 4 / 5"), "2 ^ 3 × 4 ÷ 5");
}
}