matrix/matrix-bin/src/repl.rs

61 lines
1.7 KiB
Rust
Raw Normal View History

2024-02-23 16:32:47 +00:00
use std::{io::Write, sync::atomic::Ordering};
use matrix::{value::Value, vm::Interupt};
2024-02-27 00:00:42 +00:00
use rustyline::{Config, EditMode, ColorMode, Editor, CompletionType};
2024-02-23 16:32:47 +00:00
2024-02-27 00:00:42 +00:00
use crate::{State, helper::MatrixHelper};
2024-02-19 23:38:15 +00:00
pub struct Repl<'a> {
state: State<'a>
}
impl<'a> Repl<'a> {
pub fn new(state: State<'a>) -> Self {
Self { state }
}
pub fn run(&mut self) {
2024-02-23 16:32:47 +00:00
2024-02-27 00:00:42 +00:00
let interupt = self.state.vm.borrow().interupt();
2024-02-23 16:32:47 +00:00
ctrlc::set_handler(move || {
interupt.store(Interupt::KeyboardInterupt as usize, Ordering::SeqCst);
}).unwrap();
let config = Config::builder()
.check_cursor_position(true)
2024-02-27 00:00:42 +00:00
.completion_type(CompletionType::List)
.edit_mode(EditMode::Emacs)
.color_mode(if self.state.color { ColorMode::Enabled } else { ColorMode::Disabled })
2024-02-23 16:32:47 +00:00
.build();
2024-02-27 00:00:42 +00:00
let helper = MatrixHelper::new(self.state.vm.clone());
let mut rl = Editor::with_config(config).unwrap();
rl.set_helper(Some(helper));
2024-02-19 23:38:15 +00:00
loop {
let Ok(line) = rl.readline(">> ") else {
break;
};
2024-02-27 00:00:42 +00:00
if let Err(_) = rl.add_history_entry(&line) {
break;
};
2024-02-23 16:32:47 +00:00
match self.state.execute(line) {
2024-02-27 00:00:42 +00:00
Err(err) => crate::error(err, &self.state),
2024-02-23 16:32:47 +00:00
Ok(val) => {
if val != Value::Nil {
2024-02-27 00:00:42 +00:00
if self.state.color {
println!("{val:#}");
} else {
println!("{val}");
}
2024-02-23 16:32:47 +00:00
}
}
2024-02-19 23:38:15 +00:00
}
2024-02-23 16:32:47 +00:00
let _ = std::io::stdout().flush();
2024-02-19 23:38:15 +00:00
}
}
}