rustrust-macros

Parsing Attribute Macro Arguments in Rust


I'm writing an attribute macro and trying to parse arguments passed there.

Like: #[macro(Arg1, Arg2)]

The issue is that I cannot find the right structure to parse it as. I tried parsing it as Meta and MetaList but none of them seem to work.

pub fn some_macro(args: TokenStream, item: TokenStream) -> TokenStream {
let args_parsed = parse_macro_input!(args as MetaList);

////////

let args_parsed = parse_macro_input!(args as Meta);

}

When I parse it as MetaList I get: "unexpected end of input, expected parentheses" Error.


Solution

  • I assume you use the syn crate.


    Proc macros don't get their arguments as a meta, but after stripping the #[name(...)]. That is, args will contain Arg1, Arg2 and not #[macro(Arg1, Arg2)] which is what Meta (and MetaList) expect.

    What you want is Punctuated:

    // Note that I put `syn::Path` but you can put whatever you want to parse between the commas.
    // For example `syn::NestedMeta` if you want the full attribute syntax.
    let args_parsed = syn::punctuated::Punctuated::<syn::Path, syn::Token![,]>::parse_terminated
        .parse(args)
        .unwrap(); // Better to turn it into a `compile_error!()`