How to get a DeriveInput from proc_macro2::TokenStream?

I want to debug my proc-macros, in order to do this, I move all the implementation into a non-proc-macro lib.

Since proc_macro::TokenStream crate cannot be used other than a proc-macro lib, I use proc_macro2::TokenStream instead. But my implementations take a DeriveInput as input, and originally I use parse_macro_input!(ts as DeriveInput); to do the conversion, but this cannot be done since the ts is a proc_macro2::TokenStream, not a proc_macro::TokenStream.

So how can I get a DeriveInput from proc_macro2::TokenStream?

There's a From impl for that conversion (as well as the opposite direction).

DeriveInput::from(ts); seems not working.

Not for DeriveInput but between proc_macro::TokenStream and proc_macro2::TokenStream. Please read the documentation of the latter.

I can't do this because I cannot use proc_macro::TokenStream, the compiler will report

procedural macro API is used outside of a procedural macro
thread 'struct_test' panicked at 'procedural macro API is used outside of a procedural macro', library/proc_macro/src/bridge/client.rs:331:17

Tricky things is that it's not a proc-macro library.

Then you can use syn::parse2::<DeriveInput>() and handle the error manually.

2 Likes

It works, thanks.

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.