Capturing doc comments in declarative macros
Sometimes, when writing declarative macros in Rust, we may want to capture not only the code itself, but also doc comments for that code. Intuitively one could write something like:
Unfortunately, it’s not gonna work, and the compiler will promptly warn us:
As rustc suggests, the solution is to move the doc comment into macro body and capture it. This will work because doc comments desugar into attributes. So the example above can be rewritten as:
And, as you may have guessed, it is possible to match against attributes in macros. In fact, many libraries leverage that fact, e.g. quick_error or bitflags. With that in mind, we can rewrite our macro to capture doc comments.
To match against the attributes, we can use the meta
metavariable:
Now the SomeType
struct will have the doc comment we defined in macro body.