calnexus 0.2.0

A command-line math expression evaluator with 11 core and 3 optional (time/unit/fx) computation domains plus a numerical-linalg feature, symbolic calculus, REPL, batch processing, HTTP and MCP servers
Documentation
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
// Copyright (c) 2026 Kirky.X🌠
// SPDX-License-Identifier: MIT

//! REPL 模式:基于 rustyline 的交互式读-求值-打印循环,`:let`/`:vars`/`:clear`/`:help`/`:quit` 命令。

use crate::cli::format_result;
use crate::core::evaluate;
use crate::core::{EvalContext, EvalResult};
use crate::i18n::I18n;
use rustyline::completion::Completer;
use rustyline::{Editor, Helper, Highlighter, Hinter, Result as RlResult, Validator};

/// REPL 命令补全候选:函数名 + REPL 命令。
const REPL_COMMANDS: &[&str] = &[":let", ":vars", ":quit", ":q", ":help", ":clear"];

/// 已知函数名(用于 Tab 补全;由统一函数目录派生,含 feature 门控函数)。
fn known_functions() -> Vec<&'static str> {
    crate::function_catalog::all_function_names()
}

/// REPL 会话:持有路由器、缓存、变量上下文、i18n。
pub struct ReplSession {
    ctx: EvalContext,
    cache: crate::CacheManager,
    i18n: I18n,
}

impl ReplSession {
    /// 创建 REPL 会话,初始化空缓存与给定上下文。
    #[allow(dead_code)] // 纯 build(非 --all-targets)下仅测试使用(CLI 走 with_cache)
    pub fn new(ctx: EvalContext, i18n: I18n) -> Self {
        Self {
            ctx,
            cache: crate::CacheManager::new(),
            i18n,
        }
    }

    /// 创建 REPL 会话并注入既有缓存(CLI `--cache-size` 预算)。
    pub fn with_cache(ctx: EvalContext, i18n: I18n, cache: crate::CacheManager) -> Self {
        Self { ctx, cache, i18n }
    }

    /// 启动 REPL 主循环:读入 → REPL 命令或 parse+evaluate → 打印结果;错误不退出。
    pub fn run(mut self) -> i32 {
        let mut rl: Editor<ReplHelper, _> = Editor::new().expect("failed to init rustyline Editor");
        rl.set_helper(Some(ReplHelper));

        println!("{}", self.i18n.t("repl.welcome"));
        loop {
            // "calnexus> " 是数学语法(DP-3),跨语言通用,保留原样
            let readline = rl.readline("calnexus> ");
            match readline {
                Ok(line) => {
                    let trimmed = line.trim();
                    if trimmed.is_empty() {
                        continue;
                    }
                    let _ = rl.add_history_entry(trimmed);
                    if trimmed.starts_with(':') {
                        match self.handle_command(trimmed) {
                            CommandResult::Continue => {}
                            CommandResult::Quit => {
                                println!("{}", self.i18n.t("repl.bye"));
                                return 0;
                            }
                        }
                    } else {
                        self.evaluate_line(trimmed);
                    }
                }
                Err(rustyline::error::ReadlineError::Interrupted) => {
                    // Ctrl+C:继续
                    continue;
                }
                Err(rustyline::error::ReadlineError::Eof) => {
                    // Ctrl+D:退出
                    println!("{}", self.i18n.t("repl.bye"));
                    return 0;
                }
                Err(e) => {
                    eprintln!(
                        "{}",
                        self.i18n.tf("repl.error", &[("error", &e.to_string())])
                    );
                    return 1;
                }
            }
        }
    }

    /// 处理 REPL 命令。
    fn handle_command(&mut self, line: &str) -> CommandResult {
        let parts: Vec<&str> = line.splitn(2, char::is_whitespace).collect();
        let cmd = parts[0];
        match cmd {
            ":quit" | ":q" => CommandResult::Quit,
            ":help" => {
                self.print_help();
                CommandResult::Continue
            }
            ":vars" => {
                self.print_vars();
                CommandResult::Continue
            }
            ":clear" => {
                // 清屏:打印 ANSI 转义序列
                print!("\x1b[2J\x1b[H");
                CommandResult::Continue
            }
            ":let" => {
                if parts.len() < 2 {
                    eprintln!("{}", self.i18n.t("repl.usage_let"));
                    return CommandResult::Continue;
                }
                self.handle_let(parts[1]);
                CommandResult::Continue
            }
            _ => {
                eprintln!("{}", self.i18n.tf("repl.unknown_command", &[("cmd", cmd)]));
                CommandResult::Continue
            }
        }
    }

