Can you pass tokens from quote! macro into other macros

I am using a macro routes_with_openapi![mycrate::func1, mycrate::func2, mycrate::func3 ]

Hypothetically, I want something like this where I join two lists of token together and pass into original macro using quote! or any other mechanism. The list of functions (which is what this macro expects) I have is long and I want to conditionally add elements.

let a = quote!(mycrate::func1, mycrate::func2);
let b = quote!(mycrate::func3);
routes_with_openapi![ #a, #b];

https://lib.rs/crates/rocket_okapi

What is the problem, what doesn't work? Are you missing the #(…)* repetition operator?

let mut args = Vec::new();
args.push(quote!(func1));

if condition {
    args.push(quote!(func2));
}

quote!{
    call_macro![#(#args,)*];
}

So, you intend to call a third-party proc-macro from within your own proc-macro. Alas, the "obvious" step of saying that you depend on their proc-macro crate to call their function implementation is not possible:

//! This, alas, doesn't work
::rocket_okapi_codegen::routes_with_openapi(
    quote!(#a, #b).into()
)

So, instead, you need to call their macro as a macro, that is, inside the emitted code:

quote!(
    ::some::path::routes_with_openapi![ #a, #b ];
)

And then remains the question of the crate setup and what ::some::path should be. I've explained those in detail in the following post:

Thanks for all the feedback! In my case I am not calling the third-party proc-macro(routes_with_openapi!) from within my own proc-macro - just from my own vanilla rust main.rs code (not in a proc-macro). I would like to provide it with a (somehow expanded) TokenStream I created before the call. The issue I am encountering is that I cannot invoke the macro twice. If I understand you correctly, I should go ahead and write my own macro like you outlined and then call the third party macro instead. But I fear I have a fundamental misunderstanding of my own problem. At runtime I need to vary the list of tokens passed to the macro - I fear I am trying to conflating compile time and runtime constructs.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.