1

My goal is to write a simple attribute proc macro, that can be used to annotate a function and print its arguments.

example:

#[print_arguments]
fn add(a:u64, b:u64) -> u64 {
   a + b
}

Using quote i can interpolate tokens in scope and with syn parse the rust code fragement. So I tried the following:

#[proc_macro_attribute]
pub fn print_arguments(_: TokenStream, item: TokenStream) -> TokenStream {
    let fn_type = parse_macro_input!(item as ItemFn);
    let signature = fn_type.sig;
    let ident = signature.ident;
    let arguments = signature.inputs;
    let return_type = signature.output;

    let mut args = arguments.iter();
    let fn_arg = args.next().expect("msg");

    let block = fn_type.block;

    TokenStream::from(quote! {
        fn #ident ( #arguments ) #return_type {
            println!("enhanced function {:?}", #(#args)*); // this one seems wrong, as it would iterate over FnArg, which is an enum. 
            #block
        }
    })
}

Is there any possibility to access the FnArg ident(ifiers)?

tungsten
  • 63
  • 1
  • 6
  • 1
    Bear in mind that function arguments do not necessarily have idents, but rather are patterns against which the incoming type is matched: one could, for example, have `fn add(&mut self, (_, SomeStruct { field: mut ref binding, .. }, _, None): TupleType)`... how exactly will you handle that? Do you just want to bail out with an error if the pattern is anything but a simple ident? – eggyal Mar 11 '21 at 15:32
  • Basically yes. The main intention is get acquainted with proc_macros, and start with some "simple" examples to get a grasp on how they work. – tungsten Mar 11 '21 at 15:54
  • 1
    So then you need to map the iterator from its `FnArg` enums to the expected type: see lines 14-20 in [this playground](https://play.rust-lang.org/?version=stable&mode=debug&edition=2018&gist=d31c67133453b749a5c1094c1e8f334a) (I had to change the function signature as I don't think the playground can compile proc macros). – eggyal Mar 11 '21 at 16:20
  • Ha! Nice! Thanks for you effort, but there seem to be a problem with the modified signature. Will look it up ( problem: applying the macro to a function won't allow more than one argument ) – tungsten Mar 11 '21 at 17:06

0 Answers0