我的目标是编写一个简单的属性 proc 宏,可用于注释函数并打印其参数。
例子:
#[print_arguments]
fn add(a:u64, b:u64) -> u64 {
a + b
}
使用引号我可以在范围内插入标记并使用syn解析 rust 代码片段。所以我尝试了以下方法:
#[proc_macro_attribute]
pub fn print_arguments(_: TokenStream, item: TokenStream) -> TokenStream {
let fn_type = parse_macro_input!(item as ItemFn);
let signature = fn_type.sig;
let ident = signature.ident;
let arguments = signature.inputs;
let return_type = signature.output;
let mut args = arguments.iter();
let fn_arg = args.next().expect("msg");
let block = fn_type.block;
TokenStream::from(quote! {
fn #ident ( #arguments ) #return_type {
println!("enhanced function {:?}", #(#args)*); // this one seems wrong, as it would iterate over FnArg, which is an enum.
#block
}
})
}
是否有可能访问 FnArg 标识符(标识符)?