    /// 处理 `:let NAME = VALUE` 变量绑定。
    fn handle_let(&mut self, args: &str) {
        let eq_parts: Vec<&str> = args.splitn(2, '=').collect();
        if eq_parts.len() != 2 {
            eprintln!("{}", self.i18n.t("repl.let_missing_equals"));
            return;
        }
        let name = eq_parts[0].trim();
        let value_str = eq_parts[1].trim();
        if name.is_empty() {
            eprintln!("{}", self.i18n.t("repl.empty_var_name"));
            return;
        }
        match value_str.parse::<f64>() {
            Ok(v) => {
                self.ctx = self.ctx.clone().with_var(name, v);
                // "name = value" 是数学等式语法(DP-3),跨语言通用
                println!("{} = {}", name, v);
            }
            Err(e) => {
                // 尝试作为表达式求值
                match evaluate(value_str, &self.ctx, None, &self.cache) {
                    Ok((EvalResult::Scalar(v), _, _, _)) => {
                        self.ctx = self.ctx.clone().with_var(name, v);
                        println!("{} = {}", name, v);
                    }
                    Ok((result, _, _, _)) => {
                        let formatted = format_result(&result, None);
                        eprintln!(
                            "{}",
                            self.i18n
                                .tf("repl.let_non_scalar", &[("value", &formatted)])
                        );
                    }
                    Err(e2) => {
                        eprintln!(
                            "{}",
                            self.i18n.tf(
                                "repl.let_invalid_value",
                                &[
                                    ("value", value_str),
                                    // error1:std ParseFloatError(库文案,无 i18n 目录键),保持原文
                                    ("error1", &e.to_string()),
                                    ("error2", &e2.friendly(&self.i18n))
                                ]
                            )
                        );
                    }
                }
            }
        }
    }

    /// 打印所有已绑定变量。
    fn print_vars(&self) {
        if self.ctx.vars.is_empty() {
            println!("{}", self.i18n.t("repl.no_vars"));
            return;
        }
        let mut names: Vec<&String> = self.ctx.vars.keys().collect();
        names.sort();
        for name in names {
            if let Some(v) = self.ctx.vars.get(name) {
                // "name = value" 是数学等式语法(DP-3)
                println!("{} = {}", name, v);
            }
        }
    }

    /// 打印帮助信息。
    fn print_help(&self) {
        println!("{}", self.i18n.t("repl.help_title"));
        println!("{}", self.i18n.t("repl.help_let"));
        println!("{}", self.i18n.t("repl.help_vars"));
        println!("{}", self.i18n.t("repl.help_clear"));
        println!("{}", self.i18n.t("repl.help_help"));
        println!("{}", self.i18n.t("repl.help_quit"));
        println!();
        println!("{}", self.i18n.t("repl.help_otherwise"));
        println!("{}", self.i18n.t("repl.help_examples"));
    }

    /// 求值一行表达式并打印结果。
    fn evaluate_line(&mut self, expr: &str) {
        match evaluate(expr, &self.ctx, self.ctx.precision, &self.cache) {
            Ok((result, domain, cache_hit, fmt_prec)) => {
                let output = format_result(&result, fmt_prec);
                let cached_str = if cache_hit {
                    self.i18n.t("label.cached_suffix").to_string()
                } else {
                    String::new()
                };
                println!(
                    "{}",
                    self.i18n.tf(
                        "repl.result",
                        &[
                            ("value", &output),
                            ("domain", &domain),
                            ("cached", &cached_str)
                        ]
                    )
                );
            }
            Err(e) => {
                eprintln!(
                    "{}",
                    self.i18n
                        .tf("repl.eval_error", &[("error", &e.friendly(&self.i18n))])
                );
            }
        }
    }
}

/// 命令处理结果。
enum CommandResult {
    Continue,
    Quit,
}

