proc-macro-error
This crate aims to provide an error reporting mechanism that is usable inside
proc-macros
, can highlight a specific span, and can be migrated from
panic!
-based errors with minimal efforts.
Usage
In your Cargo.toml
:
= "0.1"
In lib.rs
:
extern crate proc_macro_error;
use ;
// This is your main entry point
Motivation and Getting started
Error handling in proc-macros sucks. It's not much of a choice today:
you either "bubble up" the error up to top-level of you macro and convert it to
a compile_error!
invocation or just use a good old panic. Both these ways suck:
- Former sucks because it's quite redundant to unroll a proper error handling
just for critical errors that will crash the macro anyway so people mostly
choose not to bother with it at all and use panic. Almost nobody does it,
simple
.expect
is too tempting. - Later sucks because there's no way to carry out span info via panic.
rustc
will highlight the whole invocation itself but not some specific token inside it. Furthermore, panics aren't for error-reporting at all; panics are for bug-detecting (like unwrapping onNone
or out-of range indexing) or for early development stages when you need a prototype ASAP and error handling can wait. Mixing these usages only messes things up. - There is
proc_macro::Diagnostics
but it's experimental.
That said, we need a solution, but this solution must meet these conditions:
- It must be better than panics. The main point: it must offer a way to carry span information over to user.
- It must require as little effort as possible to migrate from panic. Ideally, a new macro with the same semantics plus ability to carry out span info.
- It must be usable on stable.
This crate aims to provide such a mechanism. All you have to do is enclose all
the code inside your top-level #[proc_macro]
function in [filter_macro_errors!
]
invocation and change panics to [span_error!
]/[call_site_error!
] where appropriate,
see Usage
How it works
Effectively, it emulates try-catch mechanism on top of panics.
Essentially, the [filter_macro_errors!
] macro is a
try catch
[span_error!
] and co are
throw ;
By calling [span_error!
] you trigger panic that will be caught by [filter_macro_errors!
]
and converted to compile_error!
invocation.
All the panics that wasn't triggered by [span_error!
] and co but any other reason
will be resumed as is.
Panic catching is indeed slow but the macro is about to abort anyway so speed is not
a concern here. Please note that this crate is not intended to be used in any other way
than a proc-macro error reporting, use Result
and ?
instead.