如何使用syn插入注释?

问题描述 投票:0回答:1

我有这个小片段,试图将注释附加到源文件中。


    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());
            }
            _ => {}
        }
    }

但这就是结果:

#[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 ()>,
}

我期待着

/// this is a comment
形式的评论。我做错了什么?

rust comments documentation syn
1个回答
0
投票
从某种意义上说,

///
//!
并不是真正的注释:它们是#[doc]
属性的语法糖。实际注释在解析时会被丢弃,并且不能被 
syn
 操作。

因此,您生成的代码是有效的,并将生成文档文本。只是拼写有点不同。

© www.soinside.com 2019 - 2024. All rights reserved.