/// rustyline Helper:提供 Tab 补全。
///
/// 手动实现 `Completer`,其余三个 trait 由 derive 生成默认空实现。
#[derive(Helper, Hinter, Validator, Highlighter)]
struct ReplHelper;

impl Completer for ReplHelper {
    type Candidate = String;

    fn complete(
        &self,
        line: &str,
        pos: usize,
        _ctx: &rustyline::Context<'_>,
    ) -> RlResult<(usize, Vec<String>)> {
        Ok(complete_candidates(line, pos))
    }
}

/// 纯函数:根据当前输入行和光标位置计算补全候选(抽离自 `Completer::complete`
/// 以便无需构造 rustyline Context 即可单测)。
fn complete_candidates(line: &str, pos: usize) -> (usize, Vec<String>) {
    // 仅在行尾补全
    if pos != line.len() {
        return (0, Vec::new());
    }
    let mut candidates: Vec<String> = Vec::new();

    // 补全 REPL 命令(以 : 开头)
    if line.starts_with(':') {
        for cmd in REPL_COMMANDS {
            if cmd.starts_with(line) {
                candidates.push(cmd.to_string());
            }
        }
        return (0, candidates);
    }

    // 补全函数名:提取当前正在输入的标识符前缀
    let prefix: String = line
        .chars()
        .rev()
        .take_while(|c| c.is_alphanumeric() || *c == '_')
        .collect::<String>()
        .chars()
        .rev()
        .collect();
    if prefix.is_empty() {
        return (0, Vec::new());
    }
    let start = pos - prefix.len();
    for func in known_functions() {
        if func.starts_with(&prefix) && *func != prefix {
            candidates.push(func.to_string());
        }
    }
    (start, candidates)
}

// ============================ 单元测试 ============================

#[cfg(test)]
mod tests {
    use super::*;

    #[test]
    fn test_repl_session_new() {
        let session = ReplSession::new(EvalContext::new(), I18n::default());
        assert!(session.ctx.vars.is_empty());
    }

    #[test]
    fn test_repl_session_with_vars() {
        let ctx = EvalContext::new().with_var("x", 3.14);
        let session = ReplSession::new(ctx, I18n::default());
        assert_eq!(session.ctx.get_var("x"), Some(3.14));
    }

    #[test]
    fn test_handle_let_numeric() {
        let mut session = ReplSession::new(EvalContext::new(), I18n::default());
        session.handle_let("x = 42");
        assert_eq!(session.ctx.get_var("x"), Some(42.0));
    }

    #[test]
    fn test_handle_let_expression() {
        let mut session = ReplSession::new(EvalContext::new(), I18n::default());
        session.handle_let("y = 2+3*4");
        assert_eq!(session.ctx.get_var("y"), Some(14.0));
    }

    #[test]
    fn test_handle_let_missing_equals() {
        let mut session = ReplSession::new(EvalContext::new(), I18n::default());
        session.handle_let("x 42");
        assert!(session.ctx.vars.is_empty());
    }

    #[test]
    fn test_handle_let_empty_name() {
        let mut session = ReplSession::new(EvalContext::new(), I18n::default());
        session.handle_let(" = 42");
        assert!(session.ctx.vars.is_empty());
    }

    #[test]
    fn test_command_quit() {
        let mut session = ReplSession::new(EvalContext::new(), I18n::default());
        let result = session.handle_command(":quit");
        assert!(matches!(result, CommandResult::Quit));
    }

    #[test]
    fn test_command_q_alias() {
        let mut session = ReplSession::new(EvalContext::new(), I18n::default());
        let result = session.handle_command(":q");
        assert!(matches!(result, CommandResult::Quit));
    }

    #[test]
    fn test_command_help() {
        let mut session = ReplSession::new(EvalContext::new(), I18n::default());
        let result = session.handle_command(":help");
        assert!(matches!(result, CommandResult::Continue));
    }

    #[test]
    fn test_command_vars_empty() {
        let mut session = ReplSession::new(EvalContext::new(), I18n::default());
        let result = session.handle_command(":vars");
        assert!(matches!(result, CommandResult::Continue));
    }

