Sub topic 10
Reporting errors with syn::Error
This chapter assumes you can write a basic derive macro with syn and quote, and that you know Result and the ? operator. By the end you will turn bad macro input into normal compiler errors that point at the right line of the user's code.
Why a macro should not panic
A procedural macro is a function that runs inside the compiler. If it panics, the compiler prints "proc macro panicked" and points at the whole macro invocation. The message may help you, but the user sees a vague location and a stack of internal text.
A macro can return a better result. It can emit a call to the built-in compile_error! macro. The compiler reports that call like any other error, with the message you chose and the location you chose. syn::Error builds that call for you.
Three situations should produce an error instead of a panic:
- The input does not parse, for example
add!(1 2)with a missing comma. - The input parses but is not supported, for example a derive applied to an enum when it only handles structs.
- A helper attribute has an unknown key or a value of the wrong type.
The pieces of syn::Error
A syn::Error holds a message and a span. A span is a region of the user's source code. The compiler underlines that region when it prints the error. You get the span from tokens that came in with the input.
| Function | What it does |
|---|---|
| `Error::new(span, msg)` | Creates an error at one `Span`. |
| `Error::new_spanned(tokens, msg)` | Creates an error covering everything the tokens span, from the first token to the last. |
| `error.to_compile_error()` | Returns a `proc_macro2::TokenStream` containing a `compile_error!` call. It borrows the error. |
| `error.into_compile_error()` | The same, but it consumes the error. |
| `error.combine(other)` | Merges another error into this one, so both are reported. |
The alias syn::Result<T> is Result<T, syn::Error>. Use it for every helper function in your macro, so ? works everywhere.
Choosing between new and new_spanned
Error::new takes a single Span. A node such as a Field or a Type covers many tokens. On stable Rust you cannot join the first and last spans of such a node yourself. new_spanned handles this: the compiler underlines the whole node.
use proc_macro2::Span;
use syn::Error;
fn examples(ident: &syn::Ident, ty: &syn::Type) -> (Error, Error, Error) {
// Underlines exactly the identifier.
let a = Error::new(ident.span(), "this name is reserved");
// Underlines the entire type, such as `Vec<Option<u8>>`.
let b = Error::new_spanned(ty, "this type is not supported");
// Points at the macro invocation itself, used when no better token exists.
let c = Error::new(Span::call_site(), "missing required argument");
(a, b, c)
}Prefer the most specific span you have. Span::call_site() marks the #[derive(...)] or macro call, and the user then has to guess which field you meant.
The standard shape: expand returns syn::Result
The cleanest design puts all the logic in a function that returns syn::Result<proc_macro2::TokenStream>. The exported macro function becomes a thin wrapper that turns an Err into tokens.
use proc_macro::TokenStream;
use quote::quote;
use syn::{parse_macro_input, Data, DataStruct, DeriveInput, Error, Fields};
#[proc_macro_derive(FieldNames)]
pub fn field_names(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 fields = match &input.data {
Data::Struct(DataStruct {
fields: Fields::Named(f),
..
}) => &f.named,
_ => {
return Err(Error::new_spanned(
&input.ident,
"FieldNames only supports structs with named fields",
))
}
};
let names = fields.iter().map(|f| f.ident.as_ref().unwrap().to_string());
let (ig, tg, wc) = input.generics.split_for_impl();
Ok(quote! {
impl #ig #name #tg #wc {
pub fn field_names() -> &'static [&'static str] {
&[#(#names),*]
}
}
})
}This design has two benefits. Inside expand you can use ? and return Err(...) freely. The wrapper has a single place where errors become tokens.
If a user writes #[derive(FieldNames)] enum Color { Red }, the compiler prints something like this:
error: FieldNames only supports structs with named fields
--> src/main.rs:4:6
|
4 | enum Color {
| ^^^^^The underline sits under Color because new_spanned(&input.ident, ...) used the identifier's span.
The .unwrap().to_string() on f.ident is safe here. The match arm only accepts Fields::Named, and every named field has an identifier.
Errors from parsing
You rarely need to build errors for malformed syntax. Every syn parse call returns a syn::Result whose error already carries the span of the unexpected token. Inside a Parse implementation, ? passes that error up:
use syn::parse::{Parse, ParseStream};
use syn::{LitInt, Token};
struct Pair {
left: LitInt,
right: LitInt,
}
impl Parse for Pair {
fn parse(input: ParseStream) -> syn::Result<Self> {
let left = input.parse()?;
input.parse::<Token![,]>()?;
let right = input.parse()?;
Ok(Pair { left, right })
}
}For add!(1 2), the Token![,] parse fails at 2 with the message "expected ,". The parse_macro_input! macro does the conversion for you. On failure it returns the compile error from the macro function immediately, so you never write that match yourself.
You can improve a built-in message with ParseStream::error or by checking input.peek(...) before parsing:
use syn::parse::{Parse, ParseStream};
use syn::{LitStr, Token};
struct Greeting {
text: LitStr,
}
impl Parse for Greeting {
fn parse(input: ParseStream) -> syn::Result<Self> {
if input.is_empty() {
return Err(input.error("expected a string literal, like \"hello\""));
}
let text: LitStr = input.parse()?;
if !input.is_empty() {
let _: Token![,] = input.parse()?;
}
Ok(Greeting { text })
}
}input.error points at the current position in the input. When the input is empty, it points at the whole macro call.
Errors inside helper attributes
The parse_nested_meta closure from syn 2 returns syn::Result<()>. Its meta argument has an error method that builds a syn::Error spanned at the key being parsed:
use syn::{DeriveInput, LitStr};
fn describe_name(input: &DeriveInput) -> syn::Result<Option<String>> {
let mut name = None;
for attr in &input.attrs {
if attr.path().is_ident("describe") {
attr.parse_nested_meta(|meta| {
if meta.path.is_ident("name") {
let value: LitStr = meta.value()?.parse()?;
name = Some(value.value());
Ok(())
} else {
Err(meta.error("unsupported describe property"))
}
})?;
}
}
Ok(name)
}If the user writes #[describe(title = "x")], the error underlines title. This is the right place to reject unknown keys. If you silently ignore them, a typo like nmae = "x" disappears without any message.
Reporting several errors at once
Returning the first error makes users fix problems one at a time, with a rebuild between each. When checks are independent, collect them and use combine. The compiler then shows every error in one run.
use syn::{Data, DeriveInput, Error};
fn check_fields(input: &DeriveInput) -> syn::Result<()> {
let data = match &input.data {
Data::Struct(s) => s,
_ => return Err(Error::new_spanned(&input.ident, "only structs are supported")),
};
let mut errors: Option<Error> = None;
for field in &data.fields {
if field.ident.is_none() {
let err = Error::new_spanned(field, "all fields must be named");
match &mut errors {
Some(existing) => existing.combine(err),
None => errors = Some(err),
}
}
}
match errors {
Some(e) => Err(e),
None => Ok(()),
}
}When you call to_compile_error on a combined error, it emits one compile_error! call per message, each with its own span.
Keeping the rest of the program compiling
An attribute macro replaces the item it is attached to. If you return only an error, the item vanishes. Every other line that uses that function then produces a second error such as "cannot find function". These follow-up errors hide the one the user needs to read.
The fix is to emit the error and the original item together:
use proc_macro::TokenStream;
use proc_macro2::TokenStream as TokenStream2;
use quote::quote;
use syn::{parse_macro_input, Error, ItemFn};
#[proc_macro_attribute]
pub fn trace(attr: TokenStream, item: TokenStream) -> TokenStream {
let attr = TokenStream2::from(attr);
let func = parse_macro_input!(item as ItemFn);
if !attr.is_empty() {
let err = Error::new_spanned(&attr, "#[trace] takes no arguments").into_compile_error();
return quote! { #err #func }.into();
}
let attrs = &func.attrs;
let vis = &func.vis;
let sig = &func.sig;
let block = &func.block;
let name = sig.ident.to_string();
quote! {
#(#attrs)*
#vis #sig {
println!("entering {}", #name);
#block
}
}
.into()
}The same idea applies to derives. Because a derive adds code without replacing the type, the type stays intact. You only need to avoid emitting a half-built impl that fails with its own errors.
The flow of an error
Common mistakes
- Calling
panic!,unwrap()orexpect()on user-controlled input. Use?andErrinstead. Anunwrapis acceptable only when an earlier check guarantees success, as with the named-fields match above. - Using
Span::call_site()for everything. The error then points at the derive line, not at the field that caused it. - Forgetting to return the tokens. Building an
Errorand dropping it has no effect. You must returninto_compile_error()as part of the macro output. - Writing vague messages. Say what is expected and what was found, and name your macro: "FieldNames only supports structs with named fields" beats "invalid input".
- Ignoring unknown helper attribute keys. Reject them with
meta.error.
Exercise
A derive macro rejects a tuple struct field with Error::new(Span::call_site(), "fields must be named"). Users complain that the error underlines the #[derive(...)] line and not the field. Which change fixes this, and what should the macro do if the struct has three unnamed fields and you want all three reported?
Show answer
Use Error::new_spanned(field, "fields must be named"), where field is the syn::Field value, so the underline covers that field. To report all three, create an Option<Error> before the loop. For each bad field, build an error and call existing.combine(err) if one exists, or store it if not. After the loop, return Err(combined). The compiler then prints one error per field in a single run.
Exercise
Your attribute macro #[trace] returns only Error::new_spanned(&attr, "takes no arguments").into_compile_error() when given arguments. The user sees the intended error plus "cannot find function work in this scope" at every call site. Why, and how do you fix it?
Show answer
An attribute macro replaces the annotated item with its output. Returning only the error removes the function, so each call site fails to resolve it. Return the error tokens followed by the original item, as in quote! { #err #func }.into(). The function then still exists and only the intended error appears.