Procedural macro on structs, handling generics

I have a procedural macro that can be used like:

#[derive(My_Trait)]
pub struct Foo {
  ...
}

in the procedural macro body, it uses things like

quote! {
  impl Bar_Trait for #struct_name {

  }
}

This works fine so far. Now, I need to to figure out how to make it work with generics, i.e.

#[derive(My_Trait)]
pub struct Foo<T0: ..., T1: ..., T2: ...> {

}

and generate

impl <T0: ..., T1: ..., T2: ...> Bar_Trait for Foo<T0, T1, T2, ...> {
}

The data I need is in parse_macro_input in syn - Rust and DeriveInput in syn - Rust but is a bit messy to extract. Is there a builtin for handling this common case? (I don't need 'use' the generics, I just need them on the impl ... for line).

You might be looking for Generics::split_for_impl(). For how to use it, see the derive macro example in the syn repository.

2 Likes

Quoting @LegionMammal978 's link:

let (impl_generics, ty_generics, where_clause) = generics.split_for_impl();
quote! {
    impl #impl_generics MyTrait for #name #ty_generics #where_clause {
        // ...
    }
}

is precisely what I'm looking for.

This topic was automatically closed 90 days after the last reply. We invite you to open a new topic if you have further questions or comments.