complexpr/src/bin/main.rs

47 lines
1.4 KiB
Rust
Raw Normal View History

use std::{rc::Rc, cell::RefCell, fs};
2022-09-06 13:52:29 +00:00
use complexpr::{eval::Environment, interpreter::interpret, value::Value, stdlib};
2022-09-06 13:52:29 +00:00
use rustyline::{self, error::ReadlineError};
2022-09-11 17:02:18 +00:00
const C_RESET: &str = "\x1b[0m";
const C_BLUE: &str = "\x1b[94m";
const PROMPT: &str = "\x1b[94m>> \x1b[0m";
2022-09-07 20:11:51 +00:00
2022-09-06 13:52:29 +00:00
fn main() -> Result<(), Box<dyn std::error::Error>> {
let args: Vec<String> = std::env::args().collect();
if args.len() == 2 {
let fname = &args[1];
let src = fs::read_to_string(fname)?;
2022-09-07 20:11:51 +00:00
let res = interpret(&src, Some(fname.into()), None, false);
if let Err(e) = res {
println!("{}", e);
}
2022-09-06 13:52:29 +00:00
} else {
repl()?;
}
Ok(())
}
fn repl() -> Result<(), Box<dyn std::error::Error>> {
2022-09-07 20:11:51 +00:00
println!("Press {}Ctrl+D{} to exit.", C_BLUE, C_RESET);
2022-09-06 13:52:29 +00:00
let mut rl = rustyline::Editor::<()>::new()?;
let env = Rc::new(RefCell::new(Environment::new()));
stdlib::load(&mut env.borrow_mut());
2022-09-06 13:52:29 +00:00
loop {
2022-09-07 20:11:51 +00:00
let readline = rl.readline(PROMPT);
2022-09-06 13:52:29 +00:00
match readline {
Ok(line) => {
2022-09-07 20:11:51 +00:00
let result = interpret(&line, None, Some(env.clone()), true);
2022-09-06 13:52:29 +00:00
match result {
Ok(Value::Nil) => (),
Ok(value) => println!("{}", value.repr()),
2022-09-07 20:11:51 +00:00
Err(e) => println!("{}", e)
2022-09-06 13:52:29 +00:00
}
}
Err(ReadlineError::Eof) => break,
Err(_) => (),
}
}
Ok(())
2022-09-11 17:02:18 +00:00
}