Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Documenting a function created with a macro in Rust [duplicate]

Tags:

macros

rust

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?

like image 958
Sergey Avatar asked Dec 28 '16 12:12

Sergey


People also ask

What is the difference between macro and function Rust?

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.

Is macro_rules a macro?

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.

Can you use macros in Rust?

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.

How do macros work in Rust?

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.


1 Answers

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.

like image 64
Lukas Kalbertodt Avatar answered Sep 22 '22 10:09

Lukas Kalbertodt