How can I add rustdoc comments to proc macro-generated code?
Asked Answered
M

0

9

I wrote a proc-macro library to accompany a library I'm writing - they go together, with the former being used to abstract away a lot of redundant code in the latter.

I am successfully generating several structs and impls in my proc macro. I am also using cargo doc with the library, and my documentation is what I expect. However, the documentation comments I'm creating in my proc macro aren't working as expected. Some code from my proc macro looks roughly like this:

#[proc_macro_derive(MyDerive)]
pub fn derive(input: TokenStream) -> TokenStream {
    ...
    let expanded = quote! {
        ...
        impl #my_struct {
            /// This comment doesn't show up in documentation
            pub fn foo(&self, n: i32) -> bool {
               false
            }

            /// This comment DOES show up in documentation
            pub fn bar(n: i32) -> Vec<String> {
               ...
            }
        }
    }
    expanded.into()
}

When I open up the generated documentation:

  • foo itself shows up in the documentation, but its comment doesn't
  • bar and its comment are in the documentation
  • If I change the comment for bar, the comment is not updated.

This third point tells me that I probably used some cargo doc flag at some point that works correctly, but I'm now using a different set of flags that don't work with proc macros. I don't want to document all my external crate dependencies (--no-deps), but I do want to document my private items (--document-private-items). I'm therefore generating docs with cargo doc --no-deps --document-private-items. I've also tried with --release.

I assume documentation is built from the source code and not from the built .so file itself, so I haven't been doing cargo build before doing cargo doc, though I have also tried this to debug this issue. So what is the right way to make sure my proc macro-generated code's documentation gets properly generated and updated?

Mandolin answered 12/6, 2020 at 16:32 Comment(2)
Doesn't the method stated here work?Pneumococcus
If you mean using the #[doc="this is a comment"] approach instead of /// this is a comment - no, that doesn't change the resulting generated docs.Mandolin

© 2022 - 2024 — McMap. All rights reserved.