liveBook · Manning

Proc_macro_error

As explained in Write Powerful Rust Macros

proc_macro_error is a Rust library that provides procedural-macro facilities for reporting compile-time errors with reduced boilerplate.

proc_macro_error is a Rust library for reporting useful compile-time errors from procedural macros with less boilerplate than syn::Error. Annotate the public macro entry point with #[proc_macro_error] before using its diagnostic macros. section 7.9.2 section 7.9.3

Choose the reporting operation according to how processing should proceed:

  • Use abort! when a problem makes continued processing inappropriate; it can identify a span and attach help or note text. section 7.9.2
  • Use emit_error! when multiple problems should be reported while parsing and transforming the remaining input. section 7.9.2
  • Prefer syn::Error when an existing syn dependency and explicit Result-based failure flow matter more than reduced ceremony. section 7.9.3

Validating a panic-to-Result attribute macro

An attribute macro can reject an empty panic with abort! and report an incompatible Result signature with emit_error!. The resulting diagnostics point to the relevant panic or signature and can include actionable guidance instead of pointing only to the macro invocation. section 7.9.2

Listing 7.23 Adding the extra attribute macro to our public lib.rs function
use proc_macro_error::proc_macro_error;      #1

#[proc_macro_error]       #2
#[proc_macro_attribute]
pub fn panic_to_result(_a: TokenStream, item: TokenStream) -> TokenStream {
    // ...
}

Use the entry-point attribute together with the procedural-macro attribute before invoking proc_macro_error diagnostics. section 7.9.2

How Write Powerful Rust Macros covers it

How deep it goes
Explains entry-point setup, abort-versus-emit_error control flow, diagnostic annotations, and the syn::Error trade-off without detailing library internals.
Examples
Demonstrates panic-to-Result transformation, missing panic messages, invalid return signatures, and span-targeted diagnostics with help and documentation.
What it assumes
Assumes Rust procedural-macro and syn familiarity while contrasting its APIs with Result-based syn::Error handling.
What you can do after
Apply it via procedural-macro attributes to report precise, actionable, and possibly multiple compile-time errors.
How it connects
Connects procedural macros with attribute macros, TokenStream manipulation, spans, syn::Error, Result, and compile-time error reporting.

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Write Powerful Rust Macros. The section links point to the parts of the book it draws on.