Sub topic 14
Limitations, Compile-Time Cost, and Best Practices
This chapter closes the series on procedural macros. It covers what a procedural macro cannot know, what it costs to compile, and the habits that keep macro crates maintainable. It assumes you have written a derive macro with syn and quote, that you know what a TokenStream is, and that you have used cargo test.
What a procedural macro cannot do
A procedural macro receives tokens. It does not receive a type-checked program. Most limitations follow from that.
| Limitation | Consequence | Workaround |
|---|---|---|
| No type information | `Option<String>` is only the tokens `Option`, `<`, `String`, `>`. Type aliases are invisible. | Match on syntax, document the heuristic, and let the generated code make the compiler check types. |
| No view of other items | A derive sees only the struct it is attached to, not sibling items or other modules. | Pass information through attributes, or generate trait calls that the compiler resolves later. |
| A proc-macro crate exports only macros | You cannot put a shared trait or runtime helper in the same crate. | Split into a runtime crate and a macro crate, and re-export the macros from the runtime crate. |
| `proc_macro` types work only during expansion | `proc_macro::TokenStream` panics in ordinary unit tests. | Use `proc_macro2` types in the logic and convert at the edge. |
| Unhygienic output by default | Identifiers from `quote!` use the call site's name resolution, so they can collide with user names. | Use absolute paths and unlikely local names. |
Guessing types from syntax
Sometimes a macro has to branch on a type, for example to treat Option<T> fields as optional. The macro can only inspect the path as written.
use syn::{GenericArgument, PathArguments, Type};
/// Returns `T` if the type is spelled `Option<T>`, `std::option::Option<T>`, etc.
fn option_inner(ty: &Type) -> Option<&Type> {
let Type::Path(p) = ty else { return None };
if p.qself.is_some() {
return None;
}
let seg = p.path.segments.last()?;
if seg.ident != "Option" {
return None;
}
let PathArguments::AngleBracketed(args) = &seg.arguments else {
return None;
};
match args.args.first()? {
GenericArgument::Type(inner) => Some(inner),
_ => None,
}
}
#[cfg(test)]
mod tests {
use super::*;
use syn::parse_quote;
#[test]
fn detects_option_by_spelling() {
let ty: Type = parse_quote!(Option<String>);
assert!(option_inner(&ty).is_some());
let alias: Type = parse_quote!(MaybeName);
assert!(option_inner(&alias).is_none());
}
}If a user writes type MaybeName = Option<String>; and uses MaybeName in a field, the macro treats it as a plain type. It cannot see through the alias. A user's own type named Option is mistaken for the standard one. State this in your macro's documentation. If a wrong guess would silently produce wrong behavior, offer an explicit attribute such as #[describe(optional)] instead.
Macros run with full privileges
A procedural macro is ordinary Rust compiled and run by the compiler, with your user's permissions. It can read files, open sockets, and run commands. Three consequences follow.
- Adding a macro dependency means trusting its code at build time, even if you never run the final binary. Review macro crates as you would a build script.
- Macros should be pure: the same input tokens should always produce the same output. The compiler's incremental caching assumes this. A macro that reads a file or an environment variable and does not tell Cargo can produce stale builds.
- If a macro reads a file, prefer
include_str!orinclude_bytes!in the generated code. The compiler then tracks the file as a dependency.
Compile-time cost
Procedural macros add time in three places.
- Building the macro crate and its dependencies.
synis the largest cost. It is built for the host machine, even when you cross-compile. - Running the macro. Each invocation parses and regenerates code. This is usually fast, but it adds up if a macro runs hundreds of times or parses large inputs.
- Compiling the generated code. A macro that emits large
implblocks for every type makes the compiler type-check, optimize, and monomorphize all of it.
Trim `syn` features
syn gates most of its syntax tree behind Cargo features. A derive macro that only reads a DeriveInput does not need the full feature, which adds expression and statement parsing.
[lib]
proc-macro = true
[dependencies]
syn = { version = "2", default-features = false, features = ["derive", "parsing", "printing", "proc-macro"] }
quote = "1"
proc-macro2 = "1"Enable full only when you parse items such as ItemFn (as in an attribute macro). Enable extra-traits only if you need Debug or PartialEq on syntax nodes, for instance in a debugging session. If a build fails after trimming features, the compiler error names the missing item, and you can add the matching feature back.
Measure before optimizing
Use Cargo's timing report to see where build time goes.
# Cargo.toml of the workspace root. Optimizes proc macros and build scripts only.
[profile.dev.build-override]
opt-level = 3Run cargo build --timings and open the HTML report it writes under target/cargo-timings. If the macro crate and syn dominate a clean build, trim features. If the macro itself runs slowly on every incremental build, build-override raises the optimization level of the macro code, which speeds up expansion at the cost of a longer first compile of the macro crate. Compare the two timings and keep the setting only if it helps. To see how much code your macro emits, use cargo expand from the previous chapter and look at the size of the output.
Choosing the right tool
A procedural macro is the heaviest option. Reach for it last.
Procedural macros earn their cost when you must read struct fields, parse a custom syntax, rewrite a function body, or give errors that point into the user's code.
Best practices
Keep logic out of the entry point
Entry points take and return proc_macro::TokenStream, which cannot be used in unit tests. Make each entry point a thin wrapper around a function that uses proc_macro2 and returns syn::Result. That function can be tested directly.
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::{parse2, DeriveInput};
#[proc_macro_derive(TypeName)]
pub fn type_name(input: TokenStream) -> TokenStream {
expand(input.into())
.unwrap_or_else(syn::Error::into_compile_error)
.into()
}
fn expand(input: TokenStream2) -> syn::Result<TokenStream2> {
let input: DeriveInput = parse2(input)?;
let name = &input.ident;
let name_str = name.to_string();
let (ig, tg, wc) = input.generics.split_for_impl();
Ok(quote! {
impl #ig #name #tg #wc {
pub fn type_name() -> &'static str {
#name_str
}
}
})
}
#[cfg(test)]
mod tests {
use super::*;
#[test]
fn expands_for_a_struct() {
let out = expand(quote! { struct Point { x: i32 } }).unwrap();
assert!(out.to_string().contains("type_name"));
}
#[test]
fn rejects_invalid_input() {
assert!(expand(quote! { not an item }).is_err());
}
}Unit tests like these check the logic quickly. Keep trybuild for the exact wording and location of compiler errors, which you saw in the testing chapter.
Generate small code that calls into a runtime crate
If the expansion contains real logic, it is hard to read, hard to debug, and costs compile time for every use. Put the logic in ordinary generic functions in a runtime crate, and have the macro emit a short call to them. Users get readable stack traces, and the compiler checks the logic once instead of once per expansion.
Protect the generated code from the user's scope
- Refer to items by absolute path:
::core::option::Option,::std::fmt::Debug, and::my_crate::Trait. A user may have shadowedOptionor not imported the trait. - Name local variables so they are unlikely to collide, such as
__my_macro_value. Identifiers created withquote!resolve at the call site, so a plainvaluecan clash with a user's binding. - Pass user-written tokens through unchanged, so error messages and IDE features refer to the right source location.
Fail with errors, never panics
A panic gives the user a message that starts with "proc-macro derive panicked", with little context. Return syn::Error with a span on the offending token, and use Error::combine to report several problems in one compile run instead of one at a time.
Document the contract
Write down which inputs the macro accepts, which helper attributes it reads, what it generates, and what the generated code requires from the user's crate, such as a dependency on the runtime crate. Include a short "Expansion" example in the documentation, taken from cargo expand.
Exercise
A derive macro needs to treat fields of type Option<T> differently. A user declares type Nick = Option<String>; and a field nick: Nick. Why does the macro treat the field as non-optional, and how can you give the user a reliable way to get the optional behavior?
Show answer
The macro sees only the tokens Nick, not the type alias it refers to, so a check on the spelling Option does not match. Add an explicit helper attribute such as #[describe(optional)], read with parse_nested_meta. Alternatively, document that only the literal Option<...> spelling is detected.
Exercise
Your derive macro crate takes 40 seconds to build from scratch, and most of that is syn. Name two changes you can make to reduce this, and one tool for confirming where the time goes.
Show answer
Disable syn's default features and enable only what the macro uses (for example derive, parsing, printing, proc-macro), and leave out full and extra-traits unless needed. Another change is to replace the macro with macro_rules! or generics if it does not need to inspect fields. Use cargo build --timings to see which crates dominate the build.
Exercise
Why can a unit test call expand(quote! { struct Point { x: i32 } }) but not call a function that takes proc_macro::TokenStream directly?
Show answer
proc_macro::TokenStream is only usable while the compiler is running a macro expansion, and it panics in a normal test binary. proc_macro2::TokenStream falls back to its own implementation outside the compiler, so logic written against it can be tested with cargo test.