Procedural macros
A procedural macro is a compiler plugin written in Rust that turns a token stream into another token stream. Derives, attribute macros, and function-like proc macros are the three kinds.
Detailed Explanation
#[derive(Debug)] is a procedural macro. The compiler hands the struct's tokens to a function in the syn/quote ecosystem, and that function returns the tokens of an impl Debug for TheStruct. You did not write the impl. The derive did. #[tokio::main] is an attribute macro: it rewrites the item it sits on, wrapping main in a runtime. sqlx::query! is a function-like proc macro: it looks like query!("select ...") and may even talk to a database at compile time.
A proc-macro crate is a special crate type, proc-macro = true, and it can export only the macro entry points, not ordinary items for runtime use. Those entry points take TokenStream and return TokenStream. In practice everyone uses syn to parse into a syntax tree, quote to emit tokens, and proc-macro2 so the same code works in tests. Errors should go through syn::Error::to_compile_error so the user sees a spanned message, not a panic in the compiler.
The three kinds differ in where they attach. A derive may only add impls; it must not change the item. An attribute macro may replace the item entirely. A function-like macro replaces the invocation. Hygiene for proc macros is weaker than for macro_rules; you spell paths as ::core::fmt::Formatter or with the caller's identifiers as syn parsed them.
Cost: compile time. Every crate that uses your derive compiles your proc-macro crate, then runs it on every annotated item. syn is thorough and not small. A derive that does work a generic impl could do is wasted time. A derive that generates boilerplate the type system cannot express — Serialize, thiserror, builder structs — is the reason the feature exists.
When you write a proc macro: you are parsing syntax macro_rules cannot, or you are generating impls from field lists. When you do not: a generic impl, a macro_rules helper, or a build script. Do not start a proc-macro crate to save three lines of impl.
Code Examples
What a Debug derive is doing, written by hand:
// What a Debug derive is doing, written by hand:
struct Session {
user_id: u64,
}
impl std::fmt::Debug for Session {
fn fmt(&self, f: &mut std::fmt::Formatter<'_>) -> std::fmt::Result {
f.debug_struct("Session")
.field("user_id", &self.user_id)
.finish()
}
}
fn main() {
println!("{:?}", Session { user_id: 17 }); // prints: Session { user_id: 17 }
}Common Gotchas
A proc-macro crate cannot export runtime functions
Split the crate: `foo_derive` for the macro, `foo` for the traits it implements. The derive crate depends on `syn`; the runtime crate must not.
Panicking in a proc macro crashes compilation with a poor message
Return `compile_error!` tokens with a span on the offending field.
Compile-time I/O makes builds non-hermetic
`query!` that hits a live database fails in CI if the database is down. Prefer offline-checked SQL or a committed schema.
Derives cannot change the struct
If you need extra fields, use an attribute macro or generate a companion type.