    #[test]
    fn test_command_vars_with_bindings() {
        let ctx = EvalContext::new().with_var("x", 1.0).with_var("y", 2.0);
        let mut session = ReplSession::new(ctx, I18n::default());
        let result = session.handle_command(":vars");
        assert!(matches!(result, CommandResult::Continue));
    }

    #[test]
    fn test_command_let_then_vars() {
        let mut session = ReplSession::new(EvalContext::new(), I18n::default());
        session.handle_command(":let a = 10");
        session.handle_command(":let b = 20");
        assert_eq!(session.ctx.get_var("a"), Some(10.0));
        assert_eq!(session.ctx.get_var("b"), Some(20.0));
    }

    #[test]
    fn test_command_unknown() {
        let mut session = ReplSession::new(EvalContext::new(), I18n::default());
        let result = session.handle_command(":unknown");
        assert!(matches!(result, CommandResult::Continue));
    }

    #[test]
    fn test_command_let_no_args() {
        let mut session = ReplSession::new(EvalContext::new(), I18n::default());
        let result = session.handle_command(":let");
        assert!(matches!(result, CommandResult::Continue));
        assert!(session.ctx.vars.is_empty());
    }

    #[test]
    fn test_evaluate_line_arithmetic() {
        let mut session = ReplSession::new(EvalContext::new(), I18n::default());
        // 不应 panic,错误打印到 stderr
        session.evaluate_line("2+3*4");
    }

    #[test]
    fn test_evaluate_line_error_recovery() {
        let mut session = ReplSession::new(EvalContext::new(), I18n::default());
        // 语法错误:不应 panic
        session.evaluate_line("2++3");
        // 后续仍可正常求值
        session.evaluate_line("1+1");
    }

    #[test]
    fn test_evaluate_line_with_var() {
        let ctx = EvalContext::new().with_var("x", 5.0);
        let mut session = ReplSession::new(ctx, I18n::default());
        session.evaluate_line("x*2");
    }

    #[test]
    fn test_evaluate_line_symbolic() {
        let mut session = ReplSession::new(EvalContext::new(), I18n::default());
        session.evaluate_line("diff(x^2, x)");
    }

    #[test]
    fn test_completer_repl_command() {
        let (start, candidates) = complete_candidates(":l", 2);
        assert_eq!(start, 0);
        assert!(candidates.contains(&":let".to_string()));
    }

    #[test]
    fn test_completer_function_name() {
        let (start, candidates) = complete_candidates("si", 2);
        assert_eq!(start, 0);
        assert!(candidates.contains(&"sin".to_string()));
    }

    #[test]
    fn test_completer_no_match() {
        let (_start, candidates) = complete_candidates("zzz", 3);
        assert!(candidates.is_empty());
    }

    #[test]
    fn test_completer_exact_match_excluded() {
        // 完全匹配时不补全(func == prefix 排除)
        let (_start, candidates) = complete_candidates("sin", 3);
        assert!(!candidates.contains(&"sin".to_string()));
    }

    #[test]
    fn test_command_clear() {
        let mut session = ReplSession::new(EvalContext::new(), I18n::default());
        let result = session.handle_command(":clear");
        assert!(matches!(result, CommandResult::Continue));
    }

    #[test]
    fn test_handle_let_non_scalar_result() {
        // let x = 3+4i → evaluate 返回 Complex(非 Scalar 分支)
        let mut session = ReplSession::new(EvalContext::new(), I18n::default());
        session.handle_let("x = 3+4i");
        assert!(session.ctx.get_var("x").is_none());
    }

    #[test]
    fn test_handle_let_eval_error() {
        // let x = 2++3 → f64 解析与 evaluate 双双失败(error1/error2 均上报)
        let mut session = ReplSession::new(EvalContext::new(), I18n::default());
        session.handle_let("x = 2++3");
        assert!(session.ctx.get_var("x").is_none());
    }

    #[test]
    fn test_complete_candidates_pos_not_at_end() {
        let (start, candidates) = complete_candidates("sin", 1);
        assert_eq!(start, 0);
        assert!(candidates.is_empty());
    }

    #[test]
    fn test_complete_candidates_empty_prefix() {
        // "(" 行尾无标识符字符 → 提取前缀为空
        let (start, candidates) = complete_candidates("(", 1);
        assert_eq!(start, 0);
        assert!(candidates.is_empty());
    }
}