complexpr/complexpr-bin/src/main.rs

72 lines
2.1 KiB
Rust
Raw Normal View History

2022-09-22 21:36:20 +00:00
use std::{fs, panic::{self, PanicInfo}, process::ExitCode};
2022-09-06 13:52:29 +00:00
use backtrace::Backtrace;
2022-09-23 19:09:22 +00:00
use complexpr::{interpreter::interpret, env::Environment};
2022-09-18 06:05:01 +00:00
mod helper;
2022-09-22 21:36:20 +00:00
mod repl;
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-23 19:09:22 +00:00
fn create_env() -> Environment {
let mut env = Environment::new();
complexpr_stdlib::prelude::load(&mut env);
complexpr_stdlib::io::load(&mut env);
complexpr_stdlib::iter::load(&mut env);
complexpr_stdlib::math::load(&mut env);
env
}
2022-09-22 21:36:20 +00:00
fn main() -> ExitCode {
panic::set_hook(Box::new(panic_hook));
2022-09-06 13:52:29 +00:00
let args: Vec<String> = std::env::args().collect();
2022-09-23 19:09:22 +00:00
if args.len() >= 2 {
2022-09-06 13:52:29 +00:00
let fname = &args[1];
2022-09-22 21:36:20 +00:00
let src = match fs::read_to_string(fname) {
Ok(src) => src,
Err(e) => {
eprintln!("Error reading file: {}", e);
return ExitCode::from(2);
}
};
2022-09-23 19:09:22 +00:00
let env = create_env().wrap();
let res = interpret(&src, Some(fname.into()), Some(env), false);
2022-09-07 20:11:51 +00:00
if let Err(e) = res {
2022-09-17 23:23:54 +00:00
eprintln!("Error: {}", e);
2022-09-22 21:36:20 +00:00
return ExitCode::from(1);
2022-09-07 20:11:51 +00:00
}
2022-09-06 13:52:29 +00:00
} else {
2022-09-22 21:36:20 +00:00
#[cfg(feature = "repl")]
{
if let Err(e) = repl::repl() {
eprintln!("Error: {}", e);
return ExitCode::from(4)
2022-09-06 13:52:29 +00:00
}
2022-09-22 21:36:20 +00:00
}
#[cfg(not(feature = "repl"))]
{
eprintln!("Expected a file to execute. To use complexpr in repl mode, enable the 'repl' feature (enabled by default).");
return ExitCode::from(3)
2022-09-06 13:52:29 +00:00
}
}
2022-09-22 21:36:20 +00:00
ExitCode::SUCCESS
2022-09-11 17:02:18 +00:00
}