Proc macros -- getting the contents of a function

Hello! I want to write a macro that acts on a function and produces a new function that performs the same operations as the original function twice.
I am trying to write an attribute macro. As I thought it was better suited for the task.

#[double]
fn print_hello() {
    println!("hello");
}

I want this to produce a new function print_hello_double (for example)

fn print_hello_double() {
    println!("hello");
    println!("hello");
}

I am using syn and quote crates. I am able to get the parsed version of the original function's contents using the syn crate. syn::Block.
But I am not able to understand how to use this to get the contents inside the new function produced (using quote! macro)

I tried to just include the parsed statements inside the quote! macro

quote! {
    // ....
    #stmts // stmts is the syn::Block instance obtained   
   // ....
}

But I get the error saying that this doesn't implement the ToTokens trait from quote crate.

the trait bound std::vec::Vec<syn::stmt::Stmt>: quote::to_tokens::ToTokens is not satisfied
required by `quote::to_tokens::ToTokens::to_tokens

Due to the error, I presume that stmts is not syn::Block, but the vector of syn::Stmt extracted from the block. For this case, quote has the separate syntax:

quote! {
    // ....
    #(#stmts)*
   // ....
}
2 Likes

Oh thanks! I failed to notice that it was a vector (mainly because I am trying to debug by using println! within the macro and my function had only one statement). This solved my problem. Thanks, once again

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.