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};
const REPL_COMMANDS: &[&str] = &[":let", ":vars", ":quit", ":q", ":help", ":clear"];
fn known_functions() -> Vec<&'static str> {
crate::function_catalog::all_function_names()
}
pub struct ReplSession {
ctx: EvalContext,
cache: crate::CacheManager,
i18n: I18n,
}
impl ReplSession {
#[allow(dead_code)] pub fn new(ctx: EvalContext, i18n: I18n) -> Self {
Self {
ctx,
cache: crate::CacheManager::new(),
i18n,
}
}
pub fn with_cache(ctx: EvalContext, i18n: I18n, cache: crate::CacheManager) -> Self {
Self { ctx, cache, i18n }
}
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 {
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) => {
continue;
}
Err(rustyline::error::ReadlineError::Eof) => {
println!("{}", self.i18n.t("repl.bye"));
return 0;
}
Err(e) => {
eprintln!(
"{}",
self.i18n.tf("repl.error", &[("error", &e.to_string())])
);
return 1;
}
}
}
}
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" => {
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
}
}
}
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);
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", &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) {
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,
}
#[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))
}
}
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();
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());
session.evaluate_line("2+3*4");
}
#[test]
fn test_evaluate_line_error_recovery() {
let mut session = ReplSession::new(EvalContext::new(), I18n::default());
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() {
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 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 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());
}
}