Proc-macro conditional compilation

Hi,

How can I detect if the proc_macro crate is available for use? I need to implement TryFrom<proc_macro::TokenStream> only if it's available.

Regards,
Danilo

There is ::proc_macro::is_available(), although it's currently unstable.

Until then, the only available tool is the hacky approach of attempting to use the API and see if it panics… :grimacing: See how ::proc_macro2 does it:

https://github.com/alexcrichton/proc-macro2/blob/b128cd6cfd5647da1cb2f74295ea076515eb8174/src/detection.rs#L57-L63

  • As to how to convert these runtime checks into compile-time ones, the idea is that you wouldn't provide a compile-time difference: you'd always implement TryFrom<::proc_macro::TokenStream> or whatever other API, and you'd, when unavailable, let it be unimplemented!.

  • For the very case of TryFrom<TokenStream>, the function shall only be called by someone who managed to get hold of a TokenStream instance to begin with, which means proc-macro was available. So you can use ::proc_macro APIs without fear of panic!-king, since the panic would have already occurred when trying to come up with a TokenStream instance.


XY problem

I suggest you implement TryFrom<TokenStream2> "instead", or TryFrom<impl Into<TokenStream2>>, so as to only rely on TokenStream2 as far as your API is concerned, letting the job of handling ::proc_macro, when around, to ::proc_macro2, which is the very purpose of that crate, and is thus guaranteed to handle it optimally :slightly_smiling_face:

Wait, I thought it was stabilized already.

Which doesn't work with -Cpanic=abort. (globally enabled by some people, mandatory for cg_clif as it doesn't yet support unwinding)

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.