use std::sync::atomic::{AtomicBool, Ordering};
use std::time::{Duration, Instant};
use crate::core::{
AstCanonicalizer, AstNode, CacheManager, CalcError, CanonicalForm, DomainRouter, EvalContext,
EvalResult, MAX_PRECISION, parse,
};
use crate::domains::{build_default_router, build_precision_domain};
pub fn evaluate(
expr: &str,
ctx: &EvalContext,
precision: Option<usize>,
cache: &CacheManager,
) -> Result<(EvalResult, String, bool, Option<usize>), CalcError> {
evaluate_with_router(expr, ctx, precision, cache, build_default_router())
}
pub fn evaluate_with_router(
expr: &str,
ctx: &EvalContext,
precision: Option<usize>,
cache: &CacheManager,
router: &DomainRouter,
) -> Result<(EvalResult, String, bool, Option<usize>), CalcError> {
let start = Instant::now();
validate_inputs(ctx, precision)?;
let ast = parse(expr)?;
check_elapsed(start, ctx.timeout)?;
let (canonical_ast, cf) = AstCanonicalizer::canonicalize(&ast)?;
check_elapsed(start, ctx.timeout)?;
let cache_cf = build_cache_key(&cf, ctx, precision);
if precision.is_some() {
eval_precision_mode(&canonical_ast, ctx, cache, &cache_cf, precision, start)
} else {
eval_regular_mode(&canonical_ast, ctx, cache, &cache_cf, start, router)
}
}
fn validate_inputs(ctx: &EvalContext, precision: Option<usize>) -> Result<(), CalcError> {
if ctx.timeout.is_zero() {
return Err(CalcError::timeout());
}
if let Some(p) = precision
&& p > MAX_PRECISION
{
return Err(
CalcError::domain(format!("precision {} exceeds limit {}", p, MAX_PRECISION))
.with_i18n(
"msg.core.precision_exceeds_limit",
vec![
("precision".to_string(), p.to_string()),
("max".to_string(), MAX_PRECISION.to_string()),
],
),
);
}
Ok(())
}
fn build_cache_key(
cf: &CanonicalForm,
ctx: &EvalContext,
precision: Option<usize>,
) -> CanonicalForm {
let base = if precision.is_some() {
format!("precision:{}", cf.as_str())
} else {
cf.as_str().to_string()
};
let mut vars_input: Vec<u8> = Vec::new();
let mut sorted_vars: Vec<_> = ctx.vars.iter().collect();
sorted_vars.sort_by_key(|(k, _)| *k);
for (k, v) in sorted_vars {
vars_input.extend_from_slice(k.as_bytes());
vars_input.push(0); vars_input.extend_from_slice(&v.to_bits().to_le_bytes());
vars_input.push(0); }
let vars_hash_hex = blake3::hash(&vars_input).to_hex();
let timeout_nanos = ctx.timeout.as_nanos();
CanonicalForm::new(format!(
"{}|vars={}|timeout={}",
base, vars_hash_hex, timeout_nanos
))
}
fn eval_precision_mode(
canonical_ast: &AstNode,
ctx: &EvalContext,
cache: &CacheManager,
cache_cf: &CanonicalForm,
precision: Option<usize>,
start: Instant,
) -> Result<(EvalResult, String, bool, Option<usize>), CalcError> {
let computed = AtomicBool::new(false);
let result = cache.get_or_compute(cache_cf, || {
computed.store(true, Ordering::Relaxed);
let domain = build_precision_domain();
check_elapsed(start, ctx.timeout)?;
let r = domain.evaluate(canonical_ast, ctx)?;
check_elapsed(start, ctx.timeout)?;
Ok(r)
})?;
Ok((
result,
"precision".to_string(),
!computed.load(Ordering::Relaxed),
precision,
))
}
fn eval_regular_mode(
canonical_ast: &AstNode,
ctx: &EvalContext,
cache: &CacheManager,
cache_cf: &CanonicalForm,
start: Instant,
router: &DomainRouter,
) -> Result<(EvalResult, String, bool, Option<usize>), CalcError> {
if router.is_nondeterministic(canonical_ast) {
let domain = router.route(canonical_ast)?;
check_elapsed(start, ctx.timeout)?;
let result = domain.evaluate(canonical_ast, ctx)?;
check_elapsed(start, ctx.timeout)?;
let fmt_prec = extract_format_precision(canonical_ast);
return Ok((result, domain.domain_name().to_string(), false, fmt_prec));
}
let computed = AtomicBool::new(false);
let result = cache.get_or_compute(cache_cf, || {
computed.store(true, Ordering::Relaxed);
let domain = router.route(canonical_ast)?;
check_elapsed(start, ctx.timeout)?;
let r = domain.evaluate(canonical_ast, ctx)?;
check_elapsed(start, ctx.timeout)?;
Ok(r)
})?;
let domain = router.route(canonical_ast)?;
let fmt_prec = extract_format_precision(canonical_ast);
let cache_hit = !computed.load(Ordering::Relaxed);
Ok((
result,
domain.domain_name().to_string(),
cache_hit,
fmt_prec,
))
}
fn check_elapsed(start: Instant, timeout: Duration) -> Result<(), CalcError> {
if start.elapsed() > timeout {
return Err(CalcError::timeout());
}
Ok(())
}
fn extract_format_precision(ast: &AstNode) -> Option<usize> {
if let AstNode::FunctionCall(name, args) = ast
&& name == "precision"
&& args.len() == 2
&& let AstNode::Number(n) = &args[0]
&& n.fract() == 0.0
&& *n > 0.0
{
let n_usize = *n as usize;
if n_usize <= MAX_PRECISION {
return Some(n_usize);
}
}
None
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::{BinaryOp, ErrorKind, EvalContext};
#[test]
fn test_evaluate_with_router_injection() {
let router = DomainRouter::new();
let cache = CacheManager::new();
let ctx = EvalContext::new();
let r = evaluate_with_router("1+1", &ctx, None, &cache, &router);
assert!(r.is_err(), "空路由器应无法路由 1+1");
}
#[test]
fn test_extract_format_precision_float_n() {
let ast = AstNode::FunctionCall(
"precision".to_string(),
vec![
AstNode::Number(2.5),
AstNode::BinaryOp(
BinaryOp::Div,
Box::new(AstNode::Number(1.0)),
Box::new(AstNode::Number(3.0)),
),
],
);
assert_eq!(extract_format_precision(&ast), None);
}
#[test]
fn test_extract_format_precision_non_number_n() {
let ast = AstNode::FunctionCall(
"precision".to_string(),
vec![AstNode::Variable("x".to_string()), AstNode::Number(1.0)],
);
assert_eq!(extract_format_precision(&ast), None);
}
#[test]
fn test_extract_format_precision_bignumber_n() {
let ast = AstNode::FunctionCall(
"precision".to_string(),
vec![AstNode::BigNumber("5".to_string()), AstNode::Number(1.0)],
);
assert_eq!(extract_format_precision(&ast), None);
}
#[test]
fn test_extract_format_precision_valid() {
let ast = AstNode::FunctionCall(
"precision".to_string(),
vec![AstNode::Number(5.0), AstNode::Number(1.0)],
);
assert_eq!(extract_format_precision(&ast), Some(5));
}
#[test]
fn test_extract_format_precision_non_precision_call() {
let ast = AstNode::FunctionCall("sin".to_string(), vec![AstNode::Number(1.0)]);
assert_eq!(extract_format_precision(&ast), None);
}
#[test]
fn test_extract_format_precision_non_function() {
let ast = AstNode::Number(42.0);
assert_eq!(extract_format_precision(&ast), None);
}
#[test]
fn test_evaluate_precision_mode_cache_hit() {
let cache = CacheManager::new();
let ctx = EvalContext::new();
let (result1, domain1, cache_hit1, fmt_prec1) =
evaluate("2+3", &ctx, Some(5), &cache).unwrap();
assert_eq!(result1, EvalResult::BigInt(num_bigint::BigInt::from(5)));
assert_eq!(domain1, "precision");
assert!(!cache_hit1);
assert_eq!(fmt_prec1, Some(5));
let (result2, domain2, cache_hit2, fmt_prec2) =
evaluate("2+3", &ctx, Some(5), &cache).unwrap();
assert_eq!(result2, result1);
assert_eq!(domain2, "precision");
assert!(cache_hit2);
assert_eq!(fmt_prec2, Some(5));
}
#[test]
fn test_evaluate_precision_mode_does_not_pollute_regular_cache() {
let cache = CacheManager::new();
let ast = parse("2+3").unwrap();
let (_, cf) = AstCanonicalizer::canonicalize(&ast).unwrap();
cache.insert(&cf, &Ok(EvalResult::Scalar(5.0)));
let ctx = EvalContext::new();
let (result, domain, cache_hit, fmt_prec) = evaluate("2+3", &ctx, Some(5), &cache).unwrap();
assert_ne!(result, EvalResult::Scalar(5.0));
assert_eq!(result, EvalResult::BigInt(num_bigint::BigInt::from(5)));
assert_eq!(domain, "precision");
assert!(!cache_hit);
assert_eq!(fmt_prec, Some(5));
}
#[test]
fn test_evaluate_precision_bypass_dos_rejected() {
let cache = CacheManager::new();
let ctx = EvalContext::new();
let huge_n = MAX_PRECISION + 1;
let expr = format!("precision({}, 1/3)", huge_n);
let result = evaluate(&expr, &ctx, None, &cache);
assert!(
result.is_err(),
"precision N > MAX_PRECISION must be rejected"
);
}
#[test]
fn test_evaluate_precision_param_exceeds_limit_rejected() {
let cache = CacheManager::new();
let ctx = EvalContext::new();
let result = evaluate("1/3", &ctx, Some(MAX_PRECISION + 1), &cache);
assert!(
result.is_err(),
"precision param > MAX_PRECISION must be rejected"
);
}
#[test]
fn test_evaluate_regular_mode_cache_hit() {
let cache = CacheManager::new();
let ast = parse("2+3").unwrap();
let (_, cf) = AstCanonicalizer::canonicalize(&ast).unwrap();
let ctx = EvalContext::new();
let cache_cf = build_cache_key(&cf, &ctx, None);
cache.insert(&cache_cf, &Ok(EvalResult::Scalar(5.0)));
let (result, domain, cache_hit, fmt_prec) = evaluate("2+3", &ctx, None, &cache).unwrap();
assert_eq!(result, EvalResult::Scalar(5.0));
assert_eq!(domain, "arithmetic");
assert!(cache_hit);
assert_eq!(fmt_prec, None);
}
#[test]
fn test_v08_cli_number_theory_gcd() {
let cache = CacheManager::new();
let ctx = EvalContext::new();
let (result, domain, cache_hit, _) = evaluate("gcd(12,18)", &ctx, None, &cache).unwrap();
assert_eq!(result, EvalResult::Scalar(6.0));
assert_eq!(domain, "number_theory");
assert!(!cache_hit);
}
#[test]
fn test_v08_cli_combinatorics_C() {
let cache = CacheManager::new();
let ctx = EvalContext::new();
let (result, domain, cache_hit, _) = evaluate("C(10,3)", &ctx, None, &cache).unwrap();
assert_eq!(result, EvalResult::Scalar(120.0));
assert_eq!(domain, "combinatorics");
assert!(!cache_hit);
}
#[test]
fn test_v08_cli_vector_dot() {
let cache = CacheManager::new();
let ctx = EvalContext::new();
let (result, domain, _, _) = evaluate("dot([1,2,3],[4,5,6])", &ctx, None, &cache).unwrap();
assert_eq!(result, EvalResult::Scalar(32.0));
let _ = domain;
}
#[test]
fn test_v08_cli_polynomial_add() {
let cache = CacheManager::new();
let ctx = EvalContext::new();
let (result, domain, _, _) = evaluate("poly_add(x+1,x+2)", &ctx, None, &cache).unwrap();
assert!(matches!(result, EvalResult::Polynomial(_)));
assert_eq!(domain, "polynomial");
}
#[test]
fn test_v08_cli_cache_hit_number_theory() {
let cache = CacheManager::new();
let ast = parse("gcd(12,18)").unwrap();
let (_, cf) = AstCanonicalizer::canonicalize(&ast).unwrap();
let ctx = EvalContext::new();
let cache_cf = build_cache_key(&cf, &ctx, None);
cache.insert(&cache_cf, &Ok(EvalResult::Scalar(6.0)));
let (result, domain, cache_hit, _) = evaluate("gcd(12,18)", &ctx, None, &cache).unwrap();
assert_eq!(result, EvalResult::Scalar(6.0));
assert_eq!(domain, "number_theory");
assert!(cache_hit);
}
#[test]
fn test_v08_cli_cache_hit_combinatorics() {
let cache = CacheManager::new();
let ast = parse("C(10,3)").unwrap();
let (_, cf) = AstCanonicalizer::canonicalize(&ast).unwrap();
let ctx = EvalContext::new();
let cache_cf = build_cache_key(&cf, &ctx, None);
cache.insert(&cache_cf, &Ok(EvalResult::Scalar(120.0)));
let (result, domain, cache_hit, _) = evaluate("C(10,3)", &ctx, None, &cache).unwrap();
assert_eq!(result, EvalResult::Scalar(120.0));
assert_eq!(domain, "combinatorics");
assert!(cache_hit);
}
#[test]
fn test_evaluate_timeout_zero_immediate() {
let cache = CacheManager::new();
let mut ctx = EvalContext::new();
ctx.timeout = Duration::ZERO;
let result = evaluate("1+1", &ctx, None, &cache);
assert!(
matches!(result, Err(ref e) if e.kind == ErrorKind::Timeout),
"timeout=0 should trigger immediate timeout, got {:?}",
result
);
}
#[test]
fn test_evaluate_timeout_elapsed_triggers() {
let cache = CacheManager::new();
let mut ctx = EvalContext::new();
ctx.timeout = Duration::from_nanos(1);
std::thread::sleep(Duration::from_millis(1));
let result = evaluate("1+1", &ctx, None, &cache);
assert!(
matches!(result, Err(ref e) if e.kind == ErrorKind::Timeout),
"should timeout (elapsed > 1ns), got {:?}",
result
);
}
#[test]
fn test_evaluate_timeout_normal_succeeds() {
let cache = CacheManager::new();
let ctx = EvalContext::new(); let result = evaluate("1+1", &ctx, None, &cache);
assert!(
result.is_ok(),
"normal eval should succeed, got {:?}",
result
);
}
#[test]
fn test_evaluate_timeout_elapsed_precision_mode() {
let cache = CacheManager::new();
let mut ctx = EvalContext::new();
ctx.timeout = Duration::from_nanos(1);
std::thread::sleep(Duration::from_millis(1));
let result = evaluate("1+1", &ctx, Some(5), &cache);
assert!(
matches!(result, Err(ref e) if e.kind == ErrorKind::Timeout),
"precision mode should also timeout, got {:?}",
result
);
}
#[test]
fn test_check_elapsed_ok_when_not_expired() {
let start = Instant::now();
let timeout = Duration::from_secs(60);
assert!(check_elapsed(start, timeout).is_ok());
}
#[test]
fn test_check_elapsed_err_when_expired() {
let start = Instant::now();
let timeout = Duration::from_nanos(1);
std::thread::sleep(Duration::from_millis(1));
let result = check_elapsed(start, timeout);
assert!(
matches!(result, Err(ref e) if e.kind == ErrorKind::Timeout),
"expired should return Timeout error, got {:?}",
result
);
}
#[test]
fn test_evaluate_three_phases() {
{
let cache = CacheManager::new();
let mut ctx = EvalContext::new();
ctx.timeout = Duration::ZERO;
let r = evaluate("1+1", &ctx, None, &cache);
assert!(matches!(r, Err(ref e) if e.kind == ErrorKind::Timeout));
}
{
let cache = CacheManager::new();
let ctx = EvalContext::new();
let r = evaluate("1/3", &ctx, Some(MAX_PRECISION + 1), &cache);
assert!(r.is_err());
}
{
let cache = CacheManager::new();
let ctx = EvalContext::new();
let r = evaluate("(1+2", &ctx, None, &cache);
assert!(r.is_err());
}
{
let cache = CacheManager::new();
let ctx = EvalContext::new();
let (r, domain, hit, fmt) = evaluate("2+3", &ctx, Some(5), &cache).unwrap();
assert_eq!(r, EvalResult::BigInt(num_bigint::BigInt::from(5)));
assert_eq!(domain, "precision");
assert!(!hit);
assert_eq!(fmt, Some(5));
}
{
let cache = CacheManager::new();
let ctx = EvalContext::new();
let _ = evaluate("2+3", &ctx, Some(5), &cache).unwrap();
let (r, domain, hit, fmt) = evaluate("2+3", &ctx, Some(5), &cache).unwrap();
assert_eq!(r, EvalResult::BigInt(num_bigint::BigInt::from(5)));
assert_eq!(domain, "precision");
assert!(hit);
assert_eq!(fmt, Some(5));
}
{
let cache = CacheManager::new();
let ctx = EvalContext::new();
let (r, domain, hit, fmt) = evaluate("2+3", &ctx, None, &cache).unwrap();
assert_eq!(r, EvalResult::Scalar(5.0));
assert_eq!(domain, "arithmetic");
assert!(!hit);
assert_eq!(fmt, None);
}
{
let cache = CacheManager::new();
let ctx = EvalContext::new();
let _ = evaluate("2+3", &ctx, None, &cache).unwrap();
let (r, domain, hit, fmt) = evaluate("2+3", &ctx, None, &cache).unwrap();
assert_eq!(r, EvalResult::Scalar(5.0));
assert_eq!(domain, "arithmetic");
assert!(hit);
assert_eq!(fmt, None);
}
{
let cache = CacheManager::new();
let ctx = EvalContext::new();
let (r, domain, _, _) = evaluate("gcd(12,18)", &ctx, None, &cache).unwrap();
assert_eq!(r, EvalResult::Scalar(6.0));
assert_eq!(domain, "number_theory");
}
{
let cache = CacheManager::new();
let ctx = EvalContext::new();
let (r, domain, _, _) = evaluate("C(10,3)", &ctx, None, &cache).unwrap();
assert_eq!(r, EvalResult::Scalar(120.0));
assert_eq!(domain, "combinatorics");
}
{
let cache = CacheManager::new();
let ctx = EvalContext::new();
let (r, domain, _, fmt) = evaluate("precision(5, 1/3)", &ctx, None, &cache).unwrap();
let _ = r;
let _ = domain;
assert_eq!(fmt, Some(5));
}
{
let cache = CacheManager::new();
let ctx = EvalContext::new();
let (_, _, _, fmt) = evaluate("sin(0)", &ctx, None, &cache).unwrap();
assert_eq!(fmt, None);
}
{
let cache = CacheManager::new();
let ctx = EvalContext::new();
let (_, _, hit1, _) = evaluate("6*7", &ctx, None, &cache).unwrap();
assert!(!hit1);
let (_, _, hit2, _) = evaluate("6*7", &ctx, None, &cache).unwrap();
assert!(hit2);
}
}
#[test]
fn test_cache_key_includes_vars_different_values_do_not_collide() {
let cache = CacheManager::new();
let ctx1 = EvalContext::new().with_var("x", 1.0);
let ctx2 = EvalContext::new().with_var("x", 2.0);
let (r1, _, hit1, _) = evaluate("x", &ctx1, None, &cache).unwrap();
assert_eq!(r1, EvalResult::Scalar(1.0));
assert!(!hit1, "first call must miss");
let (r2, _, hit2, _) = evaluate("x", &ctx2, None, &cache).unwrap();
assert_eq!(
r2,
EvalResult::Scalar(2.0),
"different vars must not return cached value from other vars"
);
assert!(!hit2, "different vars must not hit cache");
}
#[test]
fn test_cache_key_includes_timeout_different_values_do_not_collide() {
let cf = CanonicalForm::new("(+ 2 3)");
let ctx1 = EvalContext::new();
let mut ctx2 = EvalContext::new();
ctx2.timeout = Duration::from_secs(10);
let key1 = build_cache_key(&cf, &ctx1, None);
let key2 = build_cache_key(&cf, &ctx2, None);
assert_ne!(
key1, key2,
"different timeout must produce different cache key"
);
}
#[test]
fn test_build_cache_key_includes_vars() {
let cf = CanonicalForm::new("(+ 2 3)");
let ctx_empty = EvalContext::new();
let ctx_x1 = EvalContext::new().with_var("x", 1.0);
let ctx_x2 = EvalContext::new().with_var("x", 2.0);
let ctx_y = EvalContext::new().with_var("y", 1.0);
let key_empty = build_cache_key(&cf, &ctx_empty, None);
let key_x1 = build_cache_key(&cf, &ctx_x1, None);
let key_x2 = build_cache_key(&cf, &ctx_x2, None);
let key_y = build_cache_key(&cf, &ctx_y, None);
assert_ne!(key_empty, key_x1, "empty vars vs vars=x:1 must differ");
assert_ne!(key_x1, key_x2, "vars x:1 vs x:2 must differ");
assert_ne!(key_x1, key_y, "vars x:1 vs y:1 must differ");
let key_x1_again = build_cache_key(&cf, &ctx_x1, None);
assert_eq!(key_x1, key_x1_again, "same ctx must produce same key");
}
#[test]
fn test_build_cache_key_precision_prefix_preserved() {
let cf = CanonicalForm::new("(+ 2 3)");
let ctx = EvalContext::new();
let key_reg = build_cache_key(&cf, &ctx, None);
let key_prec = build_cache_key(&cf, &ctx, Some(5));
assert_ne!(
key_reg, key_prec,
"precision mode key must differ from regular mode"
);
assert!(
key_prec.as_str().contains("precision:"),
"precision mode key must contain precision: prefix, got {}",
key_prec
);
}
#[cfg(any(feature = "cli", feature = "http", feature = "mcp"))]
#[test]
fn test_precision_function_preserves_exact_rational() {
let cache = CacheManager::new();
let ctx = EvalContext::new();
let (result, domain, _, fmt_prec) =
evaluate("precision(20, 1/3)", &ctx, None, &cache).unwrap();
assert_eq!(domain, "precision");
assert_eq!(fmt_prec, Some(20));
let r = match result {
EvalResult::BigRational(r) => r,
other => panic!("expected BigRational(1/3), got {:?}", other),
};
let one = num_bigint::BigInt::from(1);
let three = num_bigint::BigInt::from(3);
let expected = num_rational::BigRational::new(one, three);
assert_eq!(
r, expected,
"precision(20, 1/3) must be exact 1/3, got {}",
r
);
let formatted = crate::domains::format_bigrational(&r, Some(20));
assert_eq!(
formatted, "0.33333333333333333333",
"20-digit 1/3 must be exact, got {}",
formatted
);
}
#[cfg(any(feature = "cli", feature = "http", feature = "mcp"))]
#[test]
fn test_precision_function_preserves_exact_rational_other_fraction() {
let cache = CacheManager::new();
let ctx = EvalContext::new();
let (result, _, _, fmt_prec) = evaluate("precision(10, 1/6)", &ctx, None, &cache).unwrap();
assert_eq!(fmt_prec, Some(10));
let r = result.as_bigrational().expect("expected BigRational");
let one = num_bigint::BigInt::from(1);
let six = num_bigint::BigInt::from(6);
let expected = num_rational::BigRational::new(one, six);
assert_eq!(
*r, expected,
"precision(10, 1/6) must be exact 1/6, got {}",
r
);
let formatted = crate::domains::format_bigrational(r, Some(10));
assert_eq!(formatted, "0.1666666667", "got {}", formatted);
}
}