Cfg! in proc_macro

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.

If in some condition your proc-macro cannot be applied, then it should emit the compile_error, like this:

#[proc_macro_attribute]
pub fn my_attr(_attr: TokenStream, tokens: TokenStream) -> TokenStream {
    quote! {
        #[cfg(target_os = "wasm32")]
        fn my_func() {}
        #[cfg(not(target_os = "wasm32"))]
        compile_error!("This attribute can be used only on wasm target");
    }
}

Didn't know about this macro. Thanks @Cerber-Ursi!

Additional remark to the solution code.
For me target_os didn't work. Had to switch it to target_arch.

This topic was automatically closed 90 days after the last reply. New replies are no longer allowed.