Sub topic 8
Supporting generic types with split_for_impl
This chapter assumes you can write a basic derive macro with syn and quote, and that you know Rust generics, trait bounds, and where clauses. By the end you will be able to make a derive macro work for types such as Wrapper<T>, Ref<'a, T>, and Buf<const N: usize>.
Why a simple derive breaks on generic types
A derive macro that emits impl Trait for #name { ... } works for struct Point. It fails for this input:
struct Wrapper<T> {
value: T,
}The macro would emit impl Trait for Wrapper, and the compiler rejects it with "missing generics for struct Wrapper". A correct impl must declare the parameters after impl and repeat them after the type name:
impl<T> Trait for Wrapper<T> { /* ... */ }The two lists are not identical. The list after impl declares parameters, so it carries bounds and const types. The list after the type name only uses them. Bounds are not allowed there, so Wrapper<T: Clone> is a syntax error in that position. A where clause goes after the trait and type.
The three parts
syn::Generics has a method, split_for_impl, that produces all three pieces in the right shape:
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();Take this input type:
struct S<'a, T: Clone = i32, const N: usize = 4>
where
T: std::fmt::Debug,
{
items: &'a [T; N],
}| Piece | Used where | Contents for `S` |
|---|---|---|
| `impl_generics` | right after `impl` | `<'a, T: Clone, const N: usize>` |
| `ty_generics` | after the type name | `<'a, T, N>` |
| `where_clause` | after the type | `where T: std::fmt::Debug` |
impl_generics keeps the inline bounds. It drops the defaults (= i32, = 4), because defaults are not allowed on an impl. ty_generics keeps only the names. where_clause is an Option<&WhereClause>. When the type has no where clause it is None, and quote! emits nothing for it.
Using the three parts in a derive
The HelloMacro derive from earlier chapters already follows the pattern. The three pieces go into the quote! template in this order:
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, DeriveInput};
#[proc_macro_derive(HelloMacro)]
pub fn hello_macro_derive(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = &input.ident;
let name_str = name.to_string();
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
let expanded = quote! {
impl #impl_generics ::hello_macro::HelloMacro for #name #ty_generics #where_clause {
fn hello_macro() {
println!("Hello, Macro! My name is {}!", #name_str);
}
}
};
expanded.into()
}The path ::hello_macro::HelloMacro is absolute. The leading :: makes it resolve from the crate root, so a local module named hello_macro in the user's code cannot shadow it.
For struct Wrapper<T: Clone> where T: Send { value: T }, the macro emits:
impl<T: Clone> ::hello_macro::HelloMacro for Wrapper<T> where T: Send {
fn hello_macro() { /* ... */ }
}Lifetimes and const generics need no extra code. split_for_impl handles all three kinds of parameter.
Adding bounds for the generated code
Sometimes the generated body needs the type parameters to implement something. Suppose the macro should also call hello_macro() on every type parameter. Then the impl needs T: HelloMacro, and the user's declaration does not provide it.
Add the bound to the where clause before splitting. make_where_clause returns a mutable reference and creates an empty clause if there is none:
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, parse_quote, DeriveInput};
#[proc_macro_derive(HelloNested)]
pub fn hello_nested_derive(input: TokenStream) -> TokenStream {
let mut input = parse_macro_input!(input as DeriveInput);
let name = input.ident.clone();
let name_str = name.to_string();
let type_params: Vec<_> = input
.generics
.type_params()
.map(|p| p.ident.clone())
.collect();
let where_clause = input.generics.make_where_clause();
for param in &type_params {
where_clause
.predicates
.push(parse_quote!(#param: ::hello_macro::HelloMacro));
}
let (impl_generics, ty_generics, where_clause) = input.generics.split_for_impl();
let expanded = quote! {
impl #impl_generics ::hello_macro::HelloMacro for #name #ty_generics #where_clause {
fn hello_macro() {
println!("Hello, Macro! My name is {}!", #name_str);
#( <#type_params as ::hello_macro::HelloMacro>::hello_macro(); )*
}
}
};
expanded.into()
}The code clones ident and collects the parameter names before it borrows generics mutably. Otherwise the borrow checker would reject the mutation, because name would still borrow input.
Here is a user crate that depends on the trait crate and the macro crate:
use hello_macro::HelloMacro;
use hello_macro_derive::HelloNested;
struct Leaf;
impl HelloMacro for Leaf {
fn hello_macro() {
println!("Hello from Leaf");
}
}
#[derive(HelloNested)]
#[allow(dead_code)]
struct Pair<A, B> {
a: A,
b: B,
}
fn main() {
Pair::<Leaf, Leaf>::hello_macro();
}It prints:
Hello, Macro! My name is Pair!
Hello from Leaf
Hello from LeafLike the standard library's #[derive(Clone)], this approach bounds every type parameter. That can be stricter than necessary. If T appears only inside PhantomData<T>, users still have to satisfy T: HelloMacro. Production crates such as serde analyze the fields and bound only the types that need it. Start with the simple approach, and refine it when a real user hits the problem.
Adding a parameter that the type does not have
Some traits need a parameter that the user's type lacks. A Decode<'de> trait is a common example. Put the extra parameter in impl_generics only. Split a modified copy for that piece, and split the original for the other two:
use proc_macro2::TokenStream;
use quote::quote;
use syn::{parse_quote, DeriveInput, GenericParam};
fn expand_decode(input: &DeriveInput) -> TokenStream {
let name = &input.ident;
let mut extended = input.generics.clone();
let de: GenericParam = parse_quote!('de);
extended.params.insert(0, de);
let (impl_generics, _, _) = extended.split_for_impl();
let (_, ty_generics, where_clause) = input.generics.split_for_impl();
quote! {
impl #impl_generics ::my_crate::Decode<'de> for #name #ty_generics #where_clause {
fn decode() {}
}
}
}Insert at index 0, not at the end. Rust requires lifetime parameters to come before type and const parameters, so pushing 'de to the end of <T> would produce the invalid impl<T, 'de>. The type uses ty_generics from the original Generics, so 'de does not leak into #name #ty_generics.
Common mistakes
- Interpolating
#genericsdirectly.GenericsimplementsToTokens, but it prints defaults and omits thewhereclause. It also cannot serve both positions, because the type position must not carry bounds. - Hand-writing
impl<T>. This works only for types with exactly one unbounded type parameter. - Splitting before mutating.
split_for_implborrowsGenerics. Add bounds first, then split. - Dropping the where clause. Leaving
#where_clauseout of the template compiles for simple types and breaks the first type that has awhereclause. - Forgetting
::on trait paths. A relative path resolves differently in each caller's module. - Turbofish expressions. To name the type in expression position, such as
Name::<T>::new(), usety_generics.as_turbofish(). Plain#ty_genericsthere is parsed as a comparison.
Exercise
A derive generates impl #impl_generics Trait for #name #ty_generics #where_clause and is applied to struct Buf<T: Copy, const N: usize> where T: Default { data: [T; N] }. Write the three tokens produced for implgenerics, tygenerics, and where_clause. Then say which of the three is an Option and what quote! emits when it is None.
Show answer
implgenerics is <T: Copy, const N: usize>. tygenerics is <T, N>. where_clause is where T: Default. The where clause is the Option<&WhereClause>. When it is None, quote! emits no tokens, so the impl header simply ends after the type.
Exercise
Your derive adds 'de to impl_generics for a type declared as struct Msg<T>. You write extended.params.push(parse_quote!('de)) and get a syntax error in the expanded code. What is wrong, and how do you fix it?
Show answer
push appends the lifetime after T, producing impl<T, 'de>, and Rust requires lifetime parameters before type and const parameters. Insert it at the front with extended.params.insert(0, de), which produces impl<'de, T>.