Rust: Comments for macro expansions

Created on 19 Oct 2016  ·  3Comments  ·  Source: rust-lang/rust

macro_rules! foo_macro {
    ($name:ident) => {
        pub struct $name;
    }
}

/// Doc comment for Foo struct.
foo_macro!(Foo);

/// Doc comment for Bar struct.
foo_macro!(Bar);

In this trivial code sample the user wants to create a struct via macro expansion and write a unique comment for every different macro invokation.
This means a unique comment for struct Foo and Bar which is currently not possible in the rust compiler when enabling:

#![warn(missing_docs)]

With the following warnings:

warning: missing documentation for a struct
  --> src/activation_fn.rs:9:3
   |
9  |        pub struct $name;
   |        ^^^^^^^^^^^^^^^^^
...
14 | foo_macro!(Foo);
   | ---------------- in this macro invocation
   |
note: lint level defined here
  --> src/lib.rs:1:9
   |
1  | #![warn(missing_docs)]
   |         ^^^^^^^^^^^^

warning: missing documentation for a struct
  --> src/activation_fn.rs:9:3
   |
9  |        pub struct $name;
   |        ^^^^^^^^^^^^^^^^^
...
17 | foo_macro!(Bar);
   | ---------------- in this macro invocation
   |
note: lint level defined here
  --> src/lib.rs:1:9
   |
1  | #![warn(missing_docs)]
   |         ^^^^^^^^^^^^

While this obviously does work:

macro_rules! foo_macro {
    /// Unified comment for any macro expansion which is bad!
    ($name:ident) => {
        pub struct $name;
    }
}

foo_macro!(Foo);
foo_macro!(Bar);

Most helpful comment

The issue here does not seem to be solved. How to write doc comments for macros that start with an ident ?

All 3 comments

You could just forward all attributes (doc comments are #[doc] attributes), but since the repetition of attributes can't be followed directly by an ident, it requires changing the syntax a bit.

Example (playground)

macro_rules! foo_macro {
    ($(#[$attr:meta])* struct $name:ident) => {
        $(#[$attr])*
        pub struct $name;
    }
}

foo_macro!(
    /// Doc comment for Foo struct.
    struct Foo
);

foo_macro!(
    /// Doc comment for Bar struct.
    struct Bar
);

fn main() {
}

The user forum is a good place to discuss questions like this. https://users.rust-lang.org/

Concrete bug reports are very welcome here, but I'll close this as it has been answered and futher discussion is best on the user forum.

The issue here does not seem to be solved. How to write doc comments for macros that start with an ident ?

Was this page helpful?
0 / 5 - 0 ratings