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>>));