use std::borrow::Cow;
use crate::core::{AstNode, CalcError, EvalContext};
pub fn ensure_math_constants(ctx: &EvalContext) -> Cow<'_, EvalContext> {
let needs_pi = ctx.get_var("pi").is_none();
let needs_e = ctx.get_var("e").is_none();
if !needs_pi && !needs_e {
return Cow::Borrowed(ctx);
}
let mut ctx = ctx.clone();
if needs_pi {
ctx = ctx.with_var("pi", std::f64::consts::PI);
}
if needs_e {
ctx = ctx.with_var("e", std::f64::consts::E);
}
Cow::Owned(ctx)
}
pub fn resolve_variable(ctx: &EvalContext, name: &str) -> Result<f64, CalcError> {
ctx.get_var(name).ok_or_else(|| {
CalcError::eval(format!("unbound variable: {}", name)).with_i18n(
"msg.unbound_variable",
vec![("name".to_string(), name.to_string())],
)
})
}
pub fn extract_variable_name(ast: &AstNode) -> Result<String, CalcError> {
match ast {
AstNode::Variable(name) => Ok(name.clone()),
_ => Err(
CalcError::domain(format!("expected variable name, got: {:?}", ast)).with_i18n(
"msg.domain.expected_variable_name",
vec![("node".to_string(), format!("{:?}", ast))],
),
),
}
}
pub fn unsupported_node_error(domain: &str, ast: &AstNode) -> CalcError {
CalcError::domain(format!(
"{} domain does not support this node type: {:?}",
domain, ast
))
.with_i18n(
"msg.domain.unsupported_node",
vec![
("domain".to_string(), domain.to_string()),
("node".to_string(), format!("{:?}", ast)),
],
)
}
pub fn unsupported_function_error(domain: &str, name: &str) -> CalcError {
CalcError::domain(format!(
"unsupported function in {} domain: {}",
domain, name
))
.with_i18n(
"msg.domain.unsupported_function",
vec![
("domain".to_string(), domain.to_string()),
("name".to_string(), name.to_string()),
],
)
}