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, lifetimes, and where clauses. You will fix a derive macro that breaks on generic types.
The problem with a naive impl
Here is a first attempt at a derive macro. It works only for types with no generics:
let expanded = quote! {
impl ::hello_macro::HelloMacro for #name {
fn hello_macro() {
println!("Hello, Macro! My name is {}!", #name_str);
}
}
};Apply it to struct Wrapper<T> { value: T }. The macro emits impl HelloMacro for Wrapper, and the compiler rejects it because Wrapper is missing its generic argument.
A correct impl must repeat the type's generics in two places. The impl header declares them with their bounds. The type position uses them as plain arguments. For this type:
struct Wrapper<'a, T: Clone, const N: usize>
where
T: Send,
{
value: &'a [T; N],
}the impl should look like this:
impl<'a, T: Clone, const N: usize> Trait for Wrapper<'a, T, N>
where
T: Send,
{ /* ... */ }Splitting the generics
Generics::split_for_impl returns three values that map onto those positions.
| Value | Renders as | Used in |
|---|---|---|
| `impl_generics` | `<'a, T: Clone, const N: usize>` | right after `impl` |
| `ty_generics` | `<'a, T, N>` | after the type name |
| `where_clause` | `where T: Send` (an `Option`) | before the opening brace |
All three implement ToTokens, so you can interpolate them directly with #. An absent where clause renders as nothing.
The generic-aware derive
This is the derive from the previous chapters, now using all three values:
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()
}Now a user can write the following, and the impl compiles:
use hello_macro::HelloMacro;
use hello_macro_derive::HelloMacro;
#[derive(HelloMacro)]
struct Wrapper<T: Clone>
where
T: Send,
{
value: T,
}
fn main() {
<Wrapper<i32> as HelloMacro>::hello_macro();
}Adding bounds for type parameters
Some derives need every type parameter to implement the trait being derived. #[derive(Debug)] does this: Wrapper<T> is Debug only when T is. Modify a cloned Generics value before splitting it:
use syn::{parse_quote, GenericParam, Generics};
fn add_trait_bounds(mut generics: Generics) -> Generics {
for param in &mut generics.params {
if let GenericParam::Type(type_param) = param {
type_param.bounds.push(parse_quote!(::std::fmt::Debug));
}
}
generics
}Call it as let generics = add_trait_bounds(input.generics.clone());, then generics.split_for_impl(). The returned values borrow from generics, so keep that variable alive until you finish the quote! call.
Exercise
A derive macro generates impl #name #ty_generics #where_clause { ... } and fails on struct Pair<T: Copy>(T, T); with an error about an undeclared type T. What is missing, and what should the impl header look like?
Show answer
The impl header doesn't declare T. It needs #impl_generics after impl, so the output is impl #impl_generics #name #ty_generics #where_clause { ... }. For Pair<T: Copy> this expands to impl<T: Copy> Pair<T> { ... }.