Search code examples
rustcommentsdocumentationsyn

How to insert doc comments using syn?


I have this little snippet that is trying to append comments to a source file.


    let mut file: File = syn::parse_str(file_content.as_str()).expect("Failed to parse Rust code");

    for item in &mut file.items {
        // Use quote! to generate a comment and append it to the item
        let mut comment: Attribute = parse_quote! {
            /// This is a generated comment.
        };

        comment.style = AttrStyle::Outer;

        match item {
            Item::Struct(ref mut s) => {
                s.attrs.push(comment.clone());
            }
            Item::Enum(ref mut e) => {
                e.attrs.push(comment.clone());
            }
            Item::Fn(ref mut f) => {
                f.attrs.push(comment.clone());
            }
            _ => {}
        }
    }

But this is the result:

#[doc = r" This is a generated comment."]
pub struct MTContainerGuardMut<'a, T> {
    data: *mut T,
    #[cfg(debug_assertions)]
    flag: &'a AtomicBool,
    #[cfg(not(debug_assertions))]
    _phantom: PhantomData<&'a ()>,
}

I was expecting a comment of the form /// this is a comment. What am I doing wrong?


Solution

  • /// and //! are, in a sense, not really comments: they are syntax sugar for the #[doc] attribute. Actual comments are discarded at parse time and cannot be manipulated by syn.

    So, your generated code is valid, and will produce documentation text. It is just spelled a little differently.