Macro To Substitute Code Comments

I had an interesting idea earlier for a compiler plugin/macro that would convert my code comments to log::trace! statements. That way I could add extra trace logs without having to change my code and my general readability comments could help debugging as well, though I might want to do something like //- log message instead of just using //.

Anyway, does anybody know a way to write a macro or plugin that would be able to do that across my entire crate?

1 Like

I've never tried this, but as far as I know, the compiler converts documentation comments into #[doc = "…"] attributes. If you were to write an attribute-like procedural macro, you could capture this doc attribute and insert a log::trace!() call right at the beginning of the function body, then just emit the rest of the function body as-is.

3 Likes

To illustrate @H2CO3's point: Rust Playground

macro_rules! trace {(
    #[doc = $expr:expr]
) => (
    eprintln!("{}", $expr);
)}

fn main ()
{
    trace! {
        /// Hello, World!
    }
}

2 Likes

Cool. Am I correct in understanding that you would need a nightly feature to apply a proc macro to an entire crate? An attribute macro on the crate would be the way to do that right?

Last time I tried, the proc-macro only got dummy input. That is,

#[my_proc_macro]
mod foo;

leads to my_proc_macro(_, input: TokenStream) receiving these three "dummy" tokens: input.to_string() == "mod foo ;"

Crate global attribute macros are a feature I would like to hack my way into, hopefully soon, but not right now anyways (it will require a build.rs script that starts by bundling the whole crate into a single one file source code, and then have the proc macro work on that file).

1 Like

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.