From 546b094555768faf3c2d519dc63cee83a8bfeb91 Mon Sep 17 00:00:00 2001 From: fkDead Date: Wed, 11 Nov 2026 20:20:48 +0100 Subject: [PATCH] capri-tools: add calc module --- crates/capri-tools/src/calc.rs | 725 +++++++++++++++++++++++++++++++++ 1 file changed, 725 insertions(+) create mode 100644 crates/capri-tools/src/calc.rs diff --git a/crates/capri-tools/src/calc.rs b/crates/capri-tools/src/calc.rs new file mode 100644 index 0000000..f9291bb --- /dev/null +++ b/crates/capri-tools/src/calc.rs @@ -0,0 +1,725 @@ +//! Capri's precise calculator (`calculator.mjs`, `math-expression.mjs`, `math-worker.mjs`) in Rust: +//! scientific expressions, programmer integers, unit conversion and date arithmetic. +//! TODO: f64 (15 significant digits) instead of mathjs 64-digit BigNumber; switch to a decimal crate if more digits are needed. +use anyhow::{anyhow, bail, Result}; +use chrono::{Datelike, Months, NaiveDate}; +use serde_json::{json, Map, Value}; + +const FUNCTIONS: [&str; 52] = [ + "abs", "sqrt", "cbrt", "nthRoot", "square", "cube", "pow", "exp", "expm1", "log", "ln", "log10", "log2", "log1p", "sin", + "cos", "tan", "asin", "acos", "atan", "atan2", "sec", "csc", "cot", "asec", "acsc", "acot", "sinh", "cosh", "tanh", + "asinh", "acosh", "atanh", "sech", "csch", "coth", "asech", "acsch", "acoth", "factorial", "combinations", + "permutations", "mod", "gcd", "lcm", "floor", "ceil", "round", "fix", "sign", "hypot", "bitNot", +]; +const BIT_FUNCTIONS: [&str; 6] = ["bitAnd", "bitOr", "bitXor", "leftShift", "rightArithShift", "rightLogShift"]; + +#[derive(Debug, Clone, PartialEq)] +enum Tok { + Num(String), + Id(String), + Op(&'static str), +} + +#[derive(Debug)] +enum Node { + Num(String), + Const(String), + Unary(&'static str, Box), + Binary(&'static str, Box, Box), + Postfix(&'static str, Box), + Call(String, Vec), +} + +fn tokenize(expression: &str) -> Result> { + let s = expression.replace("**", "^").replace('×', "*").replace('÷', "/").replace('π', "pi").replace('²', "^2").replace('³', "^3"); + let chars: Vec = s.chars().collect(); + let (mut i, mut out) = (0, vec![]); + const OPS: [&str; 15] = [">>>", "<<", ">>", "+", "-", "*", "/", "^", "!", "%", "(", ")", ",", "&", "|"]; + while i < chars.len() { + let c = chars[i]; + if c.is_whitespace() { + i += 1; + } else if c.is_ascii_digit() || (c == '.' && chars.get(i + 1).is_some_and(char::is_ascii_digit)) { + let start = i; + while i < chars.len() && (chars[i].is_ascii_digit() || chars[i] == '.') { + i += 1; + } + if i < chars.len() && matches!(chars[i], 'e' | 'E') { + let mut j = i + 1; + if j < chars.len() && matches!(chars[j], '+' | '-') { + j += 1; + } + if j < chars.len() && chars[j].is_ascii_digit() { + i = j; + while i < chars.len() && chars[i].is_ascii_digit() { + i += 1; + } + } + } + out.push(Tok::Num(chars[start..i].iter().collect())); + } else if c.is_ascii_alphabetic() { + let start = i; + while i < chars.len() && chars[i].is_ascii_alphanumeric() { + i += 1; + } + out.push(Tok::Id(chars[start..i].iter().collect())); + } else if c == '~' { + out.push(Tok::Op("~")); + i += 1; + } else { + let rest: String = chars[i..chars.len().min(i + 3)].iter().collect(); + let op = OPS.iter().find(|op| rest.starts_with(**op)).ok_or_else(|| anyhow!("Unsupported numeric operator."))?; + out.push(Tok::Op(op)); + i += op.chars().count(); + } + if out.len() > 256 { + bail!("The expression is too complex."); + } + } + Ok(out) +} + +struct Parser { + toks: Vec, + pos: usize, + nodes: usize, +} + +impl Parser { + fn peek(&self) -> Option<&Tok> { + self.toks.get(self.pos) + } + fn is_op(&self, op: &str) -> bool { + matches!(self.peek(), Some(Tok::Op(o)) if *o == op) || matches!(self.peek(), Some(Tok::Id(id)) if id == op) + } + fn eat(&mut self, op: &str) -> bool { + let hit = self.is_op(op); + self.pos += hit as usize; + hit + } + fn node(&mut self, depth: usize, node: Node) -> Result> { + self.nodes += 1; + if self.nodes > 256 || depth > 48 { + bail!("The expression is too complex."); + } + Ok(Box::new(node)) + } + fn operand_starts(&self, at: usize) -> bool { + match self.toks.get(at) { + Some(Tok::Num(_)) | Some(Tok::Op("(")) => true, + Some(Tok::Id(id)) => id != "mod" && id != "xor", + _ => false, + } + } + /// Binary levels from lowest to highest precedence (mathjs order). + fn binary(&mut self, level: usize, depth: usize) -> Result> { + const LEVELS: [&[&str]; 6] = [&["|"], &["xor"], &["&"], &["<<", ">>>", ">>"], &["+", "-"], &["*", "/", "mod", "%"]]; + if level == LEVELS.len() { + return self.unary(depth); + } + let mut left = self.binary(level + 1, depth + 1)?; + loop { + let op = LEVELS[level].iter().find(|op| self.is_op(op)).copied(); + let op = match op { + // A `%` not followed by an operand is a percentage, handled in postfix. + Some("%") if !self.operand_starts(self.pos + 1) => break, + Some(op) => { + self.pos += 1; + op + } + None if level == 5 && self.operand_starts(self.pos) => "*", // implicit multiplication: 2pi, 2(3+4) + None => break, + }; + let right = self.binary(level + 1, depth + 1)?; + left = self.node(depth, Node::Binary(if op == "%" { "mod" } else { op }, left, right))?; + } + Ok(left) + } + fn unary(&mut self, depth: usize) -> Result> { + for op in ["-", "+", "~"] { + if self.eat(op) { + let inner = self.unary(depth + 1)?; + return self.node(depth, Node::Unary(op, inner)); + } + } + let base = self.postfix(depth + 1)?; + if self.eat("^") { + let exponent = self.unary(depth + 1)?; + return self.node(depth, Node::Binary("^", base, exponent)); + } + Ok(base) + } + fn postfix(&mut self, depth: usize) -> Result> { + let mut node = self.primary(depth + 1)?; + loop { + if self.eat("!") { + node = self.node(depth, Node::Postfix("!", node))?; + } else if self.is_op("%") && !self.operand_starts(self.pos + 1) { + self.pos += 1; + node = self.node(depth, Node::Postfix("%", node))?; + } else { + return Ok(node); + } + } + } + fn primary(&mut self, depth: usize) -> Result> { + let invalid = || anyhow!("Only numeric operations are allowed: no assignments, objects, strings, arrays or code."); + match self.toks.get(self.pos).cloned() { + Some(Tok::Num(n)) => { + self.pos += 1; + self.node(depth, Node::Num(n)) + } + Some(Tok::Op("(")) => { + self.pos += 1; + let inner = self.binary(0, depth + 1)?; + if !self.eat(")") { + return Err(invalid()); + } + Ok(inner) + } + Some(Tok::Id(name)) => { + self.pos += 1; + if ["pi", "e", "tau", "phi"].contains(&name.as_str()) { + return self.node(depth, Node::Const(name)); + } + if !(FUNCTIONS.contains(&name.as_str()) || BIT_FUNCTIONS.contains(&name.as_str())) || !self.eat("(") { + bail!("Unknown numeric constant."); + } + let mut args = vec![*self.binary(0, depth + 1)?]; + while self.eat(",") { + args.push(*self.binary(0, depth + 1)?); + } + if args.len() > 8 || !self.eat(")") { + return Err(invalid()); + } + self.node(depth, Node::Call(name, args)) + } + _ => Err(invalid()), + } + } +} + +fn parse(expression: &str) -> Result { + let mut p = Parser { toks: tokenize(expression)?, pos: 0, nodes: 0 }; + let node = p.binary(0, 0)?; + if p.pos != p.toks.len() { + bail!("Only numeric operations are allowed: no assignments, objects, strings, arrays or code."); + } + Ok(*node) +} + +fn finite(v: f64) -> Result { + if v.is_finite() { Ok(v) } else { Err(anyhow!("The result is undefined or outside the real-number range.")) } +} + +fn integers(args: &[f64]) -> Result<()> { + if args.iter().any(|v| v.fract() != 0.0 || *v < 0.0 || *v > 10000.0) { + bail!("Factorials and combinations require integers from 0 to 10000."); + } + Ok(()) +} + +fn factorial(n: f64) -> f64 { + (1..=n as u64).fold(1.0, |acc, k| acc * k as f64) +} + +fn gcd(a: f64, b: f64) -> f64 { + if b == 0.0 { a.abs() } else { gcd(b, a % b) } +} + +fn scientific(node: &Node, ratio: f64) -> Result { + let v = match node { + Node::Num(n) => n.parse::().map_err(|_| anyhow!("Only numeric constants are supported."))?, + Node::Const(c) => match c.as_str() { + "pi" => std::f64::consts::PI, + "e" => std::f64::consts::E, + "tau" => std::f64::consts::TAU, + _ => std::f64::consts::GOLDEN_RATIO, + }, + Node::Unary("-", a) => -scientific(a, ratio)?, + Node::Unary("+", a) => scientific(a, ratio)?, + Node::Postfix("%", a) => scientific(a, ratio)? / 100.0, + Node::Postfix(_, a) => { + let n = scientific(a, ratio)?; + integers(&[n])?; + factorial(n) + } + Node::Binary(op, a, b) => { + let (a, b) = (scientific(a, ratio)?, scientific(b, ratio)?); + match *op { + "+" => a + b, + "-" => a - b, + "*" => a * b, + "/" => a / b, + "^" => call("pow", &[a, b], ratio)?, + "mod" => call("mod", &[a, b], ratio)?, + _ => bail!("Unsupported numeric operator."), + } + } + Node::Call(name, args) => { + let values = args.iter().map(|a| scientific(a, ratio)).collect::>>()?; + call(name, &values, ratio)? + } + Node::Unary(..) => bail!("Unsupported numeric operator."), + }; + finite(v) +} + +fn call(name: &str, a: &[f64], ratio: f64) -> Result { + let arity = |min: usize, max: usize| { + if a.len() < min || a.len() > max { Err(anyhow!("Wrong number of arguments for {name}.")) } else { Ok(()) } + }; + let x = a.first().copied().unwrap_or(f64::NAN); + let angle = x * ratio; + let one = |f: fn(f64) -> f64, v: f64| arity(1, 1).map(|_| f(v)); + let inverse = |f: fn(f64) -> f64| arity(1, 1).map(|_| f(x) / ratio); + match name { + "abs" => one(f64::abs, x), + "sqrt" => one(f64::sqrt, x), + "cbrt" => one(f64::cbrt, x), + "nthRoot" => { + arity(1, 2)?; + let n = a.get(1).copied().unwrap_or(2.0); + Ok(if x < 0.0 && n.fract() == 0.0 && n as i64 % 2 != 0 { -(-x).powf(1.0 / n) } else { x.powf(1.0 / n) }) + } + "square" => one(|v| v * v, x), + "cube" => one(|v| v * v * v, x), + "pow" => { + arity(2, 2)?; + if a[1].abs() > 1_000_000.0 { + bail!("The exponent is too large."); + } + Ok(x.powf(a[1])) + } + "exp" => one(f64::exp, x), + "expm1" => one(f64::exp_m1, x), + "log" => { + arity(1, 2)?; + Ok(a.get(1).map_or(x.ln(), |base| x.ln() / base.ln())) + } + "ln" => one(f64::ln, x), + "log10" => one(f64::log10, x), + "log2" => one(f64::log2, x), + "log1p" => one(f64::ln_1p, x), + "sin" => one(f64::sin, angle), + "cos" => one(f64::cos, angle), + "tan" => one(f64::tan, angle), + "sec" => one(|v| 1.0 / v.cos(), angle), + "csc" => one(|v| 1.0 / v.sin(), angle), + "cot" => one(|v| 1.0 / v.tan(), angle), + "asin" => inverse(f64::asin), + "acos" => inverse(f64::acos), + "atan" => inverse(f64::atan), + "asec" => inverse(|v| (1.0 / v).acos()), + "acsc" => inverse(|v| (1.0 / v).asin()), + "acot" => inverse(|v| (1.0 / v).atan()), + "atan2" => arity(2, 2).map(|_| x.atan2(a[1]) / ratio), + "sinh" => one(f64::sinh, x), + "cosh" => one(f64::cosh, x), + "tanh" => one(f64::tanh, x), + "asinh" => one(f64::asinh, x), + "acosh" => one(f64::acosh, x), + "atanh" => one(f64::atanh, x), + "sech" => one(|v| 1.0 / v.cosh(), x), + "csch" => one(|v| 1.0 / v.sinh(), x), + "coth" => one(|v| 1.0 / v.tanh(), x), + "asech" => one(|v| (1.0 / v).acosh(), x), + "acsch" => one(|v| (1.0 / v).asinh(), x), + "acoth" => one(|v| (1.0 / v).atanh(), x), + "factorial" => { + arity(1, 1)?; + integers(a)?; + Ok(factorial(x)) + } + "combinations" | "permutations" => { + arity(if name == "combinations" { 2 } else { 1 }, 2)?; + integers(a)?; + let k = a.get(1).copied().unwrap_or(x); + if k > x { + bail!("k must be less than or equal to n."); + } + let perm = (0..k as u64).fold(1.0, |acc, i| acc * (x - i as f64)); + Ok(if name == "combinations" { perm / factorial(k) } else { perm }) + } + "mod" => arity(2, 2).map(|_| if a[1] == 0.0 { x } else { x - a[1] * (x / a[1]).floor() }), + "gcd" | "lcm" => { + arity(1, 8)?; + if a.iter().any(|v| v.fract() != 0.0) { + bail!("gcd and lcm require integers."); + } + Ok(a[1..].iter().fold(x.abs(), |acc, v| if name == "gcd" { gcd(acc, *v) } else if acc == 0.0 || *v == 0.0 { 0.0 } else { (acc * v / gcd(acc, *v)).abs() })) + } + "floor" => one(f64::floor, x), + "ceil" => one(f64::ceil, x), + "round" => { + arity(1, 2)?; + let p = 10f64.powi(a.get(1).copied().unwrap_or(0.0) as i32); + Ok((x * p).round() / p) + } + "fix" => one(f64::trunc, x), + "sign" => one(|v| if v == 0.0 { 0.0 } else { v.signum() }, x), + "hypot" => arity(1, 8).map(|_| a.iter().map(|v| v * v).sum::().sqrt()), + _ => bail!("Use programmer mode for bitwise operations."), + } +} + +fn programmer(node: &Node, bits: u32) -> Result { + let mask: i128 = if bits == 64 { u64::MAX as i128 } else { (1i128 << bits) - 1 }; + let (op, args): (&str, Vec<&Node>) = match node { + Node::Num(n) => { + let v: f64 = n.parse().map_err(|_| anyhow!("Use integers within 64 bits."))?; + if v.fract() != 0.0 || v.abs() > u64::MAX as f64 { + bail!("Use integers within 64 bits."); + } + return Ok(n.parse::().unwrap_or(v as i128)); + } + Node::Unary(op, a) => (op, vec![a]), + Node::Binary(op, a, b) => (op, vec![a, b]), + Node::Call(name, args) if args.len() <= 2 => ( + match name.as_str() { + "bitAnd" => "&", + "bitOr" => "|", + "bitXor" => "xor", + "bitNot" => "~", + "leftShift" => "<<", + "rightArithShift" => ">>", + "rightLogShift" => ">>>", + _ => bail!("Use programmer arithmetic, bitwise operators or shifts."), + }, + args.iter().collect(), + ), + _ => bail!("Use programmer arithmetic, bitwise operators or shifts."), + }; + let a = programmer(args[0], bits)?; + let b = args.get(1).map(|n| programmer(n, bits)).transpose()?.unwrap_or(0); + if ["<<", ">>", ">>>"].contains(&op) && (b < 0 || b >= bits as i128) { + bail!("Shift must fit the selected word size."); + } + let signed = |v: i128| { + let v = v & mask; + if v >> (bits - 1) & 1 == 1 { v - mask - 1 } else { v } + }; + let value = match (op, args.len()) { + ("-", 1) => -a, + ("+", _) => a + b, + ("-", _) => a - b, + ("*", _) => a.checked_mul(b).ok_or_else(|| anyhow!("Use integers within 64 bits."))?, + ("/" | "mod", _) if b == 0 => bail!("Division by zero."), + ("/", _) => a / b, + ("mod", _) => a % b, + ("&", _) => a & b, + ("|", _) => a | b, + ("xor", _) => a ^ b, + ("~", _) => !a, + ("<<", _) => (a & mask) << b, + (">>", _) => signed(a) >> b, + (">>>", _) => (a & mask) >> b, + _ => bail!("Unsupported programmer operation."), + }; + Ok(value & mask) +} + +/// Rounds to `digits` significant digits and prints like JavaScript numbers (no exponent for 1e-7..1e21). +pub fn format_number(v: f64, digits: usize) -> String { + let r: f64 = format!("{:.*e}", digits - 1, v).parse().unwrap_or(v); + if r == 0.0 { + return "0".into(); + } + if (1e-7..1e21).contains(&r.abs()) { format!("{r}") } else { format!("{r:e}") } +} + +fn numeric(v: f64) -> Value { + let text = format_number(v, 15); + json!({"result": text, "displayResult": text, "precisionDigits": 15}) +} + +/// (names, dimension, factor to base unit, offset added before scaling). +const UNITS: &[(&str, &str, f64, f64)] = &[ + ("m,meter,meters,metre,metres", "L", 1.0, 0.0), + ("km,kilometer,kilometers,kilometre", "L", 1e3, 0.0), + ("cm,centimeter,centimeters", "L", 1e-2, 0.0), + ("mm,millimeter,millimeters", "L", 1e-3, 0.0), + ("um,µm,μm,micrometer", "L", 1e-6, 0.0), + ("nm,nanometer", "L", 1e-9, 0.0), + ("in,inch,inches", "L", 0.0254, 0.0), + ("ft,foot,feet", "L", 0.3048, 0.0), + ("yd,yard,yards", "L", 0.9144, 0.0), + ("mi,mile,miles", "L", 1609.344, 0.0), + ("nmi,nauticalmile", "L", 1852.0, 0.0), + ("kg,kilogram,kilograms", "M", 1.0, 0.0), + ("g,gram,grams", "M", 1e-3, 0.0), + ("mg,milligram,milligrams", "M", 1e-6, 0.0), + ("t,tonne,tonnes", "M", 1e3, 0.0), + ("lb,lbs,lbm,pound,pounds", "M", 0.453_592_37, 0.0), + ("oz,ounce,ounces", "M", 0.028_349_523_125, 0.0), + ("st,stone", "M", 6.350_293_18, 0.0), + ("s,sec,second,seconds", "T", 1.0, 0.0), + ("ms,millisecond,milliseconds", "T", 1e-3, 0.0), + ("min,minute,minutes", "T", 60.0, 0.0), + ("h,hr,hour,hours", "T", 3600.0, 0.0), + ("day,days", "T", 86400.0, 0.0), + ("week,weeks", "T", 604_800.0, 0.0), + ("l,L,liter,liters,litre,litres", "V", 1e-3, 0.0), + ("ml,mL,milliliter,milliliters", "V", 1e-6, 0.0), + ("cl,cL", "V", 1e-5, 0.0), + ("dl,dL", "V", 1e-4, 0.0), + ("m3,m^3", "V", 1.0, 0.0), + ("cm3,cm^3,cc", "V", 1e-6, 0.0), + ("gal,gallon,gallons", "V", 0.003_785_411_784, 0.0), + ("qt,quart", "V", 0.000_946_352_946, 0.0), + ("pt,pint", "V", 0.000_473_176_473, 0.0), + ("cup,cups", "V", 0.000_236_588_236_5, 0.0), + ("floz,fluidounce", "V", 2.957_352_956_25e-5, 0.0), + ("tbsp,tablespoon", "V", 1.478_676_478_125e-5, 0.0), + ("tsp,teaspoon", "V", 4.928_921_593_75e-6, 0.0), + ("m2,m^2", "A", 1.0, 0.0), + ("km2,km^2", "A", 1e6, 0.0), + ("cm2,cm^2", "A", 1e-4, 0.0), + ("ha,hectare,hectares", "A", 1e4, 0.0), + ("acre,acres", "A", 4_046.856_422_4, 0.0), + ("ft2,ft^2,sqft", "A", 0.092_903_04, 0.0), + ("mi2,mi^2", "A", 2_589_988.110_336, 0.0), + ("m/s", "S", 1.0, 0.0), + ("km/h,kph,kmh", "S", 1.0 / 3.6, 0.0), + ("mph,mi/h", "S", 0.447_04, 0.0), + ("knot,knots,kn", "S", 1852.0 / 3600.0, 0.0), + ("ft/s", "S", 0.3048, 0.0), + ("K,kelvin", "Θ", 1.0, 0.0), + ("degC,°C,C,celsius", "Θ", 1.0, 273.15), + ("degF,°F,F,fahrenheit", "Θ", 5.0 / 9.0, 459.67), + ("b,bit,bits", "D", 1.0, 0.0), + ("B,byte,bytes", "D", 8.0, 0.0), + ("kB,KB", "D", 8e3, 0.0), + ("MB", "D", 8e6, 0.0), + ("GB", "D", 8e9, 0.0), + ("TB", "D", 8e12, 0.0), + ("KiB", "D", 8.0 * 1024.0, 0.0), + ("MiB", "D", 8.0 * 1_048_576.0, 0.0), + ("GiB", "D", 8.0 * 1_073_741_824.0, 0.0), + ("TiB", "D", 8.0 * 1_099_511_627_776.0, 0.0), + ("J,joule,joules", "E", 1.0, 0.0), + ("kJ", "E", 1e3, 0.0), + ("cal,calorie", "E", 4.184, 0.0), + ("kcal,Cal", "E", 4184.0, 0.0), + ("Wh", "E", 3600.0, 0.0), + ("kWh", "E", 3.6e6, 0.0), + ("Pa,pascal", "P", 1.0, 0.0), + ("kPa", "P", 1e3, 0.0), + ("bar", "P", 1e5, 0.0), + ("atm", "P", 101_325.0, 0.0), + ("psi", "P", 6_894.757_293_168, 0.0), + ("deg,degree,degrees", "R", std::f64::consts::PI / 180.0, 0.0), + ("rad,radian,radians", "R", 1.0, 0.0), + ("grad,gradian", "R", std::f64::consts::PI / 200.0, 0.0), +]; + +fn unit(name: &str) -> Option<(&'static str, f64, f64)> { + let name = name.trim(); + UNITS.iter().find(|(names, ..)| names.split(',').any(|n| n == name)).map(|(_, d, f, o)| (*d, *f, *o)) +} + +fn convert(value: &str, from: &str, to: &str) -> Result { + let error = || anyhow!("Use a numeric value and recognized physical units. Live currency rates are not guessed."); + let number = regex::Regex::new(r"(?i)^[+-]?(?:\d+(?:\.\d*)?|\.\d+)(?:e[+-]?\d{1,6})?$").unwrap(); + if !number.is_match(value) { + return Err(error()); + } + let ((d1, f1, o1), (d2, f2, o2)) = (unit(from).ok_or_else(error)?, unit(to).ok_or_else(error)?); + if d1 != d2 { + return Err(error()); + } + let base = (value.parse::()? + o1) * f1; + let mut result = numeric(finite(base / f2 - o2)?); + result["unit"] = to.into(); + Ok(result) +} + +fn date(c: &Map) -> Result { + let parse = |k: &str| NaiveDate::parse_from_str(c[k].as_str().unwrap_or(""), "%Y-%m-%d").map_err(|_| anyhow!("Use ISO dates and either an end date or a bounded date offset.")); + let from = parse("fromDate")?; + if c.contains_key("toDate") { + let to = parse("toDate")?; + let days = (to - from).num_days(); + let (early, late, sign) = if to >= from { (from, to, 1) } else { (to, from, -1) }; + let mut months = (late.year() - early.year()) * 12 + late.month() as i32 - early.month() as i32; + if early.checked_add_months(Months::new(months.max(0) as u32)).is_none_or(|d| d > late) { + months -= 1; + } + let rest = (late - early.checked_add_months(Months::new(months.max(0) as u32)).unwrap_or(early)).num_days(); + return Ok(json!({"result": days.to_string(), "days": days, "years": sign * (months / 12), "months": sign * (months % 12), "remainingDays": sign as i64 * rest})); + } + let amount = c["amount"].as_i64().unwrap_or(0); + let result = match c["dateUnit"].as_str() { + Some("days") => from.checked_add_signed(chrono::Duration::days(amount)), + unit => { + let months = amount * if unit == Some("years") { 12 } else { 1 }; + let m = Months::new(months.unsigned_abs() as u32); + if months >= 0 { from.checked_add_months(m) } else { from.checked_sub_months(m) } + } + } + .ok_or_else(|| anyhow!("The date is outside the supported range."))?; + Ok(json!({"result": result.format("%Y-%m-%d").to_string()})) +} + +/// Validates like `validateCalculation`; `app` defaults to `calculator`. +pub fn validate(args: &Value) -> Result> { + let mut c = args.as_object().cloned().unwrap_or_default(); + c.entry("app").or_insert("calculator".into()); + let mode = c.get("mode").and_then(Value::as_str).unwrap_or("scientific").to_string(); + let extra: &[&str] = match mode.as_str() { + "scientific" => &["expression", "angleUnit"], + "programmer" => &["expression", "bits"], + "convert" => &["value", "fromUnit", "toUnit"], + "date" => &["fromDate", "toDate", "amount", "dateUnit"], + _ => bail!("Unknown calculator mode."), + }; + if c.keys().any(|k| !["action", "app", "mode", "showWindow"].contains(&k.as_str()) && !extra.contains(&k.as_str())) + || c["app"] != "calculator" + || c.get("showWindow").is_some_and(|v| !v.is_boolean()) + { + bail!("Invalid calculator arguments for this mode."); + } + let s = |k: &str| c.get(k).and_then(Value::as_str); + if matches!(mode.as_str(), "scientific" | "programmer") { + let allowed = regex::Regex::new(r"^[\p{L}\p{N} +*/^%!().,\-×÷π²³&|~<>]+$").unwrap(); + if !s("expression").is_some_and(|e| !e.trim().is_empty() && capri_core::utf16_len(e) <= 1200 && allowed.is_match(e)) { + bail!("Use a numeric expression of at most 1200 characters."); + } + } + if c.get("angleUnit").is_some_and(|u| !["deg", "rad", "grad"].contains(&u.as_str().unwrap_or(""))) { + bail!("Choose degrees, radians or gradians."); + } + if c.get("bits").is_some_and(|b| ![8, 16, 32, 64].contains(&b.as_i64().unwrap_or(0))) { + bail!("Choose an 8, 16, 32 or 64 bit word."); + } + if mode == "convert" && ["value", "fromUnit", "toUnit"].iter().any(|k| !s(k).is_some_and(|v| !v.trim().is_empty() && v.chars().count() <= if *k == "value" { 120 } else { 64 })) { + bail!("Supply a value and both units."); + } + if mode == "date" { + let iso = |k: &str| s(k).is_some_and(|d| regex::Regex::new(r"^\d{4}-\d{2}-\d{2}$").unwrap().is_match(d)); + let offset = c.get("amount").and_then(Value::as_i64).is_some_and(|a| a.abs() <= 1_000_000) + && ["days", "months", "years"].contains(&s("dateUnit").unwrap_or("")); + let ok = iso("fromDate") + && if c.contains_key("toDate") { iso("toDate") && !c.contains_key("amount") && !c.contains_key("dateUnit") } else { offset }; + if !ok { + bail!("Use ISO dates and either an end date or a bounded date offset."); + } + } + c.insert("mode".into(), mode.into()); + Ok(c) +} + +/// Evaluates a validated command; returns Capri's result object. +pub fn calculate(c: &Map) -> Result { + let s = |k: &str| c.get(k).and_then(Value::as_str).unwrap_or(""); + let mut result = match s("mode") { + "programmer" => { + let bits = c.get("bits").and_then(Value::as_u64).unwrap_or(64) as u32; + let v = programmer(&parse(s("expression"))?, bits)? as u64; + let signed = if bits == 64 { v as i64 } else { ((v << (64 - bits)) as i64) >> (64 - bits) }; + json!({"result": v.to_string(), "signed": signed.to_string(), "hex": format!("{v:X}"), + "binary": format!("{v:0width$b}", width = bits as usize), "octal": format!("{v:o}"), "bits": bits}) + } + "convert" => convert(s("value"), s("fromUnit"), s("toUnit"))?, + "date" => date(c)?, + _ => { + let ratio = match c.get("angleUnit").and_then(Value::as_str) { + Some("rad") => 1.0, + Some("grad") => std::f64::consts::PI / 200.0, + _ => std::f64::consts::PI / 180.0, + }; + numeric(scientific(&parse(s("expression"))?, ratio)?) + } + }; + result["ok"] = true.into(); + result["app"] = "calculator".into(); + result["engine"] = "capri-precise-calculator".into(); + Ok(result) +} + +#[cfg(test)] +mod tests { + use super::*; + + fn eval(expression: &str) -> String { + let c = validate(&json!({"action": "calculate", "expression": expression})).unwrap(); + match calculate(&c) { + Ok(v) => v["result"].as_str().unwrap().to_string(), + Err(e) => format!("error: {e}"), + } + } + + #[test] + fn scientific_grammar() { + for (expr, want) in [ + ("square(12)", "144"), + ("sqrt(1036)", "32.1869538788622"), + ("nthRoot(125,3)", "5"), + ("nthRoot(-8,3)", "-2"), + ("log(8,2)", "3"), + ("ln(e)", "1"), + ("sin(30)", "0.5"), + ("2^10", "1024"), + ("2**3", "8"), + ("-2^2", "-4"), + ("2^-1", "0.5"), + ("(2+3)*4", "20"), + ("factorial(5)", "120"), + ("5!", "120"), + ("0.1+0.2", "0.3"), + ("2pi", "6.28318530717959"), + ("2(3+4)", "14"), + ("7 mod 3", "1"), + ("7 % 3", "1"), + ("50%", "0.5"), + ("10 × 3 ÷ 2", "15"), + ("3²", "9"), + ("combinations(5,2)", "10"), + ("atan(1)", "45"), + ("1/0", "error: The result is undefined or outside the real-number range."), + ("sqrt(-1)", "error: The result is undefined or outside the real-number range."), + ("x+1", "error: Unknown numeric constant."), + ("factorial(2.5)", "error: Factorials and combinations require integers from 0 to 10000."), + ] { + assert_eq!(eval(expr), want, "{expr}"); + } + assert!(validate(&json!({"action":"calculate","expression":"a=1"})).is_err()); + assert!(validate(&json!({"action":"calculate","app":"notepad","expression":"1"})).is_err()); + let c = validate(&json!({"expression":"sin(pi/2)","angleUnit":"rad"})).unwrap(); + assert_eq!(calculate(&c).unwrap()["result"], "1"); + } + + #[test] + fn deep_or_long_expressions_are_refused() { + assert!(eval(&"(".repeat(60)).starts_with("error")); + assert!(eval("1+".repeat(200).trim_end_matches('+')).starts_with("error")); + } + + #[test] + fn programmer_mode() { + let c = validate(&json!({"mode":"programmer","expression":"0xF","bits":8})); + assert!(c.is_ok()); + let c = validate(&json!({"mode":"programmer","expression":"~0","bits":8})).unwrap(); + let r = calculate(&c).unwrap(); + assert_eq!((r["result"].as_str(), r["signed"].as_str(), r["hex"].as_str()), (Some("255"), Some("-1"), Some("FF"))); + let c = validate(&json!({"mode":"programmer","expression":"12 & 10 | 1 << 4"})).unwrap(); + assert_eq!(calculate(&c).unwrap()["result"], "24"); + let c = validate(&json!({"mode":"programmer","expression":"bitXor(6, 3)","bits":16})).unwrap(); + assert_eq!(calculate(&c).unwrap()["binary"], "0000000000000101"); + let c = validate(&json!({"mode":"programmer","expression":"1 << 9","bits":8})).unwrap(); + assert!(calculate(&c).is_err()); + } + + #[test] + fn conversions_and_dates() { + let conv = |v: &str, f: &str, t: &str| calculate(&validate(&json!({"mode":"convert","value":v,"fromUnit":f,"toUnit":t})).unwrap()); + assert_eq!(conv("100", "degC", "degF").unwrap()["result"], "212"); + assert_eq!(conv("1", "mi", "km").unwrap()["result"], "1.609344"); + assert_eq!(conv("1", "km", "kg").unwrap_err().to_string(), "Use a numeric value and recognized physical units. Live currency rates are not guessed."); + let date = |args: Value| calculate(&validate(&args).unwrap()).unwrap(); + assert_eq!(date(json!({"mode":"date","fromDate":"2024-01-31","amount":1,"dateUnit":"months"}))["result"], "2024-02-29"); + let r = date(json!({"mode":"date","fromDate":"2024-01-15","toDate":"2025-03-20"})); + assert_eq!((r["days"].as_i64(), r["years"].as_i64(), r["months"].as_i64(), r["remainingDays"].as_i64()), (Some(430), Some(1), Some(2), Some(5))); + assert!(validate(&json!({"mode":"date","fromDate":"2024-01-15","toDate":"2025-03-20","amount":1})).is_err()); + } +}