Skip to content

Commit

Permalink
Use custom println macro instead of if-checks
Browse files Browse the repository at this point in the history
  • Loading branch information
megabyte6 committed Jan 10, 2025
1 parent 6179a77 commit 054e6df
Showing 1 changed file with 41 additions and 15 deletions.
56 changes: 41 additions & 15 deletions src/main.rs
Original file line number Diff line number Diff line change
Expand Up @@ -15,37 +15,65 @@ use preprocessor::{lex, parse};
fn main() {
let args = CliArgs::parse();

/// A macro that conditionally prints to the console based on the verbosity
/// flag.
///
/// This macro behaves like `println!` and can be used as a drop-in
/// replacement, but only prints the output if the `verbose` flag in the
/// `args` structure is set to `true`.
///
/// # Examples
///
/// ```rust
/// let args = Args { verbose: true };
/// vprintln!("This will be printed because verbose is true.");
///
/// let args = Args { verbose: false };
/// vprintln!("This will not be printed because verbose is false.");
/// ```
///
/// # Arguments
///
/// * `$($arg:tt)*` - The format string and arguments, similar to
/// `println!`.
///
/// # Note
///
/// The `args` structure must be in scope and contain a `verbose` field of
/// type `bool`.
macro_rules! vprintln {
($($arg:tt)*) => {{
if args.verbose {
println!($($arg)*);
}
}};
}

match args.command {
Some(Run {
file,
memory_available,
}) => {
if args.verbose {
println!("Reading file: {}", file);
}
let source = read_to_string(file).expect("Error: Unable to read file.");
vprintln!("Reading file: `{}`", file);
let source = read_to_string(file).expect("error: unable to read file.");

if args.verbose {
println!("Lexing source code...");
}
vprintln!("Lexing source code...");
let tokens = match lex(source.as_str()) {
Ok(tokens) => tokens,
Err(errors) => {
for error in errors {
eprintln!("Error: {}", error);
eprintln!("error: {}", error);
}
eprintln!("Please fix errors before continuing.");
return;
}
};

if args.verbose {
println!("Generating intermediate representation...")
}
vprintln!("Generating intermediate representation...");
let instructions = match parse(tokens) {
Ok(intermediate) => intermediate,
Err(error) => {
eprintln!("Error: {}", error);
eprintln!("error: {}", error);
eprintln!("Please fix errors before continuing.");
return;
}
Expand All @@ -54,9 +82,7 @@ fn main() {
let mut tape = vec![0u8; memory_available.into()];
let mut pointer: usize = 0;

if args.verbose {
println!("Running program...");
}
vprintln!("Running program...");
execute(&instructions, &mut tape, &mut pointer);
} // TODO : Uncomment when the 'build' subcommand is implemented.
// Some(Build { file: _, output: _ }) => {
Expand Down

0 comments on commit 054e6df

Please sign in to comment.