Skip to content

Commit

Permalink
Utils: display_error accepts output target
Browse files Browse the repository at this point in the history
  • Loading branch information
Ernest1338 committed Jan 23, 2025
1 parent b38541e commit b42e26f
Show file tree
Hide file tree
Showing 4 changed files with 52 additions and 42 deletions.
2 changes: 2 additions & 0 deletions .gitignore
Original file line number Diff line number Diff line change
@@ -1,5 +1,7 @@
/target
out.app
debug.ir
debug.asm

# Hugo
docs/public/
Expand Down
6 changes: 4 additions & 2 deletions src/compiler.rs
Original file line number Diff line number Diff line change
Expand Up @@ -5,8 +5,8 @@ use crate::{
expr_to_line_number, type_check, Ast, BinExpr, FuncCall, Variable, VariableDeclaration,
},
utils::{
dbg, dbg_plain, escape_string, get_tmp_fname, map_line_nr, measure_time, ErrorInner,
ErrorType,
dbg, dbg_file_if_env, dbg_plain, escape_string, get_tmp_fname, map_line_nr, measure_time,
ErrorInner, ErrorType,
},
Expr,
};
Expand Down Expand Up @@ -296,6 +296,7 @@ impl Compiler {

dbg("Variables", &self.variables);
dbg_plain("Compiled IR", &ir);
dbg_file_if_env(&ir, "debug.ir", "SAVE_IR");

let out_file_str = output_file.to_str().expect("invalid output file");

Expand Down Expand Up @@ -336,6 +337,7 @@ impl Compiler {
});

dbg("QBE output", &qbe_output);
dbg_file_if_env(&qbe_output, "debug.asm", "SAVE_ASM");

let mut cc_output = String::new();

Expand Down
29 changes: 16 additions & 13 deletions src/main.rs
Original file line number Diff line number Diff line change
@@ -1,7 +1,7 @@
use crate::{
compiler::Compiler,
interpreter::Interpreter,
utils::{display_error, display_error_stdout, ErrorInner, ErrorType},
utils::{display_error, ErrorInner, ErrorType, Output},
};
use std::{
fs::{canonicalize, read_to_string},
Expand Down Expand Up @@ -83,15 +83,15 @@ fn main() {
let tokens = match lexer(&code) {
Ok(tokens) => tokens,
Err(err) => {
display_error_stdout(err);
display_error(err, Output::Stdout);
continue;
}
};
let mut parser = Parser::new(&tokens);
let ast = match parser.parse() {
Ok(ast) => ast,
Err(err) => {
display_error_stdout(err);
display_error(err, Output::Stdout);
continue;
}
};
Expand All @@ -102,7 +102,7 @@ fn main() {

let res = interpreter.run(&input);
if let Err(err) = res {
display_error_stdout(err);
display_error(err, Output::Stdout);
}
}
}
Expand All @@ -114,10 +114,13 @@ fn main() {
Some(ref input) => match read_to_string(input) {
Ok(input) => input,
Err(_) => {
display_error(ErrorType::Generic(ErrorInner {
message: "Could not read source code file".to_string(),
line_number: None,
}));
display_error(
ErrorType::Generic(ErrorInner {
message: "Could not read source code file".to_string(),
line_number: None,
}),
Output::Stderr,
);
exit(1);
}
},
Expand All @@ -135,7 +138,7 @@ fn main() {
let tokens = measure_time("Lexical Analysis", || match lexer(&source_code) {
Ok(tokens) => tokens,
Err(err) => {
display_error(err);
display_error(err, Output::Stderr);
exit(1);
}
});
Expand All @@ -148,7 +151,7 @@ fn main() {
let ast = measure_time("Parsing", || match parser.parse() {
Ok(ast) => ast,
Err(err) => {
display_error(err);
display_error(err, Output::Stderr);
exit(1);
}
});
Expand All @@ -161,7 +164,7 @@ fn main() {
let mut interpreter = Interpreter::from_ast(ast);
measure_time("Interpreter Execution", || {
if let Err(err) = interpreter.run(&orig_source_code) {
display_error(err);
display_error(err, Output::Stderr);
exit(1);
}
});
Expand All @@ -172,7 +175,7 @@ fn main() {
let mut compiler = Compiler::from_ast(ast);
measure_time("Full Compiler Execution", || {
if let Err(err) = compiler.compile(&orig_source_code, args.output.clone()) {
display_error(err);
display_error(err, Output::Stderr);
exit(1);
}
});
Expand All @@ -193,7 +196,7 @@ fn main() {
let mut compiler = Compiler::from_ast(ast);
measure_time("Full Compiler Execution", || {
if let Err(err) = compiler.compile(&orig_source_code, args.output.clone()) {
display_error(err);
display_error(err, Output::Stderr);
exit(1);
}
});
Expand Down
57 changes: 30 additions & 27 deletions src/utils.rs
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@ use crate::parser::{expr_to_line_number, Expr};
use std::{
env,
fmt::{Debug, Display},
fs::OpenOptions,
io::{stdout, Write},
time::{Instant, SystemTime, UNIX_EPOCH},
};
Expand Down Expand Up @@ -163,47 +164,35 @@ fn get_line_nr_str(line_nr: Option<usize>) -> String {
}
}

/// Display error to the user in a pretty way
pub fn display_error(err: ErrorType) {
match err {
ErrorType::SyntaxError(inner) => {
eprintln!(
"{}{} {}",
color("[Syntax Error]", Color::LightRed),
get_line_nr_str(inner.line_number),
inner.message
);
}
ErrorType::Generic(inner) => {
eprintln!(
"{}{} {}",
color("[Error]", Color::LightRed),
get_line_nr_str(inner.line_number),
inner.message
);
}
};
#[derive(Debug, PartialEq)]
pub enum Output {
Stdout,
Stderr,
}

// FIXME code duplication
/// Display error to the user in a pretty way
pub fn display_error_stdout(err: ErrorType) {
pub fn display_error(err: ErrorType, target: Output) {
let output_fn = match target {
Output::Stdout => |msg| println!("{msg}"),
Output::Stderr => |msg| eprintln!("{msg}"),
};

match err {
ErrorType::SyntaxError(inner) => {
println!(
output_fn(&format!(
"{}{} {}",
color("[Syntax Error]", Color::LightRed),
get_line_nr_str(inner.line_number),
inner.message
);
));
}
ErrorType::Generic(inner) => {
println!(
output_fn(&format!(
"{}{} {}",
color("[Error]", Color::LightRed),
get_line_nr_str(inner.line_number),
inner.message
);
));
}
};
}
Expand All @@ -213,7 +202,7 @@ pub fn escape_string(s: &str) -> String {
s.replace("\\", "\\\\").replace("\"", "\\\"")
}

/// TODO
/// Maps a result to include line number information in errors
pub fn map_line_nr<T>(
result: Result<T, String>,
node: &Expr,
Expand All @@ -227,3 +216,17 @@ pub fn map_line_nr<T>(
})),
}
}

/// Writes data to a file if the given environment variable is set
pub fn dbg_file_if_env(data: &str, file: &str, var: &str) {
if env::var(var).is_ok() {
OpenOptions::new()
.write(true)
.create(true)
.truncate(true)
.open(file)
.unwrap()
.write_all(data.as_bytes())
.unwrap();
}
}

0 comments on commit b42e26f

Please sign in to comment.