From a39b0c0d5ad6c32010d94d4cf25d6f00979ae422 Mon Sep 17 00:00:00 2001 From: Araozu Date: Fri, 1 Mar 2024 17:38:04 -0500 Subject: [PATCH] Properly handle errors in compilation pipeline --- src/file/mod.rs | 49 +++++++++++++++++++++++++------------------------ src/main.rs | 7 +++++-- 2 files changed, 30 insertions(+), 26 deletions(-) diff --git a/src/file/mod.rs b/src/file/mod.rs index a2676bc..60ce7a0 100644 --- a/src/file/mod.rs +++ b/src/file/mod.rs @@ -35,8 +35,12 @@ pub fn compile_file(input: &String) -> Result<(), ()> { } }; - let Some(out_code) = compile(&contents) else { - return Err(()); + let out_code = match compile(&contents) { + Ok(out_code) => out_code, + Err(error) => { + eprintln!("{}", error); + return Err(()); + } }; let mut output_path = Path::new(input) @@ -54,44 +58,41 @@ pub fn compile_file(input: &String) -> Result<(), ()> { } } -/// Executes Lexical analysis, handles errors and calls build_ast for the next phase -fn compile(input: &String) -> Option { +/// THP source code goes in, PHP code or an error comes out +fn compile(input: &String) -> Result { let tokens = lexic::get_tokens(input); - match tokens { - Ok(tokens) => Some(build_ast(input, tokens)), + let tokens = match tokens { + Ok(tokens) => tokens, Err(error) => { let chars: Vec = input.chars().into_iter().collect(); - println!( + return Err(format!( "{}:\n{}", "syntax error".on_red(), error.get_error_str(&chars) - ); - None + )) } - } + }; + + build_ast(input, tokens) } /// Executes Syntax analysis, and for now, Semantic analysis and Code generation. /// /// Prints the generated code in stdin -fn build_ast(input: &String, tokens: Vec) -> String { +fn build_ast(input: &String, tokens: Vec) -> Result { let ast = syntax::construct_ast(&tokens); - match ast { - Ok(ast) => { - match crate::semantic::check_semantics(&ast) { - Ok(_) => {} - Err(reason) => { - panic!("{}", reason) - } - }; - - codegen::codegen(&ast) - } + let ast = match ast { + Ok(ast) => ast, Err(reason) => { let chars: Vec = input.chars().into_iter().collect(); - panic!("{}", reason.get_error_str(&chars)) + let error = format!("{}: {}", "error".on_red(), reason.get_error_str(&chars)); + return Err(error) } - } + }; + + crate::semantic::check_semantics(&ast)?; + + Ok(codegen::codegen(&ast)) } diff --git a/src/main.rs b/src/main.rs index b40994d..0752f78 100755 --- a/src/main.rs +++ b/src/main.rs @@ -17,6 +17,9 @@ mod utils; mod error_handling; -fn main() -> Result<(), ()> { - cli::run_cli() +fn main() { + match cli::run_cli() { + Ok(_) => (), + Err(_) => std::process::exit(1), + } }