add better panic message and restructure src/args.rs

Signed-off-by: Amneesh Singh <natto@weirdnatto.in>
This commit is contained in:
2023-04-08 02:10:36 +05:30
parent 57ce926af6
commit 6979a02408
3 changed files with 68 additions and 36 deletions

View File

@@ -2,6 +2,6 @@ tricc (pronounced "trick-c" or "trixie" like pixie) is a WIP toy compiler I am
writing to understand compilers better, that's it. Will probably use LLVM as
the backend.
Notes:
- Does not work
- Is WIP
** Notes:
+ Does not work
+ Is WIP

View File

@@ -4,14 +4,22 @@ use std::process::exit;
const VERSION: &str = env!("CARGO_PKG_VERSION");
const CRATE: &str = env!("CARGO_CRATE_NAME");
// naive argument handling
#[derive(Default)]
struct Options {
pub struct Args {
version: bool,
file: String,
file: Option<String>,
}
// naive argument handling
pub fn handle() -> String {
impl Args {
pub fn new() -> Args {
Args {
version: false,
file: None,
}
}
pub fn handle(&mut self) {
let args: Vec<String> = env::args().collect();
if args.len() < 2 {
@@ -19,32 +27,34 @@ pub fn handle() -> String {
exit(0);
}
let mut options: Options = Default::default();
for arg in &args[1..] {
match arg.as_str() {
"-v" | "--version" => options.version = true,
"-v" | "--version" => self.version = true,
flag if flag.starts_with('-') => panic!("option {} not implemented!", flag),
file => {
if !options.file.is_empty() {
if self.file.is_some() {
panic!("please specify only a single source file!");
}
options.file = file.to_string();
self.file = Some(file.to_owned());
}
}
}
if options.version {
if self.version {
println!("{} version: {}", CRATE, VERSION);
}
if options.file.is_empty() {
if options.version {
if self.file.is_none() {
if self.version {
exit(0);
} else {
panic!("no file supplied!");
}
}
options.file
}
#[inline]
pub fn get_file(self) -> String {
self.file.expect("no file supplied!")
}
}

View File

@@ -1,6 +1,28 @@
use tricc::args;
use std::fs;
use std::panic;
use tricc::args::Args;
fn main() {
let file: String = args::handle();
println!("{}", file);
panic::set_hook(Box::new(|panic_info| {
if let Some(msg) = panic_info.payload().downcast_ref::<&str>() {
eprintln!("{}", msg);
} else if let Some(msg) = panic_info.payload().downcast_ref::<String>() {
eprintln!("{}", msg);
} else if let Some(location) = panic_info.location() {
eprintln!(
"panic occurred in file '{}' at line {}",
location.file(),
location.line(),
);
} else {
eprintln!("panic occurred");
}
}));
let mut args = Args::new();
args.handle();
let file = args.get_file();
let contents = fs::read_to_string(&file).expect("Couldn't read the file");
}