Sub topic 13
Testing and Debugging with trybuild and cargo expand
This chapter assumes you can already write a derive macro with syn and quote, including error reporting with syn::Error. It also assumes you know Cargo workspaces and dev-dependencies. Macros are hard to debug because the code you wrote is not the code the compiler checks. The compiler checks the expanded output. A macro also has two outcomes to test: it must generate correct code for valid input, and it must produce a clear error for invalid input.
This chapter uses the FieldNames derive from the error-reporting chapter, which generates a field_names() function and rejects anything except structs with named fields.
Choosing a testing layer
Three kinds of test cover different failures.
| Layer | What it checks | Tool |
|---|---|---|
| Unit test of the expansion logic | The tokens your code generates, and the errors it returns | `cargo test` with `proc_macro2` |
| UI test | That real code compiles, and that bad input fails with the exact message and span | `trybuild` |
| Inspection | What the generated code looks like | `cargo expand`, printing tokens |
Unit-testing the expansion logic
A function marked #[proc_macro_derive] takes and returns proc_macro::TokenStream. That type only works while the compiler is running a macro, so a unit test cannot call it. The proc_macro2 crate has a fallback implementation that works anywhere.
This is why the earlier FieldNames example has a separate expand function. It takes a syn::DeriveInput and returns syn::Result<proc_macro2::TokenStream>, so tests can call it directly. Keep the entry point as thin as possible, because it is the one part you cannot unit-test.
Add this module to the same lib.rs as expand:
#[cfg(test)]
mod tests {
use super::expand;
use quote::quote;
use syn::{parse_quote, DeriveInput};
#[test]
fn lists_field_names() {
let input: DeriveInput = parse_quote! {
struct Point { x: i32, y: i32 }
};
let actual = expand(input).unwrap();
let expected = quote! {
impl Point {
pub fn field_names() -> &'static [&'static str] {
&["x", "y"]
}
}
};
assert_eq!(actual.to_string(), expected.to_string());
}
#[test]
fn rejects_enums() {
let input: DeriveInput = parse_quote! {
enum Color { Red, Green }
};
let err = expand(input).unwrap_err();
assert_eq!(
err.to_string(),
"FieldNames only supports structs with named fields"
);
}
}parse_quote! builds a syn value from Rust-looking tokens, so you can write test inputs as ordinary code. Comparing to_string() output works because both sides are token streams, which print in a normalized form. Don't compare against hand-typed strings, since whitespace between tokens is hard to predict.
Token-string comparison has limits:
- It is brittle for large expansions, because any harmless change in generated code fails the test.
- It cannot tell you whether the generated code compiles.
- It cannot check how the error looks to a user.
Use it for small, stable outputs and for error text. Leave "does it compile" to trybuild.
UI tests with trybuild
trybuild compiles small Rust files and compares the result against expectations. A "pass" file must compile and run successfully. A "compile-fail" file must fail, and its compiler output must match a stored .stderr file. This tests what users see: the message, the line, and the span the error underlines.
Setup
Add it as a dev-dependency of the macro crate:
[dev-dependencies]
trybuild = "1"Create a test harness at tests/ui.rs:
#[test]
fn ui() {
let t = trybuild::TestCases::new();
t.pass("tests/ui/pass/*.rs");
t.compile_fail("tests/ui/fail/*.rs");
}Use one #[test] function for all cases. Trybuild builds all the files as binaries in a single generated project, so batching them is much faster than one test per file. The macro crate is made available to those files automatically, under its package name.
Pass cases
Create tests/ui/pass/basic.rs:
use my_macros::FieldNames;
#[derive(FieldNames)]
struct Point {
x: i32,
y: i32,
}
fn main() {
assert_eq!(Point::field_names(), &["x", "y"]);
}Because pass files are executed, main can assert on the macro's behavior. Add pass files for generic structs too. They catch the mistake of ignoring generics, which a unit test of a non-generic struct would miss.
Compile-fail cases
Create tests/ui/fail/enum.rs:
use my_macros::FieldNames;
#[derive(FieldNames)]
enum Color {
Red,
}
fn main() {}On the first run there is no expected output, so trybuild fails the test. It saves what the compiler printed to a wip/ directory and shows it. After you check that it looks right, accept it:
TRYBUILD=overwrite cargo testThis writes tests/ui/fail/enum.stderr:
error: FieldNames only supports structs with named fields
--> tests/ui/fail/enum.rs:4:6
|
4 | enum Color {
| ^^^^^The ^^^^^ underline is the span from Error::new_spanned(&input.ident, ...). If you changed the macro to use Span::call_site(), the underline would move to the whole derive attribute and this test would fail. That makes .stderr files a good guard against span regressions.
Review every .stderr file before committing it. A macro that panics produces a stored message that begins with "proc-macro derive panicked". That is a bug in your macro, not the expected output.
Handling compiler version drift
Compiler diagnostics change between Rust releases. A .stderr file recorded on one version may not match another, even when your macro is unchanged. Two common ways to manage this:
- Run the UI tests in only one CI job, on a pinned toolchain.
- Keep fail cases simple, so the message you assert on is mostly your own text.
Some projects gate trybuild tests behind a feature flag or a rust-toolchain.toml.
Inspecting expansions with cargo expand
When a test fails with a confusing error in generated code, look at the generated code. The cargo-expand tool prints a crate after all macros have run.
cargo install cargo-expand
rustup toolchain install nightly
cargo expandExpansion output relies on nightly compiler support, so a nightly toolchain must be installed. Your project can still build on stable.
Run it in the crate that uses the macro, not the macro crate itself. The macro crate has nothing to expand. Useful forms:
cargo expand --lib # expand the library target
cargo expand --test ui_usage # expand a given integration test file
cargo expand shapes::point # expand one module onlyFor Point, the output would include something like this:
impl Point {
pub fn field_names() -> &'static [&'static str] {
&["x", "y"]
}
}Reading the expansion often exposes the cause directly:
- A path such as
HelloMacrowhere you intended::hello_macro::HelloMacro(missing absolute path). - An
implwith no generics when the type had them (missingsplit_for_impl). - A repeated or missing item, caused by a wrong
#(...)*repetition.
Existing expansions also include output from standard derives and println!, so expand a module or a small test file to keep the output readable.
Printing tokens during expansion
You can also debug from inside the macro. Anything written to standard error while the macro runs appears in the compiler output:
let expanded = quote! { /* ... */ };
eprintln!("{}", expanded);The Display output of a token stream is one dense line. To format it, use prettyplease, which prints a syn::File as normal Rust code:
fn pretty(tokens: proc_macro2::TokenStream) -> String {
let file: syn::File = syn::parse2(tokens).expect("generated code should parse as items");
prettyplease::unparse(&file)
}Add prettyplease = "0.2" as a dev-dependency and use this helper in unit tests or temporary debugging. It requires the full feature of syn, which the macro crate already enables. The parse2 call also checks that your output is syntactically valid, which catches unbalanced braces early. It does not check types or name resolution.
Remove eprintln! calls before release. Output from a dependency's macros appears in every downstream user's build.
A practical checklist
- Put expansion logic in a function over
proc_macro2types, and unit-test it. - Add a pass case for each supported shape: plain struct, generic struct, struct with a
whereclause, and each helper attribute. - Add a compile-fail case for each error your macro can return, with the span you intend.
- When something fails, run
cargo expandon a minimal use of the macro. - Pin the toolchain used for
.stderrcomparison.
Exercise
You change FieldNames so that its error uses Span::call_site() instead of the span of the enum's identifier. The unit test rejects_enums still passes, but cargo test fails in tests/ui.rs. Why does each test behave this way, and how do you fix the failing one?
Show answer
The unit test only compares the error message text, and that text did not change. The trybuild test compares the full compiler output stored in tests/ui/fail/enum.stderr, including the line, column, and underline. With call_site() the underline moves to the #[derive(FieldNames)] attribute, so the output no longer matches. If the new span is intended, review the new output and run TRYBUILD=overwrite cargo test to update the .stderr file. Otherwise, restore the span of the identifier in the macro.
Exercise
A teammate writes #[test] fn t() { FieldNames_derive(input) } inside the macro crate, calling the function marked #[proc_macro_derive], and the test panics. What is the cause, and what is the structural fix?
Show answer
proc_macro::TokenStream can only be used while the compiler is running a macro, so calling the entry point from a normal test panics. The fix is to move the logic into a function that takes a syn::DeriveInput and returns syn::Result<proc_macro2::TokenStream>, such as expand. The entry point becomes a thin wrapper that parses its input, calls expand, and converts the result with .into(). The tests then call expand directly.