1

I'm implementing a simple attribute proc macro that's supposed to throw a warning if an invalid option is provided as an argument to it. Assume the following code:

#[proc_macro_error::proc_macro_error]
#[proc_macro_attribute]
pub fn my_attribute_with_warning(
    args: proc_macro::TokenStream,
    in_func: proc_macro::TokenStream,
) -> proc_macro::TokenStream {
    let mut in_func_parsed = syn::parse_macro_input!(in_func as syn::ItemFn);
    let func_name = in_func_parsed.sig.ident.to_string();

    let args_parsed = syn::punctuated::Punctuated::<syn::Path, syn::Token![,]>::parse_terminated
        .parse(args)
        .unwrap();

    for a in args_parsed {
        let arg_string = a.into_token_stream().to_string();
        let arg_valid = check_validity(&arg_string);
        if !arg_valid {
            proc_macro_error::emit_warning!(
                proc_macro::Span::mixed_site(),
                format!(
                    "Invalid option '{}' provided for my_attribute_with_warning on {}",
                    arg_string, func_name, 
                )
            );
        }
    }

    proc_macro::TokenStream::from(in_func_parsed.into_token_stream())
}

What I would expect to happen is that a warning is emitted at compile time when an argument is provided that results in check_validity returning false. This is however not the case. Am I wrong in that assumption? Is there a mistake in the above code that can be fixed to achieve the desired behaviour?

Note that if proc_macro_error::emit_error is used an error is generated at compile time as expected.

abcalphabet
  • 1,158
  • 3
  • 16
  • 31
  • `proc_macro_error` documentation says that warnings are not yet available on stable - https://docs.rs/proc-macro-error/latest/proc_macro_error/#limitations. Are you using stable or nightly? – Cerberus Apr 15 '22 at 19:21
  • Ah yes that's it, I was on stable... Thank you :) – abcalphabet Apr 18 '22 at 18:03

0 Answers0