Sub topic 14
Limitations, compile-time cost, and best practices
This chapter closes the tutorial. It assumes you can write a proc-macro crate, parse input with syn, generate code with quote, and report errors with syn::Error. Here we cover what procedural macros cannot do, what they cost, and how to keep them maintainable.
What procedural macros cannot do
A procedural macro sees only tokens. It does not see types, trait implementations, or the code around the item it annotates.
- No type information. A derive on
struct A { b: B }sees the identifierB. It cannot tell whetherBimplementsClone, or whetherBis a type alias. - No access to other items. An attribute macro receives only the item it is attached to. It cannot read a sibling function or the module it sits in.
- Hygiene is partial. Identifiers made with
Span::call_site()can clash with names in the user's code. Identifiers made withSpan::mixed_site()behave likemacro_rules!locals. - Crate layout. A
proc-macro = truecrate can export only macros. Shared helper types go in a separate crate. - Unstable APIs. Much of
proc_macro(diagnostics,Span::source_file, and similar) needs nightly. Stable code reports errors throughcompile_error!, whichsyn::Errorgenerates.
Compile-time cost
Every proc-macro crate and its dependencies are compiled before the crate that uses them. They also run on every build of the user's crate.
| Source of cost | Why it matters | Mitigation |
|---|---|---|
| `syn` with `full` | Parses all of Rust syntax, so it builds slowly | Use the default features when you only need `DeriveInput` |
| Many macro invocations | Each invocation runs your code | Keep expansion logic linear and avoid repeated parsing |
| Large generated code | The compiler must type-check and optimize all of it | Generate small impls that call shared generic functions |
| Dependency chain | Users pay for what you depend on | Avoid extra crates when `syn` and `quote` suffice |
Enable syn's full feature only for items such as functions (ItemFn). A derive that reads only structs and enums works with the default derive feature.
Best practices
- Prefer
macro_rules!when it is enough. A declarative macro needs no extra crate and builds faster. Use a procedural macro when you must inspect struct fields, parse custom syntax, or produce precise errors. - Keep the entry point thin. Put the logic in a function that takes and returns
proc_macro2::TokenStreamor returnssyn::Result. You can then unit-test it without the compiler's macro machinery. - Use absolute paths in generated code. Write
::core::option::Optionand::my_crate::Trait, not bare names. The user may have shadowedOptionor imported nothing. - Support generics from the start. Use
split_for_implin every derive so generic types work. - Point errors at the right span. Use
Error::new_spannedon the offending tokens so users see the problem where it occurs. - Reject what you do not support. Return an error for unions, enums, or unknown helper keys instead of generating wrong code.
- Test failures too. Use
trybuildfor both passing and failing cases, and check output withcargo expandwhile developing. - Keep macros small and documented. Document the accepted syntax and the traits or items the expansion relies on.
use proc_macro::TokenStream;
use syn::{parse_macro_input, DeriveInput};
#[proc_macro_derive(Thin)]
pub fn thin(input: TokenStream) -> TokenStream {
let input = parse_macro_input!(input as DeriveInput);
expand(input)
.unwrap_or_else(syn::Error::into_compile_error)
.into()
}
fn expand(input: DeriveInput) -> syn::Result<proc_macro2::TokenStream> {
let name = &input.ident;
let (ig, tg, wc) = input.generics.split_for_impl();
Ok(quote::quote! {
impl #ig ::core::fmt::Debug for #name #tg #wc {
fn fmt(&self, f: &mut ::core::fmt::Formatter<'_>) -> ::core::fmt::Result {
f.write_str(stringify!(#name))
}
}
})
}This derive prints only the type name. Its shape is the one to reuse: a thin entry point, a syn::Result function, absolute paths, and split_for_impl.
Exercise
A teammate's derive macro compiles slowly and gives unhelpful errors. Name two changes from this chapter that address each problem.
Show answer
For build time, drop syn's full feature if the macro only reads structs and enums, and replace the macro with macro_rules! where it would be enough. For errors, return syn::Result from an inner function and use Error::new_spanned on the offending tokens, then convert with into_compile_error.
Exercise
Why should generated code use ::core::option::Option instead of Option?
Show answer
The user's crate may define or import its own item named Option. A bare name would then resolve to that item. An absolute path always resolves to the standard library type.