use crate::core::evaluate;
use crate::domains::format_bigrational;
use crate::output::{format_canonical, format_latex, generate_steps};
use crate::{AstCanonicalizer, CacheManager, CalcError, EvalContext, EvalResult, parse};
use sdforge::clap::{self, CommandFactory, FromArgMatches, Parser};
use std::io::{self, IsTerminal, Read};
#[derive(Parser)]
#[command(
name = "calnexus",
version,
about = "CalNexus: math expression evaluator",
long_about = None
)]
struct Cli {
expression: Option<String>,
#[arg(long = "var")]
vars: Vec<String>,
#[arg(long, conflicts_with_all = ["latex", "canonical", "steps"])]
json: bool,
#[arg(long, conflicts_with_all = ["json"])]
explain: bool,
#[arg(long, value_parser = clap::builder::PossibleValuesParser::new(["en", "zh"]))]
lang: Option<String>,
#[arg(long, conflicts_with_all = ["canonical", "batch"])]
precision: Option<usize>,
#[arg(long, conflicts_with_all = ["canonical", "latex", "steps", "batch"])]
repl: bool,
#[arg(long, conflicts_with_all = ["canonical", "latex", "steps", "precision", "repl"])]
batch: Option<String>,
#[arg(long, conflicts_with_all = ["json", "canonical"])]
latex: bool,
#[arg(long, conflicts_with_all = ["json", "canonical"])]
steps: bool,
#[arg(long, conflicts_with_all = ["json", "latex", "steps", "precision", "repl", "batch"])]
canonical: bool,
#[arg(long)]
timeout: Option<f64>,
#[arg(long)]
cache_size: Option<u64>,
#[cfg(feature = "server")]
#[arg(long)]
bind: Option<String>,
#[arg(long)]
list_functions: bool,
#[cfg(feature = "server")]
#[arg(long, conflicts_with_all = ["repl", "batch", "canonical", "latex", "steps", "json", "explain", "precision", "serve_mcp"])]
serve_http: bool,
#[cfg(feature = "server")]
#[arg(long, conflicts_with_all = ["repl", "batch", "canonical", "latex", "steps", "json", "explain", "precision", "serve_http"])]
serve_mcp: bool,
}
pub fn run() -> i32 {
let about_i18n = peek_lang_i18n();
let matches = localized_command(&about_i18n).get_matches();
let cli = Cli::from_arg_matches(&matches).unwrap_or_else(|e| e.exit());
let i18n = match cli.lang.as_deref() {
Some(lang) => crate::i18n::I18n::from_str(lang),
None => crate::i18n::I18n::from_detected(),
};
let timeout_secs = match resolve_timeout(&i18n, cli.timeout) {
Ok(t) => t,
Err(msg) => {
eprintln!("calnexus: {}", msg);
return 2;
}
};
let cache_budget = match cache_budget_bytes(&i18n, cli.cache_size) {
Ok(b) => b,
Err(msg) => {
eprintln!("calnexus: {}", msg);
return 2;
}
};
#[cfg(feature = "server")]
if cli.serve_http || cli.serve_mcp {
return run_server_mode(&cli, &i18n);
}
if cli.list_functions {
return run_list_functions();
}
if cli.repl {
return run_repl_mode(&cli, &i18n, timeout_secs, cache_budget);
}
if let Some(path) = &cli.batch {
return run_batch_mode(path, &cli, &i18n, timeout_secs, cache_budget);
}
let expr = match get_expression(&cli, &i18n) {
Ok(e) => e,
Err(e) => return handle_error(&e, &cli, &i18n),
};
let mut ctx = match parse_vars(&cli.vars) {
Ok(ctx) => ctx,
Err(e) => return handle_error(&e, &cli, &i18n),
};
ctx.precision = cli.precision;
ctx.timeout = std::time::Duration::from_secs_f64(timeout_secs);
if cli.canonical {
run_canonical_mode(&expr, &cli, &i18n)
} else if cli.latex || cli.steps {
run_latex_steps_mode(&expr, &ctx, &cli, &i18n)
} else {
run_default_mode(&expr, &ctx, &cli, &i18n, cache_budget)
}
}
fn peek_lang_i18n() -> crate::i18n::I18n {
let mut args = std::env::args_os().skip(1);
while let Some(arg) = args.next() {
let arg = arg.to_string_lossy();
if let Some(value) = arg.strip_prefix("--lang=") {
return crate::i18n::I18n::from_str(value);
}
if arg == "--lang"
&& let Some(value) = args.next()
{
return crate::i18n::I18n::from_str(&value.to_string_lossy());
}
}
crate::i18n::I18n::from_detected()
}
fn localized_command(i18n: &crate::i18n::I18n) -> clap::Command {
const ARG_HELP: &[(&str, &str)] = &[
("expression", "cli.help_expression"),
("vars", "cli.help_var"),
("json", "cli.help_json"),
("explain", "cli.help_explain"),
("lang", "cli.help_lang"),
("precision", "cli.help_precision"),
("repl", "cli.help_repl"),
("batch", "cli.help_batch"),
("latex", "cli.help_latex"),
("steps", "cli.help_steps"),
("canonical", "cli.help_canonical"),
("timeout", "cli.help_timeout"),
("cache_size", "cli.help_cache_size"),
("list_functions", "cli.help_list_functions"),
];
let mut cmd = Cli::command().about(i18n.t("cli.about"));
for (id, key) in ARG_HELP {
let text = i18n.t(key);
cmd = cmd.mut_arg(*id, move |arg| arg.help(text));
}
#[cfg(feature = "server")]
{
cmd = cmd.mut_arg("bind", |arg| arg.help(i18n.t("cli.help_bind")));
cmd = cmd.mut_arg("serve_http", |arg| arg.help(i18n.t("cli.help_serve_http")));
cmd = cmd.mut_arg("serve_mcp", |arg| arg.help(i18n.t("cli.help_serve_mcp")));
}
cmd
}
fn run_list_functions() -> i32 {
for (domain, functions) in crate::function_catalog::DOMAIN_FUNCTIONS {
println!("{}:", domain);
for f in *functions {
println!(" {}", f);
}
}
0
}
#[cfg(feature = "server")]
fn run_server_mode(cli: &Cli, i18n: &crate::i18n::I18n) -> i32 {
let cache_budget = match cache_budget_bytes(i18n, cli.cache_size) {
Ok(b) => b,
Err(msg) => {
eprintln!("calnexus: {}", msg);
return 2;
}
};
crate::server::init_shared_cache(cache_budget);
let server_result = if cli.serve_http {
let bind = match resolve_bind(i18n, cli.bind.clone()) {
Ok(addr) => addr,
Err(msg) => {
eprintln!("calnexus: {}", msg);
return 2;
}
};
crate::server::HttpServer::new().with_addr(bind).run()
} else {
crate::server::McpServer::new().run()
};
match server_result {
Ok(()) => 0,
Err(e) => {
eprintln!("{}", e);
1
}
}
}
fn run_repl_mode(cli: &Cli, i18n: &crate::i18n::I18n, timeout_secs: f64, cache_budget: u64) -> i32 {
let mut ctx = match parse_vars(&cli.vars) {
Ok(ctx) => ctx,
Err(e) => return handle_error(&e, cli, i18n),
};
ctx.precision = cli.precision;
ctx.timeout = std::time::Duration::from_secs_f64(timeout_secs);
let cache = crate::CacheManager::with_capacity_bytes(cache_budget);
crate::repl::ReplSession::with_cache(ctx, i18n.clone(), cache).run()
}
fn run_batch_mode(
path: &str,
cli: &Cli,
i18n: &crate::i18n::I18n,
timeout_secs: f64,
cache_budget: u64,
) -> i32 {
let mut ctx = match parse_vars(&cli.vars) {
Ok(ctx) => ctx,
Err(e) => return handle_error(&e, cli, i18n),
};
ctx.timeout = std::time::Duration::from_secs_f64(timeout_secs);
let cache = crate::CacheManager::with_capacity_bytes(cache_budget);
crate::batch::BatchProcessor::run_with_cache(path, &ctx, cli.json, i18n, cache)
}
fn run_canonical_mode(expr: &str, cli: &Cli, i18n: &crate::i18n::I18n) -> i32 {
let ast = match parse(expr) {
Ok(ast) => ast,
Err(e) => return handle_error(&e, cli, i18n),
};
match AstCanonicalizer::canonicalize_no_fold(&ast) {
Ok((_canonical_ast, cf)) => {
println!("{}", format_canonical(&cf));
0
}
Err(e) => handle_error(&e, cli, i18n),
}
}
fn run_latex_steps_mode(expr: &str, ctx: &EvalContext, cli: &Cli, i18n: &crate::i18n::I18n) -> i32 {
let ast = match parse(expr) {
Ok(ast) => ast,
Err(e) => return handle_error(&e, cli, i18n),
};
let (canonical_ast, _cf) = match AstCanonicalizer::canonicalize(&ast) {
Ok(pair) => pair,
Err(e) => return handle_error(&e, cli, i18n),
};
if cli.steps {
match generate_steps(&ast, ctx) {
Ok(step_lines) => {
for line in &step_lines {
println!("{}", line);
}
}
Err(e) => return handle_error(&e, cli, i18n),
}
}
if cli.latex {
let cache = CacheManager::with_capacity_bytes(crate::core::DEFAULT_MAX_WEIGHT_BYTES);
match evaluate(expr, ctx, cli.precision, &cache) {
Ok((result, _domain, _cache_hit, fmt_prec)) => {
let latex_str = format_latex(&result, &canonical_ast, expr, fmt_prec);
println!("{}", latex_str);
}
Err(e) => return handle_error(&e, cli, i18n),
}
}
0
}
fn run_default_mode(
expr: &str,
ctx: &EvalContext,
cli: &Cli,
i18n: &crate::i18n::I18n,
cache_budget: u64,
) -> i32 {
let cache = CacheManager::with_capacity_bytes(cache_budget);
match evaluate(expr, ctx, cli.precision, &cache) {
Ok((result, domain, cache_hit, fmt_prec)) => {
if cli.json {
println!(
"{}",
format_json_output(&result, &domain, cache_hit, fmt_prec)
);
} else {
println!("{}", format_result(&result, fmt_prec));
}
0
}
Err(e) => handle_error(&e, cli, i18n),
}
}
fn format_json_output(
result: &EvalResult,
domain: &str,
cache_hit: bool,
fmt_prec: Option<usize>,
) -> String {
let cache_str = if cache_hit { "hit" } else { "miss" };
let result_value = match result {
EvalResult::Scalar(v) => serde_json::json!(*v),
EvalResult::Complex(re, im) => serde_json::json!({ "re": re, "im": im }),
EvalResult::Steps(v) => serde_json::json!(v),
_ => serde_json::json!(format_result(result, fmt_prec)),
};
crate::core::sort_json_keys(serde_json::json!({
"v": 1,
"result": result_value,
"domain": domain,
"cache": cache_str,
}))
.to_string()
}
fn handle_error(e: &CalcError, cli: &Cli, i18n: &crate::i18n::I18n) -> i32 {
handle_error_with_expr(e, cli.expression.as_deref(), cli, i18n)
}
fn handle_error_with_expr(
e: &CalcError,
expr: Option<&str>,
cli: &Cli,
i18n: &crate::i18n::I18n,
) -> i32 {
if cli.json {
println!("{}", e.to_json());
return e.kind.exit_code();
}
let mut contextual = e.clone();
let is_undefined_symbol = contextual.kind == CalcError::undefined_symbol("").kind
|| contextual.i18n_key == Some("msg.unbound_variable");
if is_undefined_symbol {
let name = contextual
.i18n_args
.iter()
.find(|(k, _)| k == "name")
.map(|(_, v)| v.clone())
.or_else(|| {
contextual
.message
.strip_prefix("undefined symbol: ")
.or_else(|| contextual.message.strip_prefix("Unbound variable: "))
.map(str::to_string)
});
if let Some(name) = name {
contextual.hint = Some(format!("define it via --var {name}=<value>"));
contextual = contextual.with_hint_i18n(
"hint.define_via_var",
vec![("name".to_string(), name.clone())],
);
}
}
let e = &contextual;
if cli.explain {
eprintln!("{}", e.to_explain(i18n));
} else {
eprintln!("{}: {}", i18n.t("cli.error_prefix"), e.friendly(i18n));
}
if let (Some(expr_text), Some(span)) = (expr, &e.span) {
let chars: Vec<char> = expr_text.chars().collect();
let start = span.start.min(chars.len());
let end = span.end.min(chars.len()).max(start).max(start + 1);
eprintln!(" | {}", expr_text);
eprint!(" | ");
for _ in 0..start {
eprint!(" ");
}
for _ in start..end {
eprint!("^");
}
eprintln!();
}
e.kind.exit_code()
}
fn get_expression(cli: &Cli, i18n: &crate::i18n::I18n) -> Result<String, CalcError> {
if let Some(expr) = &cli.expression {
return Ok(expr.clone());
}
if io::stdin().is_terminal() {
localized_command(i18n)
.try_get_matches_from(["calnexus", "--help"])
.unwrap_or_else(|e| e.exit());
return Err(CalcError::usage(String::new())); }
let mut input = String::new();
if io::stdin().read_to_string(&mut input).is_err() {
return Err(CalcError::usage("failed to read from stdin")
.with_i18n("cli.stdin_read_failed", vec![]));
}
let trimmed = input.trim().to_string();
if trimmed.is_empty() {
return Err(
CalcError::usage("empty expression on stdin").with_i18n("cli.empty_stdin", vec![])
);
}
Ok(trimmed)
}
fn resolve_timeout(i18n: &crate::i18n::I18n, cli_value: Option<f64>) -> Result<f64, String> {
const DEFAULT_TIMEOUT_SECS: f64 = 5.0;
const MIN: f64 = 0.1;
const MAX: f64 = 3600.0;
let raw = match cli_value {
Some(v) => v,
None => match std::env::var("CALNEXUS_TIMEOUT") {
Ok(s) => s
.trim()
.parse::<f64>()
.map_err(|_| i18n.tf("cli.invalid_timeout_env", &[("value", s.as_str())]))?,
Err(_) => DEFAULT_TIMEOUT_SECS,
},
};
if !(MIN..=MAX).contains(&raw) {
return Err(i18n.tf(
"cli.timeout_out_of_range",
&[
("value", raw.to_string().as_str()),
("min", MIN.to_string().as_str()),
("max", MAX.to_string().as_str()),
],
));
}
Ok(raw)
}
fn cache_budget_bytes(i18n: &crate::i18n::I18n, cli_value: Option<u64>) -> Result<u64, String> {
const DEFAULT_CACHE_SIZE: u64 = 10_000;
const BYTES_PER_ENTRY: u64 = 4096;
let entries = match cli_value {
Some(n) => n,
None => match std::env::var("CALNEXUS_CACHE_SIZE") {
Ok(s) => s
.trim()
.parse::<u64>()
.map_err(|_| i18n.tf("cli.invalid_cache_size_env", &[("value", s.as_str())]))?,
Err(_) => DEFAULT_CACHE_SIZE,
},
};
if entries == 0 {
return Err(i18n.t("cli.cache_size_invalid").to_string());
}
Ok(entries.saturating_mul(BYTES_PER_ENTRY).max(BYTES_PER_ENTRY))
}
#[cfg(feature = "server")]
fn resolve_bind(i18n: &crate::i18n::I18n, cli_value: Option<String>) -> Result<String, String> {
const DEFAULT_BIND: &str = "127.0.0.1:3000";
match cli_value {
Some(addr) => Ok(addr),
None => match std::env::var("CALNEXUS_BIND_ADDR") {
Ok(s) if !s.trim().is_empty() => Ok(s.trim().to_string()),
Ok(_) => Err(i18n.tf("cli.invalid_bind_addr", &[("reason", "empty value")])),
Err(_) => Ok(DEFAULT_BIND.to_string()),
},
}
}
fn parse_vars(vars: &[String]) -> Result<EvalContext, CalcError> {
let mut ctx = EvalContext::new();
for v in vars {
let parts: Vec<&str> = v.splitn(2, '=').collect();
if parts.len() != 2 {
return Err(
CalcError::usage(format!("invalid --var '{}', expected NAME=VALUE", v))
.with_i18n("cli.invalid_var", vec![("value".to_string(), v.clone())]),
);
}
let value: f64 = parts[1].parse::<f64>().map_err(|e| {
CalcError::usage(format!("invalid --var value '{}': {}", parts[1], e)).with_i18n(
"cli.invalid_var_value",
vec![
("value".to_string(), parts[1].to_string()),
("error".to_string(), e.to_string()),
],
)
})?;
ctx = ctx.with_var(parts[0], value);
}
Ok(ctx)
}
pub(crate) fn format_result(result: &EvalResult, fmt_prec: Option<usize>) -> String {
match result {
EvalResult::Scalar(v) => v.to_string(),
EvalResult::Complex(re, im) => format_complex(*re, *im),
EvalResult::Matrix(m) => format_matrix(m),
EvalResult::BigInt(b) => b.to_string(),
EvalResult::BigRational(r) => format_bigrational(r, fmt_prec),
EvalResult::Vector(v) => format_vector(v),
EvalResult::Polynomial(p) => format_polynomial(p),
EvalResult::ComplexList(c) => format_complex_list(c),
EvalResult::Symbolic(s) => s.clone(),
EvalResult::LaTeX(s) => s.clone(),
EvalResult::Steps(v) => v.join("\n"),
EvalResult::Json(v) => v.to_string(),
EvalResult::DateTime(s) => s.clone(),
}
}
fn format_complex(re: f64, im: f64) -> String {
if im >= 0.0 {
format!("{}+{}i", re, im)
} else {
format!("{}{}i", re, im)
}
}
fn format_matrix(m: &[Vec<f64>]) -> String {
let rows: Vec<String> = m
.iter()
.map(|row| {
let elems: Vec<String> = row.iter().map(|v| v.to_string()).collect();
format!("[{}]", elems.join(","))
})
.collect();
format!("[{}]", rows.join(","))
}
fn format_vector(v: &[f64]) -> String {
let elems: Vec<String> = v.iter().map(|x| x.to_string()).collect();
format!("[{}]", elems.join(","))
}
fn format_polynomial(p: &[f64]) -> String {
if p.is_empty() {
return "0".to_string();
}
let terms: Vec<String> = p
.iter()
.enumerate()
.rev()
.filter_map(|(i, &coef)| format_polynomial_term(coef, i))
.collect();
if terms.is_empty() {
return "0".to_string();
}
join_polynomial_terms(&terms)
}
fn format_polynomial_term(coef: f64, i: usize) -> Option<String> {
if coef == 0.0 {
return None;
}
let term = match i {
0 => format!("{}", coef),
1 => {
if coef == 1.0 {
"x".to_string()
} else if coef == -1.0 {
"-x".to_string()
} else {
format!("{}x", coef)
}
}
_ => {
if coef == 1.0 {
format!("x^{}", i)
} else if coef == -1.0 {
format!("-x^{}", i)
} else {
format!("{}x^{}", coef, i)
}
}
};
Some(term)
}
fn join_polynomial_terms(terms: &[String]) -> String {
let mut result = terms[0].clone();
for term in &terms[1..] {
if term.starts_with('-') {
result.push_str(term);
} else {
result.push('+');
result.push_str(term);
}
}
result
}
fn format_complex_list(c: &[(f64, f64)]) -> String {
let elems: Vec<String> = c.iter().map(|(re, im)| format_complex(*re, *im)).collect();
format!("[{}]", elems.join(","))
}
#[cfg(test)]
mod tests {
use super::*;
use crate::{AstNode, BinaryOp};
#[test]
fn locale_hint_flags_exist_in_clap_definition() {
use clap::CommandFactory;
let mut seen: Vec<String> = Vec::new();
let cmd = Cli::command();
let long_flags: Vec<String> = cmd
.get_arguments()
.filter_map(|a| a.get_long().map(|l| l.to_string()))
.collect();
for locale in ["en", "zh"] {
let path = format!("locales/{locale}/messages.ftl");
let raw = std::fs::read_to_string(&path).unwrap_or_else(|e| panic!("read {path}: {e}"));
collect_ftl_values(&raw, &mut seen);
}
let flag_re = regex::Regex::new(r"--[a-z][a-z0-9_-]*").unwrap();
let external_flags = ["features"];
let mut violations: Vec<String> = Vec::new();
for text in &seen {
for m in flag_re.find_iter(text) {
let flag = m.as_str().trim_start_matches('-').to_string();
if !long_flags.contains(&flag) && !external_flags.contains(&flag.as_str()) {
violations.push(format!("{text:?} 引用不存在的 --{flag}"));
}
}
}
assert!(
violations.is_empty(),
"locales 中存在指向不存在旗标的 hint:\n{}",
violations.join("\n")
);
}
#[test]
fn test_json_contract_non_cli_reachable_variants() {
let variants: Vec<(EvalResult, &str)> = vec![
(
EvalResult::Steps(vec!["2+9=11".into(), "11*3=33".into()]),
"steps",
),
(EvalResult::LaTeX(r"\frac{1}{2}".into()), "latex"),
(
EvalResult::Json(serde_json::json!({"U": [[1.0]], "S": [1.0]})),
"json",
),
(
EvalResult::DateTime("2026-09-14T00:00:00Z".into()),
"datetime",
),
];
for (result, name) in variants {
let out = format_json_output(&result, "test", false, None);
let parsed: serde_json::Value = serde_json::from_str(&out).unwrap_or_else(|e| {
panic!(
"{name}: {}: {e}",
crate::i18n::global_t("panic.invalid_json")
)
});
assert_eq!(parsed["v"], 1, "{name}: 契约版本必须为 1");
assert!(
parsed["result"].is_string() || parsed["result"].is_array(),
"{name}: result 应为字符串或数组"
);
}
}
fn collect_ftl_values(ftl: &str, out: &mut Vec<String>) {
for line in ftl.lines() {
let trimmed = line.trim_start();
if trimmed.is_empty() || trimmed.starts_with('#') {
continue;
}
if let Some((_, value)) = line.split_once(" = ") {
out.push(value.trim().to_string());
}
}
}
#[test]
fn resolve_timeout_out_of_range_en_message_unchanged() {
let i18n = crate::i18n::I18n::new(crate::i18n::Lang::En);
let err = resolve_timeout(&i18n, Some(99999.0)).unwrap_err();
assert_eq!(err, "--timeout 99999 out of range (0.1-3600 seconds)");
}
#[test]
fn resolve_timeout_accepts_flag_value() {
let i18n = crate::i18n::I18n::new(crate::i18n::Lang::En);
assert_eq!(resolve_timeout(&i18n, Some(0.1)).unwrap(), 0.1);
assert_eq!(resolve_timeout(&i18n, Some(3600.0)).unwrap(), 3600.0);
}
#[test]
fn cache_budget_bytes_invalid_en_message_unchanged() {
let i18n = crate::i18n::I18n::new(crate::i18n::Lang::En);
let err = cache_budget_bytes(&i18n, Some(0)).unwrap_err();
assert_eq!(err, "--cache-size must be a positive integer");
assert_eq!(cache_budget_bytes(&i18n, Some(2)).unwrap(), 2 * 4096);
}
#[test]
fn cli_about_override_matches_catalog_en() {
let i18n = crate::i18n::I18n::new(crate::i18n::Lang::En);
let cmd = Cli::command().about(i18n.t("cli.about"));
assert_eq!(
cmd.get_about().map(|s| s.to_string()).as_deref(),
Some("CalNexus: math expression evaluator")
);
}
#[test]
fn localized_command_localizes_about_and_all_arg_helps() {
let cases: [(&str, &str); 2] = [
("en", "CalNexus: math expression evaluator"),
("zh", "CalNexus: 数学表达式求值器"),
];
for (lang_tag, about) in cases {
let i18n = crate::i18n::I18n::from_str(lang_tag);
let cmd = localized_command(&i18n);
assert_eq!(
cmd.get_about().map(|s| s.to_string()).as_deref(),
Some(about),
"lang {lang_tag}: about mismatch"
);
let arg_help: &[(&str, &str)] = &[
("expression", "cli.help_expression"),
("vars", "cli.help_var"),
("json", "cli.help_json"),
("explain", "cli.help_explain"),
("lang", "cli.help_lang"),
("precision", "cli.help_precision"),
("repl", "cli.help_repl"),
("batch", "cli.help_batch"),
("latex", "cli.help_latex"),
("steps", "cli.help_steps"),
("canonical", "cli.help_canonical"),
("timeout", "cli.help_timeout"),
("cache_size", "cli.help_cache_size"),
("list_functions", "cli.help_list_functions"),
];
for (id, key) in arg_help {
let arg = cmd
.get_arguments()
.find(|a| a.get_id() == *id)
.unwrap_or_else(|| panic!("arg {id} not found"));
assert_eq!(
arg.get_help().map(|s| s.to_string()).as_deref(),
Some(i18n.t(key).as_str()),
"lang {lang_tag}: arg {id} help not localized"
);
}
if lang_tag == "zh" {
let vars_help = cmd
.get_arguments()
.find(|a| a.get_id() == "vars")
.and_then(|a| a.get_help().map(|s| s.to_string()))
.unwrap_or_default();
assert!(
vars_help.chars().any(|c| c >= '\u{4e00}'),
"zh help should contain CJK, got {vars_help:?}"
);
}
}
#[cfg(feature = "server")]
{
let i18n = crate::i18n::I18n::new(crate::i18n::Lang::Zh);
let cmd = localized_command(&i18n);
for id in ["bind", "serve_http", "serve_mcp"] {
let arg = cmd
.get_arguments()
.find(|a| a.get_id() == id)
.unwrap_or_else(|| panic!("arg {id} not found"));
assert!(
arg.get_help()
.map(|s| s.to_string())
.is_some_and(|h| h.chars().any(|c| c >= '\u{4e00}')),
"server arg {id} help should be localized in zh"
);
}
}
}
#[test]
fn peek_lang_i18n_without_flag_matches_detection() {
assert_eq!(peek_lang_i18n().lang(), crate::i18n::detect_locale());
}
#[test]
fn test_canonicalize_no_fold_basic_addition() {
let ast = parse("3+2").unwrap();
let (_, cf) = AstCanonicalizer::canonicalize_no_fold(&ast).unwrap();
assert_eq!(cf.as_str(), "(+ 2 3)");
}
#[test]
fn test_canonicalize_no_fold_equivalent_expressions() {
let ast1 = parse("3+2").unwrap();
let ast2 = parse("2+3").unwrap();
let (_, cf1) = AstCanonicalizer::canonicalize_no_fold(&ast1).unwrap();
let (_, cf2) = AstCanonicalizer::canonicalize_no_fold(&ast2).unwrap();
assert_eq!(cf1.as_str(), cf2.as_str());
assert_eq!(cf1.as_str(), "(+ 2 3)");
}
#[test]
fn test_canonicalize_no_fold_multiplication() {
let ast = parse("4*5").unwrap();
let (_, cf) = AstCanonicalizer::canonicalize_no_fold(&ast).unwrap();
assert_eq!(cf.as_str(), "(* 4 5)");
}
#[test]
fn test_canonicalize_no_fold_does_not_constant_fold() {
let ast = parse("2+3").unwrap();
let (_, cf_fold) = AstCanonicalizer::canonicalize(&ast).unwrap();
let (_, cf_no_fold) = AstCanonicalizer::canonicalize_no_fold(&ast).unwrap();
assert_eq!(cf_fold.as_str(), "5", "folded version");
assert_eq!(cf_no_fold.as_str(), "(+ 2 3)", "no-fold version");
}
#[test]
fn test_canonicalize_no_fold_preserves_double_neg_elimination() {
let ast = parse("-(2+3)").unwrap();
let (_, cf) = AstCanonicalizer::canonicalize_no_fold(&ast).unwrap();
assert_eq!(cf.as_str(), "(- (+ 2 3))");
}
#[test]
fn test_canonicalize_no_fold_does_not_fold_neg_number() {
let ast = parse("0-5").unwrap();
let (_, cf) = AstCanonicalizer::canonicalize_no_fold(&ast).unwrap();
assert_eq!(cf.as_str(), "(- 0 5)");
}
#[test]
fn test_canonicalize_no_fold_function_call() {
let ast = parse("sin(x)+cos(y)").unwrap();
let (_, cf) = AstCanonicalizer::canonicalize_no_fold(&ast).unwrap();
assert_eq!(cf.as_str(), "(+ (cos y) (sin x))");
}
#[test]
fn test_format_canonical_wrapper() {
use crate::CanonicalForm;
use crate::output::format_canonical;
let cf = CanonicalForm::new("(+ 2 3)");
assert_eq!(format_canonical(&cf), "(+ 2 3)");
}
#[test]
fn test_format_latex_dispatch_scalar() {
use crate::output::format_latex;
let r = EvalResult::Scalar(42.0);
let ast = AstNode::Number(42.0);
assert_eq!(format_latex(&r, &ast, "42", None), "42");
}
#[test]
fn test_format_latex_dispatch_matrix() {
use crate::output::format_latex;
let r = EvalResult::Matrix(vec![vec![1.0, 2.0], vec![3.0, 4.0]]);
let ast = AstNode::Number(0.0);
assert_eq!(
format_latex(&r, &ast, "[[1,2],[3,4]]", None),
"\\begin{pmatrix}1 & 2 \\\\ 3 & 4\\end{pmatrix}"
);
}
#[test]
fn test_format_latex_dispatch_symbolic_diff() {
use crate::output::format_latex;
let r = EvalResult::Symbolic("2*x".to_string());
let ast = AstNode::FunctionCall(
"diff".to_string(),
vec![
AstNode::BinaryOp(
BinaryOp::Pow,
Box::new(AstNode::Variable("x".to_string())),
Box::new(AstNode::Number(2.0)),
),
AstNode::Variable("x".to_string()),
],
);
let s = format_latex(&r, &ast, "diff(x^2,x)", None);
assert_eq!(s, "\\frac{d}{dx}\\left(x^{2}\\right) = 2 \\cdot x");
}
#[test]
fn test_generate_steps_basic() {
use crate::output::generate_steps;
let ast = parse("(2+9)*7-6").unwrap();
let ctx = EvalContext::new();
let steps = generate_steps(&ast, &ctx).unwrap();
assert_eq!(steps, vec!["2+9=11", "11*7=77", "77-6=71"]);
}
#[test]
fn test_format_result_handles_latex_variant() {
let r = EvalResult::LaTeX("\\alpha".to_string());
assert_eq!(format_result(&r, None), "\\alpha");
}
#[test]
fn test_format_result_handles_steps_variant() {
let r = EvalResult::Steps(vec!["1+1=2".to_string(), "2+2=4".to_string()]);
assert_eq!(format_result(&r, None), "1+1=2\n2+2=4");
}
}