我已经实现了以下 proc_macro
builtin_method!(hello_world(a, b, c) {
println!("{} {} {}", a, b, c);
}
并且应该生成
pub fn hello_world(args: Vec<String>) {
let a = args.get(0).unwrap();
let b = args.get(1).unwrap();
let c = args.get(2).unwrap();
println!("{} {} {}", a, b, c);
}
这是我当前的代码。
use proc_macro::TokenStream;
use quote::quote;
use syn;
struct BuiltinDef {
function: syn::Ident,
arguments: Vec<syn::Ident>,
body: syn::Block,
}
impl syn::parse::Parse for BuiltinDef {
fn parse(stream: syn::parse::ParseStream) -> syn::Result<Self> {
let function: syn::Ident = stream.parse()?;
let content;
let _: syn::token::Paren = syn::parenthesized!(content in stream);
let arguments: syn::punctuated::Punctuated<syn::Ident, syn::Token![,]> =
content.parse_terminated(syn::Ident::parse)?;
let body: syn::Block = stream.parse()?;
Ok(BuiltinDef {
function,
arguments: arguments.into_iter().collect(),
body,
})
}
}
#[proc_macro]
pub fn builtin_method(input: TokenStream) -> TokenStream {
let def = syn::parse_macro_input!(input as BuiltinDef);
let function = def.function;
let arguments = def.arguments;
let body = def.body;
let gen = quote! {
pub fn #function(args: Vec<String>) {
let mut _i = 0;
#(
let mut #arguments = args.get(_i).unwrap().clone();
_i += 1;
)*
#body
}
};
TokenStream::from(gen)
}
在变量插值中,我需要某种枚举变量计数。根据文档,没有这种方法。
我怎样才能更好地实现这一点而不是计数_i
?
let mut _i = 0;
#(
let mut #arguments = args.get(_i).unwrap().clone();
_i += 1;
)*