I tried to do
#![deny(missing_docs)]
in Rust. And I found that ///
comments are just ignored when a function is created with a macro like this:
/// docs
py_module_initializer!(libx, initlibx PyInit_libx |py, m| {
Ok(())
});
with:
error: missing documentation for a function
113 | py_module_initializer!(libx initlibx PyInit_libx |py, m| {
| ^
I thought a macro will just add a function definition after ///
. What is wrong here?
Another important difference between macros and functions is that you must define macros or bring them into scope before you call them in a file, as opposed to functions you can define anywhere and call anywhere.
macro_rules allows users to define syntax extension in a declarative way. We call such extensions "macros by example" or simply "macros". Each macro by example has a name, and one or more rules.
Rust has two types of macros: Declarative macros sometimes referred to as "macros by example", “ macro_rules! macros,” or just plain “macros”. Declarative macros enable you to write something similar to a match expression that operates on the Rust code you provide as arguments.
Rust has excellent support for macros. Macros enable you to write code that writes other code, which is known as metaprogramming. Macros provide functionality similar to functions but without the runtime cost. There is some compile-time cost, however, since macros are expanded during compile time.
Your doc comment refers to the macro invocation, which is useless in your case. To document the generated functions you have to write the doc comment into the macro definition or change your macro to also accept doc comments. Let's take a look at this:
#![deny(missing_docs)]
//! crate docs
macro_rules! gen_fn {
($name:ident) => {
/// generic doc comment... not very useful
pub fn $name() {}
}
}
gen_fn!(a);
gen_fn!(b);
This works, but it's not the best solution, because doc comments are the same for all generated functions. If you want to document each generated function, you have to change the macro:
macro_rules! gen_fn {
($(#[$attr:meta])* => $name:ident) => {
$(#[$attr])*
pub fn $name() {}
}
}
gen_fn!{
/// Doc comment for a
=> a
}
This works, because doc comments are converted to the #[doc(...)]
attribute internally. You can find more information about that here.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With