Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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.

like image 378
Timur Guvenkaya Avatar asked Sep 16 '25 18:09

Timur Guvenkaya


1 Answers

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!()`
like image 75
Chayim Friedman Avatar answered Sep 19 '25 07:09

Chayim Friedman