Search code examples
rustrust-proc-macros

Converting type inside quote! gives trait errors


I get this error:

the trait quote::to_tokens::ToTokens is not implemented for proc_macro::Ident

when I try to run this code:

#[proc_macro_hack]
pub fn between(input: TokenStream) -> TokenStream {
    let idents = input
        .into_iter()
        .map(|i| match i {
            TokenTree::Ident(b) => {
                b
            },
            _ => panic!()
        })
        .collect::<Vec<_>>();

    let new_token_stream = quote! {
        (#(#idents),*)
    };

    new_token_stream.into()
}

This is how I want to use it:

fn main() {
    let a = 1;
    let b = 2;

    // Expand to (a, b);
    between!(a, b);
}

I also have a small project which holds above code: https://bitbucket.org/JoshSinne/pm/src/master/. Why can't I transform a Ident inside tokens? I tried using parse, into but that didn't worked out for me. Thanks!


Solution

  • syn and quote are built against the alternative implementation of proc_macro, namely proc_macro2. If you want to use them, you should first convert your proc_macro::TokenStream into proc_macro2::TokenStream, make any operations necessary, and at the end convert back. Both these conversion can be made using From/Into, since they are implemented in both directions.