Sub topic 3
Spans, Hygiene, and Reliable Procedural Macros
Assume you know Rust structs, traits, generics, Cargo, and basic syn and quote. This chapter focuses on source locations, attributes, testing, and practical limits.
Spans and hygiene
A Span records where a token came from. Rust uses spans to connect compiler errors with source code. quote! usually preserves the spans of parsed tokens. Tokens created by a macro often use Span::call_site(), meaning they behave as if written at the macro call.
Hygiene limits accidental name conflicts. Still, use distinctive generated names and absolute paths such as ::core::option::Option. Do not assume a name imported by the calling crate is available.
Reporting errors with `syn::Error`
Return syn::Result from expansion logic. Error::new_spanned attaches an error to the relevant syntax node. Convert the error into compile_error! tokens at the procedural-macro boundary.
fn expand(input: syn::DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
if !input.generics.params.is_empty() {
return Err(syn::Error::new_spanned(
&input.generics,
"this macro does not support generics",
));
}
Ok(quote::quote! {})
}Reading helper attributes
Declare accepted helper attributes in the derive registration:
#[proc_macro_derive(Describe, attributes(describe))]In syn 2, use parse_nested_meta to read properties such as #[describe(name = "User")]. Reject unknown properties rather than silently ignoring mistakes.
Writing an attribute macro
An attribute macro receives its arguments and the annotated item. It returns replacement tokens. Parse the item with ItemFn, preserve its attributes and visibility, then wrap its body. Preserve the original signature so callers see the same function interface.
Testing and debugging
Use trybuild for compile-time behavior. Put valid examples in tests/ui/pass and expected failures in tests/ui/fail. Run cargo test; trybuild compares failure output with checked-in .stderr files. Use cargo expand to inspect generated Rust when a macro compiles but behaves unexpectedly.
> callout note > Test diagnostics as part of the interface. A useful error should identify the invalid syntax and explain how to correct it.
Limits and best practices
Procedural macros increase compile time because they parse and expand during compilation. Keep generated code small, validate early, support generics deliberately, and document generated APIs. Macro code cannot inspect runtime values. Prefer a normal function or macro_rules! when those tools solve the problem more simply.
Exercise
Why should a macro use Error::new_spanned instead of returning a plain string?
Show answer
It attaches the diagnostic to the offending source syntax, so the compiler can point the user to the relevant location.