A Rust derive's error about one field points at #[derive(Defaults)] instead of the field; how do syn::Error spans and quote_spanned! fix that?
answer
- every token carries a span
- quote! tokens get call_site
- interpolated tokens keep theirs
- new_spanned for your own checks
- quote_spanned! for generated code
basics
~20 sTokens written inside quote! get Span::call_site(), the derive invocation, so rustc blames #[derive(...)]. Report your own checks with syn::Error::new_spanned(node, msg).to_compile_error(), and wrap per-field code in quote_spanned!{field.ty.span()=> ...} so rustc's own errors land on the field.
solid answer
~40 sEvery token has a span, and rustc reports an error at the span of the tokens involved. `quote!` gives every token you write literally `Span::call_site()`, which for a derive is the `#[derive(...)]`; only interpolated tokens such as `#ty` keep the span of the user's code. So `#field: ::core::default::Default::default()` for a `Pool` field without `Default` yields E0277 underlining `Defaults` in the derive. Two fixes, one per error source. For the derive's own validation, return `syn::Error::new_spanned(&field.ty, "...").to_compile_error()`, or `syn::Error::new(span, ...)`, instead of panicking. For errors rustc finds in generated code, emit that code with `quote_spanned!{f.ty.span()=> ...}` so its tokens carry the field type's span. Use `Error::combine` to report several fields at once.
code
rust · 29 linesuse proc_macro::TokenStream;
use quote::{quote, quote_spanned};
use syn::{parse_macro_input, spanned::Spanned, Data, DeriveInput};
#[proc_macro_derive(Defaults)]
pub fn derive_defaults(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = &input.ident;
let Data::Struct(data) = &input.data else { return TokenStream::new() };
let inits = data.fields.iter().map(|f| {
let field = &f.ident;
// every token written here gets Span::call_site(): the #[derive(...)]
quote! { #field: ::core::default::Default::default() }
});
quote! { impl #name { pub fn defaults() -> Self { #name { #( #inits, )* } } } }.into()
}
#[proc_macro_derive(SpannedDefaults)]
pub fn derive_spanned_defaults(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
let name = &input.ident;
let Data::Struct(data) = &input.data else { return TokenStream::new() };
let inits = data.fields.iter().map(|f| {
let field = &f.ident;
// the tokens written here borrow the span of the field's type
quote_spanned! {f.ty.span()=> #field: ::core::default::Default::default() }
});
quote! { impl #name { pub fn defaults() -> Self { #name { #( #inits, )* } } } }.into()
}go deeper
Know that a derive should report bad input as a compile error pointing at the code at fault, not crash.
Explain spans, why quote! tokens point at the derive, and how syn::Error::new_spanned with to_compile_error underlines a specific field.
Separate the derive's own validation errors from rustc's errors in generated code, fix the latter with quote_spanned!, and combine errors so every bad field shows at once.
Judge a third-party derive partly by its errors: a derive that panics or blames itself costs every team using it time on every mistake.
## Spans decide where an error points Every token in a `TokenStream` carries a **span**: an opaque reference to a range of source code. rustc uses spans to underline the code an error is about. A token that came from the user's file keeps the user's location; a token a macro made up needs a span assigned to it, and that choice decides what the user sees. The quote crate's rule, from its documentation: - **interpolated tokens** (`#ty`, `#field`) keep the span their `ToTokens` implementation gives them, normally where the user wrote them; - **tokens written inside `quote!`** get `Span::call_site()`, the location of the macro invocation, which for a derive is the derive name inside `#[derive(...)]`; - **tokens written inside `quote_spanned!{span=> ...}`** get the span you pass. ## Two sources of errors | Error source | Example | Right tool | |---|---|---| | The derive's own checks | a tuple struct, an unknown helper option, an unsupported field type | return a `syn::Error` built with `new_spanned(node, msg)` or `new(span, msg)` | | rustc checking the generated code | a field type without `Default`, a missing trait bound | give the generated tokens the field's span with `quote_spanned!` | ## Reporting the derive's own errors There are three ways to fail, and they differ only in where the user looks: 1. **`panic!`**: rustc catches it and reports "proc-macro derive panicked" at the derive name, with the message as help. The error carries no field location. 2. **`syn::Error::new(Span::call_site(), msg)`**: a clean compile error, but still underlining the derive. 3. **`syn::Error::new_spanned(&field.ty, msg)`** or `new(field.ident.span(), msg)`: underlines the exact code at fault. `to_compile_error()` (or `into_compile_error()`) renders the error as a `compile_error!` invocation carrying that span; returning those tokens from the derive is what makes rustc print it. `Error::combine` merges several errors so the user sees every bad field in one build rather than one per attempt. A dedicated diagnostics API, `proc_macro::Diagnostic`, is still unstable, so on stable Rust `compile_error!` is the mechanism. ## Getting rustc's own errors onto the field Suppose a `Defaults` derive emits `#field: ::core::default::Default::default()` for every field and the user's `pool: Pool` has no `Default`. rustc's E0277 is reported at the span of the `Default::default()` call. Those tokens were written in `quote!`, so the error underlines `Defaults` in the derive, with a note that it "originates in the derive macro". The user has to guess which of the fields is wrong. Wrapping the per-field fragment in `quote_spanned!{f.ty.span()=> ... }` gives those tokens the span of the field's type. The same E0277 then underlines `Pool` on the `pool` line. The quote documentation shows the classic form of this trick: an assertion such as `struct _AssertSync where #ty: Sync;` emitted with the type's span so a failure points at the user's type. Two details matter: - the span expression is evaluated in the macro, and the `=>` separates it from the tokens to emit; - `Spanned::span()` from syn returns a node's span, but on a stable compiler only the span of the node's *first token*, because joining spans is nightly-only; `Error::new_spanned` records the first and last tokens and can underline the whole node. ## Spans also affect name resolution A span is not only a location; it also carries hygiene. The `proc_macro` docs say identifiers with `Span::call_site()` resolve as if written directly at the macro call, while `Span::mixed_site()` gives `macro_rules!`-style resolution for local variables, labels and `$crate`. A span borrowed from the user's field resolves at the user's code as well, so keep absolute paths such as `::core::default::Default` inside `quote_spanned!` too. ## Checklist for a reviewable derive - No `unwrap()` or `panic!` on user input; every failure is a `syn::Error` with a meaningful span. - Unknown helper options are errors spanned at the option. - Code generated per field is emitted with that field's span. - Several errors are combined, not reported one build at a time. - Tests compile failing inputs and check the error text, which is covered in the material on attribute and function-like macros.
- Why does an error about `#ty` itself already point at the user's type, even inside plain quote!?Interpolated tokens keep the spans their `ToTokens` implementation gives them, and a `syn::Type` parsed from the input carries the user's spans. An error that rustc attributes to those tokens, such as a bound check on `<#ty as Default>::default()`, lands on the type. Only the tokens written literally in the template default to `Span::call_site()`.
- How do you report errors for every bad field instead of stopping at the first?Keep an `Option<syn::Error>` while walking the fields; for each failure either store a new error or call `combine` on the existing one. After the loop, return `err.to_compile_error()` if any were collected. rustc then prints one error per field in a single build, each with its own span.
- panic! is fine; rustc points the error at the offending field anyway.
- Tokens written inside quote! keep the location of the user's struct.
- Error::new(Span::call_site(), msg) underlines the field being checked.
- proc_macro::Diagnostic is the stable way to emit spanned warnings.
- Error::new_spanned and Error::new always produce identical spans.