use crate::core::types::{AstNode, CalcError, EvalContext, EvalResult};
use std::collections::HashSet;
pub trait CalculationDomain: Send + Sync {
fn domain_name(&self) -> &str;
fn supports(&self, ast: &AstNode) -> bool;
fn evaluate(&self, ast: &AstNode, ctx: &EvalContext) -> Result<EvalResult, CalcError>;
fn priority(&self) -> u8;
fn nondeterministic_functions(&self) -> &'static [&'static str] {
&[]
}
}
pub struct DomainRouter {
domains: Vec<Box<dyn CalculationDomain>>,
nondeterministic_functions: HashSet<String>,
}
impl DomainRouter {
pub fn new() -> Self {
Self {
domains: Vec::new(),
nondeterministic_functions: HashSet::new(),
}
}
pub fn register(&mut self, domain: Box<dyn CalculationDomain>) {
for &func_name in domain.nondeterministic_functions() {
self.nondeterministic_functions
.insert(func_name.to_string());
}
self.domains.push(domain);
self.domains
.sort_by_key(|d| std::cmp::Reverse(d.priority()));
}
pub fn route(&self, ast: &AstNode) -> Result<&dyn CalculationDomain, CalcError> {
for domain in &self.domains {
if domain.supports(ast) {
return Ok(domain.as_ref());
}
}
let functions = collect_function_names(ast);
let detail = if functions.is_empty() {
"no functions".to_string()
} else {
format_functions_list(&functions)
};
Err(CalcError::domain(format!(
"no registered domain supports this expression ({})",
detail
))
.with_i18n(
"msg.core.no_registered_domain",
vec![("expr".to_string(), detail.to_string())],
))
}
pub fn domain_count(&self) -> usize {
self.domains.len()
}
pub fn domain_names(&self) -> Vec<&str> {
self.domains.iter().map(|d| d.domain_name()).collect()
}
pub fn is_nondeterministic(&self, ast: &AstNode) -> bool {
let functions = collect_function_names(ast);
functions
.iter()
.any(|f| self.nondeterministic_functions.contains(f))
}
}
impl Default for DomainRouter {
fn default() -> Self {
Self::new()
}
}
#[cfg(not(coverage))]
const _: () = {
const fn assert_send_sync<T: Send + Sync>() {}
assert_send_sync::<DomainRouter>();
};
fn collect_function_names(ast: &AstNode) -> Vec<String> {
let mut names = Vec::new();
collect_function_names_recursive(ast, &mut names);
names.sort();
names.dedup();
names
}
const MAX_DISPLAY_FUNCTIONS: usize = 5;
fn format_functions_list(functions: &[String]) -> String {
if functions.len() <= MAX_DISPLAY_FUNCTIONS {
return format!("functions: {:?}", functions);
}
let displayed: Vec<&str> = functions
.iter()
.take(MAX_DISPLAY_FUNCTIONS)
.map(String::as_str)
.collect();
let remaining = functions.len() - MAX_DISPLAY_FUNCTIONS;
format!("functions: {:?}, ... and {} more", displayed, remaining)
}
fn collect_function_names_recursive(ast: &AstNode, names: &mut Vec<String>) {
match ast {
AstNode::FunctionCall(name, args) => {
names.push(name.clone());
for arg in args {
collect_function_names_recursive(arg, names);
}
}
AstNode::BinaryOp(_, l, r) => {
collect_function_names_recursive(l, names);
collect_function_names_recursive(r, names);
}
AstNode::UnaryOp(_, e) => {
collect_function_names_recursive(e, names);
}
_ => {}
}
}
#[cfg(test)]
mod tests {
use super::*;
use crate::core::parser::parse;
use crate::core::ErrorKind;
const SCIENTIFIC_FUNCTIONS: &[&str] = &[
"sin", "cos", "tan", "asin", "acos", "atan", "ln", "log", "exp", "sinh", "cosh", "tanh",
"gamma", "erf",
];
const ARITHMETIC_FUNCTIONS: &[&str] = &["factorial", "mod", "abs"];
fn contains_scientific_function(ast: &AstNode) -> bool {
match ast {
AstNode::FunctionCall(name, args) => {
SCIENTIFIC_FUNCTIONS.contains(&name.as_str())
|| args.iter().any(contains_scientific_function)
}
AstNode::BinaryOp(_, l, r) => {
contains_scientific_function(l) || contains_scientific_function(r)
}
AstNode::UnaryOp(_, e) => contains_scientific_function(e),
_ => false,
}
}
fn is_arithmetic_only(ast: &AstNode) -> bool {
match ast {
AstNode::Number(_) | AstNode::Variable(_) => true,
AstNode::BinaryOp(_, l, r) => is_arithmetic_only(l) && is_arithmetic_only(r),
AstNode::UnaryOp(_, e) => is_arithmetic_only(e),
AstNode::FunctionCall(name, args) => {
ARITHMETIC_FUNCTIONS.contains(&name.as_str()) && args.iter().all(is_arithmetic_only)
}
AstNode::Complex(_, _)
| AstNode::Matrix(_)
| AstNode::List(_)
| AstNode::BigNumber(_)
| AstNode::Str(_) => false,
}
}
struct MockArithmeticDomain;
impl CalculationDomain for MockArithmeticDomain {
fn domain_name(&self) -> &str {
"arithmetic"
}
fn priority(&self) -> u8 {
10
}
fn supports(&self, ast: &AstNode) -> bool {
is_arithmetic_only(ast)
}
fn evaluate(&self, _ast: &AstNode, _ctx: &EvalContext) -> Result<EvalResult, CalcError> {
Ok(EvalResult::Scalar(0.0))
}
}
struct MockScientificDomain;
impl CalculationDomain for MockScientificDomain {
fn domain_name(&self) -> &str {
"scientific"
}
fn priority(&self) -> u8 {
20
}
fn supports(&self, ast: &AstNode) -> bool {
contains_scientific_function(ast)
}
fn evaluate(&self, _ast: &AstNode, _ctx: &EvalContext) -> Result<EvalResult, CalcError> {
Ok(EvalResult::Scalar(0.0))
}
}
struct ConfigurableMockDomain {
name: String,
priority: u8,
supports_result: bool,
}
impl CalculationDomain for ConfigurableMockDomain {
fn domain_name(&self) -> &str {
&self.name
}
fn priority(&self) -> u8 {
self.priority
}
fn supports(&self, _ast: &AstNode) -> bool {
self.supports_result
}
fn evaluate(&self, _ast: &AstNode, _ctx: &EvalContext) -> Result<EvalResult, CalcError> {
Ok(EvalResult::Scalar(0.0))
}
}
fn default_router() -> DomainRouter {
let mut router = DomainRouter::new();
router.register(Box::new(MockArithmeticDomain));
router.register(Box::new(MockScientificDomain));
router
}
#[test]
fn test_route_arithmetic_basic() {
let router = default_router();
let ast = parse("(2+9)*7-6").unwrap();
let domain = router.route(&ast).unwrap();
assert_eq!(domain.domain_name(), "arithmetic");
}
#[test]
fn test_route_arithmetic_power_factorial() {
let router = default_router();
let ast = parse("2^10 + factorial(5)").unwrap();
let domain = router.route(&ast).unwrap();
assert_eq!(domain.domain_name(), "arithmetic");
}
#[test]
fn test_route_arithmetic_mod_abs() {
let router = default_router();
let ast = parse("mod(10,3) + abs(-2)").unwrap();
let domain = router.route(&ast).unwrap();
assert_eq!(domain.domain_name(), "arithmetic");
}
#[test]
fn test_route_arithmetic_constant() {
let router = default_router();
let ast = parse("42").unwrap();
let domain = router.route(&ast).unwrap();
assert_eq!(domain.domain_name(), "arithmetic");
}
#[test]
fn test_route_scientific_trig() {
let router = default_router();
let ast = parse("sin(pi/2)").unwrap();
let domain = router.route(&ast).unwrap();
assert_eq!(domain.domain_name(), "scientific");
}
#[test]
fn test_route_scientific_log() {
let router = default_router();
let ast = parse("log(100, 10)").unwrap();
let domain = router.route(&ast).unwrap();
assert_eq!(domain.domain_name(), "scientific");
}
#[test]
fn test_route_scientific_gamma_erf() {
let router = default_router();
let ast = parse("gamma(5) + erf(1)").unwrap();
let domain = router.route(&ast).unwrap();
assert_eq!(domain.domain_name(), "scientific");
}
#[test]
fn test_route_scientific_hyperbolic() {
let router = default_router();
let ast = parse("sinh(1) + cosh(1)").unwrap();
let domain = router.route(&ast).unwrap();
assert_eq!(domain.domain_name(), "scientific");
}
#[test]
fn test_mixed_expression_routes_to_scientific() {
let router = default_router();
let ast = parse("sin(x) + 2*3").unwrap();
let domain = router.route(&ast).unwrap();
assert_eq!(domain.domain_name(), "scientific");
}
#[test]
fn test_scientific_priority_higher_than_arithmetic() {
let arithmetic = MockArithmeticDomain;
let scientific = MockScientificDomain;
assert!(scientific.priority() > arithmetic.priority());
}
#[test]
fn test_pure_arithmetic_not_supported_by_scientific() {
let scientific = MockScientificDomain;
let ast = parse("2+3*4").unwrap();
assert!(!scientific.supports(&ast));
let router = default_router();
let domain = router.route(&ast).unwrap();
assert_eq!(domain.domain_name(), "arithmetic");
}
#[test]
fn test_higher_priority_wins() {
let mut router = DomainRouter::new();
router.register(Box::new(ConfigurableMockDomain {
name: "A".to_string(),
priority: 10,
supports_result: true,
}));
router.register(Box::new(ConfigurableMockDomain {
name: "B".to_string(),
priority: 20,
supports_result: true,
}));
let ast = parse("1").unwrap();
let domain = router.route(&ast).unwrap();
assert_eq!(domain.domain_name(), "B");
}
#[test]
fn test_same_priority_registration_order_wins() {
let mut router = DomainRouter::new();
router.register(Box::new(ConfigurableMockDomain {
name: "first".to_string(),
priority: 10,
supports_result: true,
}));
router.register(Box::new(ConfigurableMockDomain {
name: "second".to_string(),
priority: 10,
supports_result: true,
}));
let ast = parse("1").unwrap();
let domain = router.route(&ast).unwrap();
assert_eq!(domain.domain_name(), "first");
}
#[test]
fn test_only_one_supports_selected() {
let mut router = DomainRouter::new();
router.register(Box::new(ConfigurableMockDomain {
name: "high_not_supporting".to_string(),
priority: 100,
supports_result: false,
}));
router.register(Box::new(ConfigurableMockDomain {
name: "low_supporting".to_string(),
priority: 1,
supports_result: true,
}));
let ast = parse("1").unwrap();
let domain = router.route(&ast).unwrap();
assert_eq!(domain.domain_name(), "low_supporting");
}
#[test]
fn test_unknown_function_no_match() {
let router = default_router();
let ast = parse("foo(1)").unwrap();
let result = router.route(&ast);
let e = result.err().expect("expected error");
assert!(
e.kind == ErrorKind::Domain,
"expected DomainError, got {:?}",
e
);
}
#[test]
fn test_no_domains_registered_error() {
let router = DomainRouter::new();
let ast = parse("1+2").unwrap();
let result = router.route(&ast);
let e = result.err().expect("expected error");
assert!(
e.kind == ErrorKind::Domain,
"expected DomainError, got {:?}",
e
);
}
#[test]
fn test_error_message_contains_function_name() {
let router = default_router();
let ast = parse("bar(2)").unwrap();
let err = router.route(&ast).err().expect("expected error");
assert_eq!(
err.kind,
ErrorKind::Domain,
"expected DomainError, got {:?}",
err
);
let msg = &err.message;
assert!(
msg.contains("bar"),
"error message should contain 'bar': {}",
msg
);
}
#[test]
fn test_router_loads_registered_domains() {
let router = default_router();
assert_eq!(router.domain_count(), 2);
let names = router.domain_names();
assert!(names.contains(&"arithmetic"));
assert!(names.contains(&"scientific"));
}
#[test]
fn test_register_then_route() {
let mut router = DomainRouter::new();
router.register(Box::new(ConfigurableMockDomain {
name: "custom".to_string(),
priority: 50,
supports_result: true,
}));
let ast = parse("1").unwrap();
let domain = router.route(&ast).unwrap();
assert_eq!(domain.domain_name(), "custom");
}
#[test]
fn test_domains_sorted_by_priority_desc() {
let mut router = DomainRouter::new();
router.register(Box::new(MockArithmeticDomain)); router.register(Box::new(MockScientificDomain));
let names = router.domain_names();
assert_eq!(names, vec!["scientific", "arithmetic"]);
}
#[test]
fn test_unimplemented_trait_cannot_register() {
let mut router = DomainRouter::new();
router.register(Box::new(MockArithmeticDomain));
assert_eq!(router.domain_count(), 1);
}
#[test]
fn test_router_is_send_sync() {
fn assert_send_sync<T: Send + Sync>(_: &T) {}
let router = DomainRouter::new();
assert_send_sync(&router);
}
#[test]
fn test_domain_router_default() {
let router = DomainRouter::default();
assert_eq!(router.domain_count(), 0);
}
#[test]
fn test_mock_arithmetic_domain_evaluate() {
let domain = MockArithmeticDomain;
let ast = parse("1+2").unwrap();
let ctx = EvalContext::new();
let result = domain.evaluate(&ast, &ctx).unwrap();
assert_eq!(result, EvalResult::Scalar(0.0));
}
#[test]
fn test_mock_scientific_domain_evaluate() {
let domain = MockScientificDomain;
let ast = parse("sin(1)").unwrap();
let ctx = EvalContext::new();
let result = domain.evaluate(&ast, &ctx).unwrap();
assert_eq!(result, EvalResult::Scalar(0.0));
}
#[test]
fn test_configurable_mock_domain_evaluate() {
let domain = ConfigurableMockDomain {
name: "test".to_string(),
priority: 10,
supports_result: true,
};
let ast = parse("1").unwrap();
let ctx = EvalContext::new();
let result = domain.evaluate(&ast, &ctx).unwrap();
assert_eq!(result, EvalResult::Scalar(0.0));
}
#[test]
fn test_is_arithmetic_only_non_arithmetic_nodes() {
assert!(!is_arithmetic_only(&AstNode::Complex(1.0, 2.0)));
assert!(!is_arithmetic_only(&AstNode::Matrix(vec![vec![
AstNode::Number(1.0)
]])));
assert!(!is_arithmetic_only(&AstNode::List(vec![AstNode::Number(
1.0
)])));
assert!(!is_arithmetic_only(&AstNode::BigNumber("123".to_string())));
}
#[test]
fn test_collect_function_names_unary_op_branch() {
let router = default_router();
let ast = AstNode::UnaryOp(
crate::core::types::UnaryOp::Neg,
Box::new(AstNode::FunctionCall(
"foo".to_string(),
vec![AstNode::Number(1.0)],
)),
);
let err = router.route(&ast).err().expect("expected error");
assert!(
err.to_string().contains("foo"),
"错误信息应包含 'foo': {}",
err
);
}
#[test]
fn test_route_error_truncates_long_function_list() {
let mut ast =
AstNode::FunctionCall("unknown_func_00".to_string(), vec![AstNode::Number(1.0)]);
for i in 1..50 {
ast = AstNode::BinaryOp(
crate::core::types::BinaryOp::Add,
Box::new(ast),
Box::new(AstNode::FunctionCall(
format!("unknown_func_{:02}", i),
vec![AstNode::Number(1.0)],
)),
);
}
let router = default_router();
let err = router.route(&ast).err().expect("expected error");
let msg = err.to_string();
assert!(
msg.len() < 500,
"error message too long ({} chars), should be truncated: {}",
msg.len(),
msg
);
assert!(
msg.contains("more") || msg.contains("..."),
"error message should indicate truncation: {}",
msg
);
}
#[test]
fn test_route_error_short_function_list_not_truncated() {
let ast = AstNode::FunctionCall("unknown_func".to_string(), vec![AstNode::Number(1.0)]);
let router = default_router();
let err = router.route(&ast).err().expect("expected error");
let msg = err.to_string();
assert!(
msg.contains("unknown_func") && !msg.contains("more"),
"short list should not be truncated: {}",
msg
);
}
use proptest::prelude::*;
proptest! {
#![proptest_config(ProptestConfig { cases: 256, ..ProptestConfig::default() })]
#[test]
fn prop_routing_deterministic(expr in (1u32..1000).prop_map(|n| format!("{}+{}", n, n+1))) {
let router = default_router();
let ast = parse(&expr).unwrap();
let d1 = router.route(&ast).unwrap().domain_name();
let d2 = router.route(&ast).unwrap().domain_name();
prop_assert_eq!(d1, d2);
}
#[test]
fn prop_priority_consistent(
high_prio in 50u8..255,
low_prio in 0u8..49
) {
let mut router = DomainRouter::new();
router.register(Box::new(ConfigurableMockDomain {
name: "low".to_string(),
priority: low_prio,
supports_result: true,
}));
router.register(Box::new(ConfigurableMockDomain {
name: "high".to_string(),
priority: high_prio,
supports_result: true,
}));
let ast = parse("1").unwrap();
let domain = router.route(&ast).unwrap();
prop_assert_eq!(domain.domain_name(), "high");
}
}
#[test]
fn test_v08_route_number_theory() {
let router = crate::domains::build_default_router();
let ast = parse("gcd(12,18)").unwrap();
let domain = router.route(&ast).unwrap();
assert_eq!(domain.domain_name(), "number_theory");
}
#[test]
fn test_v08_route_combinatorics() {
let router = crate::domains::build_default_router();
let ast = parse("P(5,2)").unwrap();
let domain = router.route(&ast).unwrap();
assert_eq!(domain.domain_name(), "combinatorics");
}
#[test]
fn test_v08_route_vector() {
let router = crate::domains::build_default_router();
let ast = parse("dot([1,2],[3,4])").unwrap();
let domain = router.route(&ast).unwrap();
assert_eq!(domain.domain_name(), "vector");
}
#[test]
fn test_v08_route_polynomial() {
let router = crate::domains::build_default_router();
let ast = parse("poly_add(x+1,x-1)").unwrap();
let domain = router.route(&ast).unwrap();
assert_eq!(domain.domain_name(), "polynomial");
}
#[test]
fn test_v08_disambiguate_mod_pow_to_number_theory() {
let router = crate::domains::build_default_router();
let ast = parse("mod_pow(2,10,1000)").unwrap();
let domain = router.route(&ast).unwrap();
assert_eq!(domain.domain_name(), "number_theory");
}
#[test]
fn test_v08_disambiguate_mean_to_statistics() {
let router = crate::domains::build_default_router();
let ast = parse("mean([1,2,3])").unwrap();
let domain = router.route(&ast).unwrap();
assert_eq!(domain.domain_name(), "statistics");
}
#[test]
fn test_v08_unknown_function_error() {
let router = crate::domains::build_default_router();
let ast = parse("unknown_func(1)").unwrap();
let result = router.route(&ast);
let e = result.err().expect("expected error");
assert!(e.kind == ErrorKind::Domain);
assert!(
e.to_string().contains("unknown_func"),
"错误信息应包含 'unknown_func': {}",
e
);
}
struct NondeterministicMockDomain {
funcs: &'static [&'static str],
}
impl CalculationDomain for NondeterministicMockDomain {
fn domain_name(&self) -> &str {
"nondeterministic_mock"
}
fn priority(&self) -> u8 {
50
}
fn supports(&self, _ast: &AstNode) -> bool {
false
}
fn evaluate(&self, _ast: &AstNode, _ctx: &EvalContext) -> Result<EvalResult, CalcError> {
Ok(EvalResult::Scalar(0.0))
}
fn nondeterministic_functions(&self) -> &'static [&'static str] {
self.funcs
}
}
#[test]
fn test_is_nondeterministic_empty_router() {
let router = DomainRouter::new();
let ast = parse("now()").unwrap();
assert!(!router.is_nondeterministic(&ast));
let ast = parse("sin(1)").unwrap();
assert!(!router.is_nondeterministic(&ast));
}
#[test]
fn test_is_nondeterministic_with_declaration() {
let mut router = DomainRouter::new();
router.register(Box::new(NondeterministicMockDomain { funcs: &["now"] }));
assert!(
router.is_nondeterministic(&parse("now()").unwrap()),
"now() 必须检测为非确定性"
);
assert!(
router.is_nondeterministic(&parse("now()+1").unwrap()),
"now()+1 必须检测为非确定性"
);
assert!(
router.is_nondeterministic(&parse("sin(now())").unwrap()),
"sin(now()) 必须检测为非确定性"
);
assert!(
!router.is_nondeterministic(&parse("sin(1)").unwrap()),
"sin(1) 不含非确定性函数"
);
assert!(
!router.is_nondeterministic(&parse("1+2").unwrap()),
"1+2 不含非确定性函数"
);
}
#[test]
fn test_is_nondeterministic_multiple_functions() {
let mut router = DomainRouter::new();
router.register(Box::new(NondeterministicMockDomain {
funcs: &["now", "today", "fx"],
}));
assert!(router.is_nondeterministic(&parse("now()").unwrap()));
assert!(router.is_nondeterministic(&parse("today()").unwrap()));
assert!(router.is_nondeterministic(&parse("fx(1,\"USD\",\"CNY\")").unwrap()));
assert!(!router.is_nondeterministic(&parse("sin(1)").unwrap()));
}
}