Debugging Macros
Macro bugs show up as confusing compiler errors at expansion sites. cargo expand, eprintln! in proc macros, and trybuild tests are the main debugging tools.
Busca en todas las páginas de la documentación
Macro bugs show up as confusing compiler errors at expansion sites. cargo expand, eprintln! in proc macros, and trybuild tests are the main debugging tools.
cargo install cargo-expand
cargo expand -p mycrate path::to::function
RUSTFLAGS="-Z unstable-options" cargo expand --theme=monokai # optional// inside proc macro during dev:
eprintln!("parsed: {:?}", input);When to reach for this: Any time expanded code does not match mental model or errors reference wrong spans.
# Expand derive output
cargo expand -p api handlers::create_order
# Expand specific module
cargo expand -p my_macros derive_validate
# Pretty print in test with macrotest// proc-macro crate dev
#[proc_macro_derive(MyTrait)]
pub fn derive_my_trait(input: TokenStream) -> TokenStream {
let ast = syn::parse_macro_input!(input as DeriveInput);
if std::env::var("DEBUG_MACRO").is_ok() {
eprintln!("{:#?}", ast);
}
// ...
TokenStream::new()
}What this demonstrates:
cargo expand shows post-macro Rusteprintln! in proc macro runs at compile timeDEBUG_MACRO env gate avoids noisy normal buildsreturn syn::Error::new_spanned(&field.ident, "field must have #[validate]")
.to_compile_error()
.into();compile_error! in macro_rules! fallback arm#[test]
fn ui() {
let t = trybuild::TestCases::new();
t.compile_fail("tests/ui/missing_field.rs");
}debug-macros.-p package - empty expand. Fix: workspace cargo expand -p proc_crate.rustfmt expanded output; snapshot with macrotest.| Alternative | Use When | Don't Use When |
|---|---|---|
trace_macros! (unstable) | macro_rules step trace | Stable CI |
macrotest snapshots | regression on expansion | Quick one-off |
Manual quote! in test | Unit test generator fn | Full integration |
Some built-in expands differ; focus on your proc macros and macro_rules!.
cargo expand --bin myapp shows main transformation.
rust-analyzer "Expand macro recursively" for some macros; cargo-expand for full fidelity.
Generated identifiers resolve at macro definition site hygiene; use deliberately.
Comment out arms; use compile_error!(stringify!($($t)*)) arm to see tokens.
macrotest or check in trybuild pass/fail only.
cargo expand -p crate dumps entire crate - large output.
Shows as compiler error with backtrace if RUST_BACKTRACE=1 on macro author machine.
Expand same input on 1.96 vs 1.97 when upgrading MSRV.
CONTRIBUTING for macro crate: expand command, trybuild, env flags.
Stack versions: This page was written for Rust 1.97.0 (edition 2024), Tokio 1.x, Axum 0.8, serde 1.0, sqlx 0.8, clap 4, and Polars 0.46+.
Revisado por Chris St. John·Última actualización: 19 jul 2026