Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Refactor CompilerError usage #1

Merged
merged 2 commits into from
Oct 18, 2024
Merged
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
56 changes: 21 additions & 35 deletions src/compiler/mod.rs
Original file line number Diff line number Diff line change
Expand Up @@ -16,17 +16,17 @@ use crate::Args;

#[derive(Error, Debug)]
pub enum CompileError {
Lex { e: lexer::LexError },
Parse { e: parser::ParseError },
FileIo { e: std::io::Error },
Lex(#[from] lexer::LexError),
Parse(#[from] parser::ParseError),
FileIo(#[from] std::io::Error),
}

impl Display for CompileError {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
match self {
Self::Lex { e } => write!(f, "{}", e),
Self::Parse { e } => write!(f, "{}", e),
Self::FileIo { e } => write!(f, "{}", e),
Self::Lex(e) => write!(f, "{}", e),
Self::Parse(e) => write!(f, "{}", e),
Self::FileIo(e) => write!(f, "{}", e),
}
}
}
Expand All @@ -38,46 +38,32 @@ impl Display for CompileError {
/// - p: bool, stop after parsing
/// - c: bool, stop after assembly code generation
pub fn compile(input_file: String, args: Args) -> Result<String, CompileError> {
let source = match fs::read_to_string(format!("{}.i", input_file)) {
Ok(s) => s,
Err(e) => return Err(CompileError::FileIo { e }),
};
let source = fs::read_to_string(format!("{}.i", input_file))?;

let tokens = match tokenize(source) {
Err(e) => return Err(CompileError::Lex { e }),
Ok(ts) => {
if args.lex {
ts.into_iter().for_each(|t| println!("TOKEN!!! {}", t));
return Ok(String::from("magic words"));
} else {
ts
}
}
};
let tokens = tokenize(source)?;
if args.lex {
tokens.into_iter().for_each(|t| println!("TOKEN!!! {}", t));
return Ok(String::from("magic words"));
}

let c_ast = parse(tokens)?;
if args.parse {
println!("VALID AST RETURNED: {}", c_ast);
return Ok(String::from("magic words"));
}

let c_ast = match parse(tokens) {
Err(e) => return Err(CompileError::Parse { e }),
Ok(ast) => {
if args.parse {
println!("VALID AST RETURNED: {}", ast);
return Ok(String::from("magic words"));
} else {
ast
}
}
};
let tacky = tacky::TackyEmitter::gen_tacky(c_ast);
if args.tacky {
return Ok(String::from("magic words"));
}

let asm_ast = gen_asm(tacky);
if args.codegen {
println!("GENERATED ASSEMBLY: {}", asm_ast);
return Ok(String::from("magic words"));
}
if let Err(e) = emit_asm(asm_ast, format!("{}.s", input_file)) {
return Err(CompileError::FileIo { e });
}

emit_asm(asm_ast, format!("{}.s", input_file))?;

Ok(format!("{}.s", input_file))
}