4

I am in the process of writing a proc-macro attribute which will be placed on structs and enums, but I am running into an issue with generics. I derive functionality for each field separately, so I need to get the generics required for a single Field from the parent type's Generics. Is there a good way to do this?

use syn::{Generics, Field};

fn generics_for_field(parent_generics: &Generics, field: &Field) -> Generics {
    // How do I extract only the generics used by field.ty?
}

For example, if I had some struct that looked like this:

struct FooIter<'abc, A, B: Bar, C: Iterator<Item=A>> {
    foo_initial: A,
    foo_count: i32,
    unrelated: Vec<B::A>,
    some_ref: PhantomData<&'abc mut C>,
}

I could somehow convert the parent generics <'abc, A, B: Bar, C: Iterator<Item=A>>, to the minimum generics required for each field.

assert_eq!(generics_for_field(generics_for_field, &fields[0]), parse_quote!(<A>));
assert_eq!(generics_for_field(generics_for_field, &fields[1]), parse_quote!(<>));
assert_eq!(generics_for_field(generics_for_field, &fields[2]), parse_quote!(<B: Bar>));
assert_eq!(generics_for_field(generics_for_field, &fields[3]), parse_quote!(<'abc, A, C: Iterator<Item=A>>));
Locke
  • 7,626
  • 2
  • 21
  • 41
  • 1
    What did you try? – Peter Hall Apr 11 '23 at 03:11
  • @PeterHall I am not asking because I am unable to implement the function myself (with enough time). I am asking because the implementation seems non-trivial and I find it unlikely that I am the first person to encounter this problem. I have been looking through documentation for a while now, but I have yet to find a solution (though there was a related question on the Rust forums). Rather than spend hours putting together a naïve implementation, I suspect that there is already a community best practice for this sort of situation that I am currently unaware of. – Locke Apr 11 '23 at 04:56
  • I asked what you tried because I found your question unclear and I thought that might clarify what you are actually asking. – Peter Hall Apr 11 '23 at 13:40
  • @PeterHall Could you clarify what parts you found unclear so I can improve the question? – Locke Apr 11 '23 at 20:16

0 Answers0