Sub topic 9
Spans and hygiene
This chapter assumes you can write a basic derive or function-like macro with syn and quote. You should also know what a TokenStream is. Here you learn what a span is, how spans decide which names resolve to what, and how to use them to place compiler errors.
What a span is
Every token carries a span. A span records where the token came from in the source and which scope its identifiers resolve in. Compiler errors use spans to underline code. Name resolution uses them to decide which x a given x refers to.
quote! gives every token it produces the span Span::call_site(). The tokens behave as if the user had typed them at the macro invocation. Tokens you interpolate with #var keep the span they already had, so code the user wrote keeps pointing at the user's source.
The three span flavors
| Span | Local variables and labels resolve at | Items and types resolve at | Status |
|---|---|---|---|
| `Span::call_site()` | the call site | the call site | stable |
| `Span::mixed_site()` | the macro definition | the call site | stable |
| `Span::def_site()` | the macro definition | the macro definition | unstable |
mixed_site matches the hygiene of macro_rules!. The generated code can't capture or shadow the user's local variables, and paths to types and functions still resolve where the user expects.
A collision from call-site identifiers
This macro times an expression. Its local start uses a mixed_site span, so it cannot collide with a variable of the same name in user code.
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::quote;
use syn::{parse_macro_input, Expr, Ident};
#[proc_macro]
pub fn timed(input: TokenStream) -> TokenStream {
let expr = parse_macro_input!(input as Expr);
let start = Ident::new("start", Span::mixed_site());
quote! {
{
let #start = ::std::time::Instant::now();
let value = #expr;
::std::println!("took {:?}", #start.elapsed());
value
}
}
.into()
}Now consider this call:
let start = 10;
let n = timed!(start * 2);If start were written directly inside quote!, it would have a call-site span. The user's start * 2 would then resolve to the macro's Instant, and compilation would fail on Instant * 2. With the mixed_site identifier, the user's start still means 10, and n is 20.
Pointing errors with quote_spanned!
quote_spanned! stamps every token it produces with a span you choose. The compiler underlines that span when the generated code fails to compile. This function makes a missing Debug implementation point at the field's type instead of at the whole derive:
use proc_macro2::TokenStream;
use quote::quote_spanned;
use syn::spanned::Spanned;
fn assert_debug(field: &syn::Field) -> TokenStream {
let ty = &field.ty;
quote_spanned! { ty.span() =>
const _: fn() = || {
fn needs_debug<T: ::std::fmt::Debug>() {}
needs_debug::<#ty>();
};
}
}The Spanned trait gives any syntax node a .span(). The explicit span goes before the => in quote_spanned!.
Common mistakes
- Using
call_sitefor temporary variables. Generatedletbindings can shadow user variables. Create them withIdent::new(name, Span::mixed_site()). - Using
Span::def_site(). It is unstable, so usemixed_siteon stable Rust. - Pointing every error at the macro call. Use the span of the offending node instead, as in the
quote_spanned!example. - Relying on hygiene for paths. Hygiene does not cover items and types. Write absolute paths such as
::std::fmt::Debug, because the user may have shadowedDebug.
Exercise
A derive macro generates let tmp = ...; using quote!. Why might this break a user's code, and what is the fix?
Show answer
Tokens inside quote! get Span::call_site(), so tmp resolves in the user's scope. It can shadow or capture a user variable named tmp. Create the identifier with Ident::new("tmp", Span::mixed_site()) and interpolate it with #tmp, so the local variable resolves in the macro's scope.