在synv1中,有NestedMeta一个对于解析嵌套元非常方便的功能。但自synv2 以来,它已被删除。
例如,
trait Hello {
fn hello();
}
#[derive(Hello)]
#[hello("world1", "world2")]
struct A;
fn main() {
A::hello();
}
Run Code Online (Sandbox Code Playgroud)
我希望上面的代码打印Hello world1, world2!在屏幕上。我的 proc-macro 可以使用 v1 来实现,syn如下所示
use proc_macro::TokenStream;
use quote::quote;
use syn::{DeriveInput, Meta};
#[proc_macro_derive(Hello, attributes(hello))]
pub fn hello_derive(input: TokenStream) -> TokenStream {
let ast: DeriveInput = syn::parse(input).unwrap();
let name = &ast.ident;
let mut target: Vec<String> = vec![];
for attr in ast.attrs {
if let Some(attr_meta_name) = attr.path.get_ident() {
if attr_meta_name …Run Code Online (Sandbox Code Playgroud) 我有这个小片段试图将注释附加到源文件中。
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());
}
_ => {}
}
}
Run Code Online (Sandbox Code Playgroud)
但这是结果:
#[doc = r" …Run Code Online (Sandbox Code Playgroud)