complexpr/complexpr-bin/src/main.rs

65 lines
2.1 KiB
Rust
Raw Normal View History

2022-09-13 17:31:29 +00:00
use std::{rc::Rc, cell::RefCell, fs, panic::{self, PanicInfo}};
2022-09-06 13:52:29 +00:00
use backtrace::Backtrace;
use complexpr::{env::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
fn panic_hook(info: &PanicInfo) {
eprintln!("{:?}", Backtrace::new());
eprintln!("!!! Internal interpreter error occured !!!");
if let Some(s) = std::thread::current().name() {
eprintln!("Thread: {}", s);
}
if let Some(loc) = info.location() {
eprintln!("Location: {}:{}:{}", loc.file(), loc.line(), loc.column())
}
if let Some(s) = info.payload().downcast_ref::<&str>() {
eprintln!("Message: {}", s);
} else if let Some(s) = info.payload().downcast_ref::<String>() {
eprintln!("Message: {}", s);
}
}
2022-09-06 13:52:29 +00:00
fn main() -> Result<(), Box<dyn std::error::Error>> {
panic::set_hook(Box::new(panic_hook));
2022-09-06 13:52:29 +00:00
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()),
Err(e) => print!("{}", e)
2022-09-06 13:52:29 +00:00
}
}
Err(ReadlineError::Eof) => break,
Err(_) => (),
}
}
Ok(())
2022-09-11 17:02:18 +00:00
}