Sub topic 9
Spans and hygiene
This chapter covers what a span is, where the spans in generated code come from, and how they control two things. The first is which source location the compiler blames in an error. The second is which variable an identifier refers to (hygiene). It assumes you have read the chapters on TokenStream, syn parsing, quote!, and error reporting with syn::Error.
What a span is
Every token carries a Span. A span records:
- A source location. This is a range of text in a file, which the compiler uses for error messages and which editors use for features such as go-to-definition.
- A syntax context. The compiler uses this to decide how names resolve. Two identifiers both spelled
tmpare different names if their syntax contexts differ.
You rarely build a span from scratch. You copy one from a token you received, or you pick one of the constructors on Span. That choice decides how the generated code behaves.
Where spans come from
| Source | Location points to | Local variables resolve |
|---|---|---|
| Tokens taken from the macro input | The user's original code | At the user's code |
| `Span::call_site()` | The macro invocation, such as `#[derive(...)]` or `name!(...)` | As if the user typed the tokens |
| `Span::mixed_site()` | The macro invocation | In the macro's own scope, so the names cannot collide with the user's |
| `Span::def_site()` | The macro definition | Nightly only, so not usable on stable Rust |
The quote! macro gives every token you write literally the span Span::call_site(). Tokens you interpolate with #name keep the span they already had. That rule explains most span behavior you will see.
Spans decide where errors point
When the compiler rejects generated code, it underlines the span of the offending token. If all the generated code carries the call-site span, the user sees an error on the whole #[derive(...)] line, with no hint about which field or type caused it.
You can give generated tokens the span of the user's code with quote_spanned!. It takes a span, then =>, then the tokens. Every literal token inside gets that span.
This derive checks that every field of a struct is Sync:
use proc_macro::TokenStream;
use quote::{quote, quote_spanned};
use syn::spanned::Spanned;
use syn::{parse_macro_input, Data, DeriveInput};
#[proc_macro_derive(AssertSync)]
pub fn assert_sync(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let data = match &input.data {
Data::Struct(data) => data,
_ => {
return syn::Error::new_spanned(
&input.ident,
"AssertSync only supports structs",
)
.into_compile_error()
.into();
}
};
let checks = data.fields.iter().map(|field| {
let ty = &field.ty;
quote_spanned! {ty.span()=>
require_sync::<#ty>();
}
});
quote! {
const _: fn() = || {
fn require_sync<T: ?Sized + Sync>() {}
#(#checks)*
};
}
.into()
}Suppose a user writes this:
use std::rc::Rc;
#[derive(AssertSync)]
struct Shared {
id: u32,
handle: Rc<String>,
}The compiler reports that Rc<String> cannot be shared between threads safely. It underlines the type Rc<String> in the handle field. Without quote_spanned!, it would underline the AssertSync name in the derive attribute.
The Spanned trait from syn::spanned gives every syntax node a .span() method. This is the same mechanism Error::new_spanned uses, so the advice from the error-reporting chapter applies here too: build errors from the node that is actually at fault.
The generated function require_sync takes the span of each field type. That is harmless, because function names are items, and items are not hygienic. The next section covers what is hygienic.
Spans on generated identifiers
When you invent an identifier from a user's name, it should keep a span tied to that name. This makes errors point at the right place, and it lets editors link the generated item back to the field:
use quote::format_ident;
let getter = format_ident!("get_{}", field_name);
let other = format_ident!("set_{}", field_name, span = field_name.span());By default, format_ident! takes the span from the first Ident among the interpolated values. Pass span = ... to choose one yourself.
Hygiene: when generated names collide
A proc macro that emits tokens with call_site spans behaves as if the user had typed those tokens by hand. For local variables, that causes name collisions.
This macro adds 10 to an expression, using a temporary variable:
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, Expr};
#[proc_macro]
pub fn add_ten_unhygienic(input: TokenStream) -> TokenStream {
let expr = parse_macro_input!(input as Expr);
quote! {{
let tmp = 10;
#expr + tmp
}}
.into()
}Now call it where the user already has a variable named tmp:
let tmp = 1;
let result = add_ten_unhygienic!(tmp);The expansion is { let tmp = 10; tmp + tmp }. The user's tmp is shadowed by the macro's let, so result is 20 instead of 11. The compiler gives no warning, because the code is valid.
The fix is to give the temporary an identifier with the mixed_site span:
use proc_macro::TokenStream;
use proc_macro2::Span;
use quote::quote;
use syn::{parse_macro_input, Expr, Ident};
#[proc_macro]
pub fn add_ten(input: TokenStream) -> TokenStream {
let expr = parse_macro_input!(input as Expr);
let tmp = Ident::new("tmp", Span::mixed_site());
quote! {{
let #tmp = 10;
#expr + #tmp
}}
.into()
}Both uses of #tmp carry the same mixed_site context, so the macro's let and the macro's use of tmp match each other. The user's tmp, inside #expr, has a different context, so it is a different variable. add_ten!(tmp) with let tmp = 1; now gives 11.
mixed_site matches the hygiene of macro_rules!. Local variables and labels use the macro's own scope. Everything else, such as types, functions, modules, and traits, resolves as if written at the call site.
When to use which span
- Use
call_site(the default inquote!) for items the user is meant to see and call, such as a generatedimpl, a method, or a struct. Their names must resolve normally. - Use
mixed_sitefor local variables and labels that only the macro uses, such as temporaries, loop counters, and closure parameters. - Use the span of an input token when the generated code stands in for that token, so errors and editor features point back at it.
Passing user tokens through
The tokens you interpolate from the input keep their original spans and contexts. This means a user expression such as #expr in add_ten still sees the variables of the user's scope. That is the behavior you want. A macro that wraps user code should not change what the user's names mean.
A common mistake is to rebuild an identifier from its string:
let name = Ident::new(&user_ident.to_string(), Span::call_site());This replaces the user's span with the call-site span. Errors then point at the macro invocation, and in some cases the identifier resolves differently from the original. Reuse the original Ident, or build a new one with user_ident.span().
Common problems
- Error points at the whole derive or macro call. The generated tokens have the
call_sitespan. Usequote_spanned!with the span of the relevant input node. - A user variable is shadowed or captured. A generated local variable uses
call_site. Create it withIdent::new(..., Span::mixed_site()). - An identifier built from a string no longer resolves. You gave it a different syntax context than the original. Use the original identifier's span.
- A generated type name resolves to the wrong type. Hygiene does not cover paths. Use absolute paths.
Exercise
A function-like macro expands to { let i = 0; #body; i }, where #body is user code. The user calls it as let i = 5; counted!(println!("{}", i)). What does the macro print and return, and how do you change the macro so it prints the user's i?
Show answer
With the default call_site span for i, the macro's let i = 0; shadows the user's variable, so println! prints 0. Create the identifier with let i = Ident::new("i", Span::mixed_site()); and interpolate it as #i in both places in the expansion. The macro's i then has a different syntax context from the user's i, so the user's println! prints 5 and the block still returns the macro's own counter.
Exercise
Why does the AssertSync derive use quote_spanned! {ty.span()=> ...} for the checks, but plain quote! for the surrounding const _: fn() = ... wrapper?
Show answer
The error should point at the field type that is not Sync, so the check that mentions the type carries that type's span. The wrapper does not depend on any one type and has no useful location, so the default call-site span is fine.