Parsing a variable number of items in a proc macro?

I'm trying to do some procedural macro stuff that involves parsing a variable number of items and doing something based on the group as a whole. Something like this:

my_macro! {
  struct A;
  struct B;
  struct C;
}

I can't figure out the right iteration or syn::parse call. If I try to parse_macro_input!(input as Item) it tries to parse the whole block as a single item. How can I incrementally pull out items one at a time?

Ah, I think parse_macro_input!(input as File) is what I want.

Would something like this work?

struct StructList {
    structs: Vec<Ident>
}

impl Parse for StructList {
    fn parse(input: ParseStream) -> Result<Self> {
        let mut idents = Vec::new();
        
        while input.peek(Token![struct]) {
            input.parse::<Token![struct]>()?;
            let ident = input.parse::<Ident>()?;
            input.parse::<Token![;]>()?;

            idents.push(ident);
        }
        
        StructList { idents }
    }
}
2 Likes

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