Search code examples
rustrust-macros

Creating a Custom Colored dbg! Macro In Rust


I'd like to create a custom macro similar to the standard dbg! macro, but with the option to use colors via the colored crate. dbg! usually prints something with the format of

[path_to_file:line_number] "symbol name" = "symbol value"
//[src/gallery/image_slot.rs:231] "my_integer_value_of_12" = "12"
  1. How do I access the path/line number [path_to_file:line_number] so I can print it?
  2. How do I access the symbol name of a variable? (i.e. print my_var given my_var = 12)

Solution

    1. Use the file!, line!, and column! macros.
    2. Use the stringify! macro.

    If you go to the docs of the dbg! macro, you can click [src], which shows the implementation of dbg!, which is as follows:

    macro_rules! dbg {
        () => {
            $crate::eprintln!("[{}:{}]", $crate::file!(), $crate::line!());
        };
        ($val:expr $(,)?) => {
            // Use of `match` here is intentional because it affects the lifetimes
            // of temporaries - https://stackoverflow.com/a/48732525/1063961
            match $val {
                tmp => {
                    $crate::eprintln!("[{}:{}] {} = {:#?}",
                        $crate::file!(), $crate::line!(), $crate::stringify!($val), &tmp);
                    tmp
                }
            }
        };
        ($($val:expr),+ $(,)?) => {
            ($($crate::dbg!($val)),+,)
        };
    }
    

    Using that, we can easily create a similar colored_dbg! macro, with the colored crate as you suggested.

    (I just picked random colors, for a simple example)

    // colored = "2.0"
    use colored::Colorize;
    
    macro_rules! colored_dbg {
        () => {
            eprintln!("{}", format!("[{}:{}]", file!(), line!()).green());
        };
        ($val:expr $(,)?) => {
            match $val {
                tmp => {
                    eprintln!("{} {} = {}",
                        format!("[{}:{}]", file!(), line!()).green(),
                        stringify!($val).red(),
                        format!("{:#?}", &tmp).blue(),
                    );
                    tmp
                }
            }
        };
        ($($val:expr),+ $(,)?) => {
            ($(colored_dbg!($val)),+,)
        };
    }
    

    You'd use it just like how you'd be able to use dbg!:

    fn main() {
        let my_var = 12;
        colored_dbg!(&my_var);
    
        let v = vec!["foo", "bar", "baz"];
        let v = colored_dbg!(v);
    }
    

    Which outputs the following:

    screenshot