matrix/matrix-bin/src/repl.rs

78 lines
2.2 KiB
Rust
Raw Normal View History

2024-02-23 16:32:47 +00:00
use std::{io::Write, sync::atomic::Ordering};
2024-02-29 22:04:28 +00:00
use rustyline::{Config, EditMode, ColorMode, Editor, CompletionType, error::ReadlineError};
use matrix_lang::prelude::*;
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
2024-02-29 22:04:28 +00:00
pub struct Repl<'s, 'a> {
state: &'s mut State<'a>
2024-02-19 23:38:15 +00:00
}
2024-02-29 22:04:28 +00:00
impl<'s, 'a> Repl<'s, 'a> {
2024-02-19 23:38:15 +00:00
2024-02-29 22:04:28 +00:00
pub fn new(state: &'s mut State<'a>) -> Self {
2024-02-19 23:38:15 +00:00
Self { state }
}
2024-02-29 22:04:28 +00:00
fn execute(&mut self, line: String) -> Result<Value> {
let fun = self.state.compile(line)?;
let val = self.state.execute(fun)?;
Ok(val)
}
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()
2024-02-29 22:04:28 +00:00
.indent_size(4)
.edit_mode(EditMode::Emacs)
2024-02-23 16:32:47 +00:00
.check_cursor_position(true)
2024-02-27 00:00:42 +00:00
.completion_type(CompletionType::List)
.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());
2024-02-29 22:04:28 +00:00
let histfile = std::env::var("MATRIX_HISTORY").ok();
2024-02-27 00:00:42 +00:00
let mut rl = Editor::with_config(config).unwrap();
rl.set_helper(Some(helper));
2024-02-29 22:04:28 +00:00
if let Some(hf) = &histfile {
rl.load_history(hf).ok();
}
2024-02-27 00:00:42 +00:00
2024-02-19 23:38:15 +00:00
loop {
2024-02-29 22:04:28 +00:00
let line = match rl.readline(">> ") {
Ok(line) => line,
Err(ReadlineError::Eof) => break,
Err(_) => continue,
2024-02-27 00:00:42 +00:00
};
2024-02-29 22:04:28 +00:00
rl.add_history_entry(&line).ok();
match self.execute(line) {
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-29 22:04:28 +00:00
Err(err) => crate::error(err, &self.state),
};
std::io::stdout().flush().ok();
}
if let Some(hf) = &histfile {
rl.save_history(hf).ok();
2024-02-19 23:38:15 +00:00
}
}
}