Sub topic 5
Generating code with quote!
This chapter assumes you can write Rust structs, traits and generics, and that you have a proc-macro crate set up as in the earlier chapters. It also assumes you can get a DeriveInput out of syn. The quote crate covers the other half of the job: turning values you have already parsed back into tokens.
What quote! does
quote! takes Rust-like source text and produces a proc_macro2::TokenStream. Anything written as #name is replaced by the value of the local variable name. Everything else is copied into the output as tokens.
use quote::quote;
let tokens = quote! {
fn answer() -> u32 { 42 }
};
println!("{}", tokens);quote! produces proc_macro2::TokenStream, not proc_macro::TokenStream. The entry point of a macro must return the second type, so the last step is almost always .into(). The proc_macro2 type exists so your helper functions can be unit-tested outside a compiler invocation.
quote! does no checking. It only builds tokens. If the generated code is invalid Rust, the error appears later, when the compiler parses the expansion at the call site.
Interpolating values with #
#var works for any value whose type implements quote::ToTokens. The syn types such as Ident, Type, Expr, Generics and LitStr all implement it. So do references to them and the primitive types.
| Value you interpolate | Tokens produced |
|---|---|
| `Ident` | the identifier itself, `Point` |
| `syn::Type` | the type, `Vec<u8>` |
| `String` or `&str` | a string literal, `"Point"` |
| `u32` or `usize` | a suffixed literal, `1u32`, `0usize` |
| `bool` | `true` or `false` |
| `Option<T>` | the inner tokens, or nothing for `None` |
| `TokenStream` | the tokens unchanged |
Two rows cause most beginner mistakes. A String becomes a string literal, never an identifier. Integers get a type suffix, so interpolating a usize into self.#i yields self.0usize, which is not valid. For tuple struct fields, use syn::Index:
use quote::quote;
use syn::Index;
let i = Index::from(0);
let access = quote! { self.#i }; // self.0To build a new identifier, use format_ident!. It formats like format! but returns an Ident, and it takes its span from the first Ident argument, so errors usually point at the user's code.
use quote::format_ident;
let field = format_ident!("width");
let getter = format_ident!("get_{}", field); // get_widthRepetition
#( ... )* repeats its contents once per item of the variables used inside. A separator can sit between the closing parenthesis and the *.
use quote::{format_ident, quote};
let names = vec![format_ident!("a"), format_ident!("b")];
let tys = vec![quote!(u8), quote!(String)];
let params = quote! { #(#names: #tys),* };
// a: u8, b: StringThe rules:
#(#x),*puts a comma between items, and#(#x);*puts a semicolon between them.#(#x)*has no separator. Use it for items that end themselves, such as functions or statements.#(#x,)*puts a comma after every item, including the last.- Several variables in one repetition advance together, like
zip. The loop stops when any of them runs out, so lists of different lengths silently drop items. - Vectors, slices, arrays and iterators all work as repetition sources. A
HashSetdoes not. - At least one variable inside the parentheses must be repeatable. Otherwise the macro fails to compile.
Iterators are consumed
If you use an iterator in two repetitions, the second use fails with a "use of moved value" error. Collect into a Vec first when you need the data twice.
let idents: Vec<_> = fields.iter().map(|f| f.ident.clone().unwrap()).collect();
quote! {
fn names() -> &'static [&'static str] { &[#(stringify!(#idents)),*] }
fn count() -> usize { [#(stringify!(#idents)),*].len() }
}Pieces and nesting
A quote! result is itself a token stream, so you can build code in parts and interpolate the parts. Each repetition item can be a whole block of code, as long as it is a TokenStream:
let methods = fields.iter().map(|f| {
let name = f.ident.as_ref().unwrap();
quote! { pub fn #name(&self) -> bool { true } }
});
quote! {
impl Thing { #(#methods)* }
}An iterator of TokenStream values works directly in #(#methods)* because each TokenStream implements ToTokens.
You can also extend a stream by hand: out.extend(quote! { ... }). Prefer building small named fragments over one very large quote!. Each fragment is then easy to test and read.
Worked example: getters and setters
This derive generates get_x and set_x methods for every named field. It uses repetition, format_ident!, and split_for_impl for generics.
use proc_macro::TokenStream;
use quote::{format_ident, quote};
use syn::{parse_macro_input, Data, DataStruct, DeriveInput, Fields};
#[proc_macro_derive(Accessors)]
pub fn accessors(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = &input.ident;
let (ig, tg, wc) = input.generics.split_for_impl();
let fields = match &input.data {
Data::Struct(DataStruct {
fields: Fields::Named(f),
..
}) => &f.named,
_ => {
return syn::Error::new_spanned(
&input.ident,
"Accessors needs a struct with named fields",
)
.into_compile_error()
.into();
}
};
let methods = fields.iter().map(|f| {
let field = f.ident.as_ref().unwrap();
let ty = &f.ty;
let getter = format_ident!("get_{}", field);
let setter = format_ident!("set_{}", field);
quote! {
pub fn #getter(&self) -> &#ty {
&self.#field
}
pub fn #setter(&mut self, value: #ty) {
self.#field = value;
}
}
});
quote! {
impl #ig #name #tg #wc {
#(#methods)*
}
}
.into()
}Using it from another crate:
use my_macros::Accessors;
#[derive(Accessors)]
struct Point<T> {
x: T,
y: T,
}
fn main() {
let mut p = Point { x: 1, y: 2 };
p.set_x(10);
println!("{} {}", p.get_x(), p.get_y());
}The macro emits roughly this for Point<T>:
impl<T> Point<T> {
pub fn get_x(&self) -> &T { &self.x }
pub fn set_x(&mut self, value: T) { self.x = value; }
pub fn get_y(&self) -> &T { &self.y }
pub fn set_y(&mut self, value: T) { self.y = value; }
}Spans of generated tokens
Tokens you type literally inside quote! get Span::call_site(). They behave as if the user had written them at the macro invocation. Tokens you interpolate keep the span they had when syn parsed them. That is why an error in a generated &#ty can point at the user's field type.
When you want generated code to blame a particular location, use quote_spanned!:
use quote::quote_spanned;
let span = field.ty.span(); // needs `use syn::spanned::Spanned;`
let check = quote_spanned! { span =>
const _: fn() = || { fn assert_clone<T: Clone>() {} assert_clone::<#ty>(); };
};If the type is not Clone, the compiler reports the failure at the field's type. Without quote_spanned!, it would point at the whole derive attribute. The next chapters treat spans and hygiene in full.
Common errors
#self.xor#input.ident.quote!interpolates only a plain variable name.#input.identbecomes the wholeinputfollowed by.ident. Bind first:let ident = &input.ident;, then write#ident.- A
Stringwhere an identifier is needed.quote! { fn #s() {} }withs: Stringproducesfn "foo"() {}. Useformat_ident!("{}", s)orIdent::new(&s, span). - A
Vecoutside repetition.#nameswherenamesis aVec<Ident>fails with a missingToTokensimplementation. Write#(#names),*. - Reusing a moved iterator. Collect it into a
Vec, as shown above. - Missing trailing comma.
#(#x),*leaves no comma after the last item. If the surrounding syntax needs one, as in a one-element tuple(#(#x),*), write#(#x,)*. - Returning the wrong stream type. The compiler complains that
proc_macro2::TokenStreamis notproc_macro::TokenStream. Add.into().
Exercises
Exercise
A derive macro has let fields: Vec<syn::Ident>. You write quote! { fn names() -> Vec<&'static str> { vec![#(#fields),*] } } and the output contains bare identifiers, not strings. How do you produce string literals?
Show answer
Convert each ident to a string first and interpolate the strings: let names: Vec<String> = fields.iter().map(|f| f.to_string()).collect();, then vec![#(#names),*]. A String interpolates as a string literal. Alternatively write stringify!(#fields) inside the repetition.
Exercise
For struct Pair(u8, u8); you generate self.#i with let i = 0usize; and get a compile error in the expansion. Why, and what do you use instead?
Show answer
A usize interpolates as the suffixed literal 0usize, so the output is self.0usize, which is invalid. Use syn::Index::from(0), which interpolates as the plain tuple index 0.