0

How can I add and use doc comments with a macro invocation?

macro_rules! foo {
(
    $(#[$outer:meta])*
    $name:ident
) => {
        pub mod $name {
            $(#[$outer])*
            pub const THE_ANSWER: i32 = 42;
        }
    }
}

/// doc for macro created module
foo!(bar);

fn main() {
    println!("{}", bar::THE_ANSWER);
}

Playground Link

I seem to be doing what's recommended by this question but I still get the warning.

warning: unused doc comment
   --> src/main.rs:13:1
   |
13 | /// doc for macro created module
   | ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ rustdoc does not generate documentation for macro invocations
   |
   = note: `#[warn(unused_doc_comments)]` on by default
   = help: to document an item produced by a macro, the macro must produce the documentation as part of its expansion
Eloff
  • 20,828
  • 17
  • 83
  • 112
  • 2
    "I seem to be doing what's recommended by" no you're not. The macro needs to capture the attribute as you are doing, but this also requires that the comment be inside of the invocation of the macro, not outside. – mcarton Aug 24 '21 at 23:20
  • 2
    Does this answer your question? [Generating documentation in macros](https://stackoverflow.com/questions/33999341/generating-documentation-in-macros) – Lauren Yim Aug 25 '21 at 00:31
  • [The duplicate applied to your example.](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=7ee9de99384a8ff9349f05db6e9cfd6e) – Jmb Aug 25 '21 at 06:45
  • 1
    @Jmb: Wouldn't it be more idiomatic to use a block for the macro invocation [like this](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=44691fde71bd0f916ec9c6922ad7e1e1)? – eggyal Aug 25 '21 at 09:22
  • @eggyal True, I read the duplicate too quickly and hadn't realized that putting a doc comment in the macro invocation instead of an explicit attribute would work – Jmb Aug 25 '21 at 10:12
  • Aha! Now I get it. Thanks mcarton, Jmb, eggyal. – Eloff Aug 25 '21 at 13:51

0 Answers0