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 what a TokenStream is. You will learn how to turn mistakes in a macro's input into compiler errors that point at the right place.
Why not panic?
A procedural macro can call panic!, and the compiler will show the message. The result is poor. The error points at the whole macro call, and the text is wrapped in a "proc macro panicked" message. A syn::Error carries a message and a span, which is a location in the user's source. The compiler then underlines the exact token you chose.
The pattern: return syn::Result
Put the macro logic in a normal function that returns syn::Result. The #[proc_macro_derive] function only converts the outcome 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 has three parts.
expandreturnssyn::Result<proc_macro2::TokenStream>. Inside it you can use?on anysynparsing call, and you can return your own errors withErr(...).Error::new_spanned(&input.ident, "...")builds an error whose span covers the tokens ofinput.ident. Any value that implementsToTokensworks as the first argument.Error::into_compile_errorturns the error into aTokenStreamcontaining acompile_error!invocation. The compiler reports it at the span you chose.
The #(#names),* part is a quote! repetition. It emits each field name as a string literal, separated by commas.
Choosing a span
The span decides where the user's eyes go. Pick the smallest token that explains the problem.
| Situation | Good span source |
|---|---|
| Wrong kind of type (enum instead of struct) | `&input.ident` |
| A bad field | that field's `ident` or `ty` |
| A bad attribute value | the literal or path inside the attribute |
| Input that fails to parse | the span `syn` already attached |
Use Error::new(span, msg) when you have a Span value, such as ident.span(). Use Error::new_spanned when you have syntax nodes. new_spanned can mark a range from the first to the last token of a node.
Errors from parsing
Errors from syn parsing already have spans. In the function-like macro add!(1, 2), a missing comma produces an error at the point where , was expected, and ? passes it up. parse_macro_input! does this too. If parsing fails, it returns a compile_error! for you and exits the macro function.
Reporting several errors
A single error stops the user from seeing other problems in the same build. syn::Error can hold several. Create one error, then call combine to add more.
use syn::{Error, Fields};
fn check_fields(fields: &Fields) -> syn::Result<()> {
let mut errors: Option<Error> = None;
for field in fields {
if field.ident.is_none() {
let err = Error::new_spanned(&field.ty, "fields must be named");
match &mut errors {
Some(all) => all.combine(err),
None => errors = Some(err),
}
}
}
match errors {
Some(all) => Err(all),
None => Ok(()),
}
}into_compile_error then emits one compile_error! per collected message.
Common mistakes
- Using
panic!orunwrap()on user input. Return an error instead. - Using
Span::call_site()for everything. The error then points at the derive or macro call and not at the cause. - Writing vague messages. Say what is supported, as in "only supports structs with named fields".
- Calling
unwrap()onf.identafter you have checked onlyFields::Named. That is safe here. For other field kinds theidentisNone, so check first.
Exercise
In the FieldNames example, why is the logic placed in expand and not directly in the #[proc_macro_derive] function?
Show answer
expand returns syn::Result, so you can use ? and Err(...) inside it. The derive function then converts any error into a compile_error! with into_compile_error. Without this split, every failure would need its own manual conversion to a TokenStream.
Exercise
You want an error that underlines the type of a field named id that is not u32. Which constructor do you use, and what do you pass as the first argument?
Show answer
Use Error::new_spanned(&field.ty, "id must be u32"). The first argument is the Type node, so the error underlines the whole type in the user's code.