Is there a way to use cfg! functionality in proc_macro attribute when it's been applied to the code.
My idea is to generate different code depending on target os (or some feature flag):
#[proc_macro_attribute]
pub fn my_attr(_attr: TokenStream, tokens: TokenStream) -> TokenStream {
if cfg!(target_os = "wasm32") {
handle_wasm(tokens);
} else {
handle_default(tokens);
}
}
This doesn't work because compiler resolves cfg! when it compiles proc_macro itself and not when attribute applies to the real code.
I know I can do something like this and it will work:
#[proc_macro_attribute]
pub fn my_attr(_attr: TokenStream, tokens: TokenStream) -> TokenStream {
quote! {
#[cfg(not(target_os = "wasm32"))]
fn my_func() {}
#[cfg(target_os = "wasm32")]
fn my_func() {}
}
}
but my idea is to prevent user from using this attribute on non allowed targets:
#[proc_macro_attribute]
pub fn my_attr(_attr: TokenStream, tokens: TokenStream) -> TokenStream {
if cfg!(target_os = "wasm32") {
handle_wasm(tokens);
} else {
panic!("Attrubute can be used only on wasm target.");
}
}
While it's not a critical problem for me I still would like to know if it's possible to implement something like this.
Thanks in advance.