From 054e6df765e76eee8f541383b95d37946356bb83 Mon Sep 17 00:00:00 2001 From: Brayden Chan <72172597+megabyte6@users.noreply.github.com> Date: Fri, 10 Jan 2025 13:58:00 -0800 Subject: [PATCH] Use custom println macro instead of if-checks --- src/main.rs | 56 +++++++++++++++++++++++++++++++++++++++-------------- 1 file changed, 41 insertions(+), 15 deletions(-) diff --git a/src/main.rs b/src/main.rs index 44cf41d..e7a83ef 100644 --- a/src/main.rs +++ b/src/main.rs @@ -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; } @@ -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: _ }) => {