Skip to content
ImagineWorld

From panic to result: Error handling

node_idnode-book_write-powerful-rust-macros_chapter-08-from-panic-to-result-error-handling
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num8
chapter_titleFrom panic to result: Error handling
governed_byCORPUS
constitutional_citationCONSTITUTION
figure_reviewassets/wpm-fig-8-01-diagram-showing-pure-sum-functions-consistently-returning.png, assets/wpm-fig-8-04-diagram-showing-manipulation-of-sum-type-either.png, assets/wpm-fig-8-05-directory-structure-diagram-showing-panictoresult-directory-with.png, assets/wpm-fig-8-06-diagram-showing-itemfn-signature-and-returntype-with.png
reviewunbalanced $ inline delimiters
local graph

Chapter 8 — From panic to result: Error handling

Section titled “Chapter 8 — From panic to result: Error handling”
  • Understanding the difference between pure and impure functions
  • Understanding the downsides of breaking control flow
  • Using Result for better error handling
  • Writing macros to manipulate function signatures and return values
  • Mutating the received TokenStream as an alternative to creating a new one
  • Creating better error messages with syn::Error or proc_macro_error

Until now, most of our code has focused on structs and enums, with very basic error handling. All of that changes right now! In this chapter, we will manipulate functions, changing panics into Results, which is a better and more idiomatic way of handling errors in Rust. This is a useful segue into seeing how we can manipulate functions with an attribute macro. We will also use this code to explore better ways

of returning errors to the user—because panicking works, but the error just points to the macro invocation, making usage harder than it needs to be. But first, as a general introduction to this chapter’s macro, let’s talk about the problem with exceptions and possible alternatives.

At the time of writing, all the most widely used programming languages (C#, Java, JavaScript, Python) depend heavily on throwing exceptions/errors for failure scenarios. Is something wrong with the data you received from your REST endpoint? Throw an exception, catch it upstream, and change it into a 400 response! A database is giving back an exception when you call it? Wrap it in one of your exceptions and throw it! This is a valid approach to handling things that go wrong or failure paths. You can build great software with error throwing. But it is not without downsides.

One important problem is that it breaks control flow. The easiest code to write, read, and reason about is linear. You read from top to bottom:

fn simple(a: i32, b: i32) -> i32 {
let sum = a + b;
let product = a * b;
sum + product
}

Once you add conditionals, things become a bit harder because you have to keep track of all the possible paths that your code might take:

fn a_bit_harder(a: i32, b: i32) -> i32 {
let sum = a + b;
let product = a * b;
if sum > 7 && product == 0 {
sum + product
} else {
sum - product
}
}

Now add loops, nested conditionals, and even more nested loops, because why not? Things will become so complex that your inner developer will be screaming “Refactor!” because the number of things to keep tabs on for you to understand the function just keeps growing. Cyclomatic complexity is a way to measure this code complexity, and it depends on the number of “paths” that you can take in a function. Ideally, you want this to be in the single digits—only a few possible paths. By default, ESLint will start warning you at 20.

Exceptions are a cause of cyclomatic complexity: if something can throw an exception, that is yet another path that your code might take. What makes them worse than conditionals and loops is how totally unexpected their behavior can be. In a large

<!-- page: 142 -->
# CHAPTER 7 From panic to result: Error handling
codebase, with a core language that likes throwing exceptions, plus a lot of dependencies, almost anything you call might throw an error in the right (well, wrong) circumstances. For example, in Java, `Optional.of` might throw a `NullPointerException`, which is funny—even if there are reasons for having a method like this—because you are using optionals to *avoid* null pointers. There is also not much you can do about it. Are you going to check every line of code from every dependency to see if there’s an exception lurking in there somewhere? If not, you have to accept that your code might take an unexpected path. And when it does, where will it go? If you are currently in function X, it might end up in the catch of function Y, or function Z, or maybe no one will catch it. Do you know for sure what will happen?
## Pure and impure functions
So exceptions make code harder to reason about. The functional programming paradigm has thought long and hard on control flow and reasoning about code. One of its key tenets is that you should prefer *pure functions* in applications.
You might remember from the previous chapter that pure functions are functions without *side effects*, whose output depends solely on the parameters they receive. The following function, which sums its parameters or returns zero, is pure. Give it the same parameters multiple times, and the answer will always be the same:
rust
fn sum_if_big_enough(a: i32, b: i32) -> i32 {
if a > 100 && b > 1000 {
a + b
} else {
0
}
}

Now look at the next function, which calls a database to determine whether to sum the parameters. Because it relies on something outside the function for its output, it is no longer deterministic. Maybe the function returns 0 for arguments 5 and 3 on our first call. Maybe someone changes the database before our second call, and we now get back 8. Maybe the database has problems on our third call and throws an error:

fn sum_if_big_enough(a: i32, b: i32) -> i32 {
if big_enough_according_to_database(a, b) {
a + b
} else {
0
}
}

Because the input no longer determines the output, this is an impure function (i.e., not pure). And it is impure even though it relies on another function (big_enough_according_to_database) to actually talk with the database. When you call an impure function, your function also becomes impure. The taint spreads (see figure 7.1).

7.2 Pure and impure functions

131

[!visual-conversion] Diagram showing pure sum functions consistently returning 9, while impure … Cropped from the scan (PDF page 143, printed p. ?): Diagram showing pure sum functions consistently returning 9, while impure sum functions vary (9, -1, Database error) due to database dependency.

Figure 7.1 Pure functions are consistent and produce the same output for the same parameters. Impure functions are less predictable.

NOTE Manipulating databases is a side effect: an effect that your function has besides returning a result (which is considered the normal effect of your code). Many other common actions are side effects as well, like calls to other systems. The problem is always the same: what your function does depends on the behavior of an external resource. Even a simple thing like logging is a side effect, as it might fail unexpectedly when the operating system is having problems! That being said, logging is one of the safest (least error-prone) side effects. As far as I’m concerned, you can call your function pure if this is the only sneaky thing it does besides returning things.

Pure functions have nice, mathematical properties like referential transparency, which means you can replace a pure function call with its result. This opens the door for optimizations like memoization, a caching of function results, which is easy when the answer is always the same as long as the parameters do not change. That means you can return a cached result when you get parameters you’ve seen before.

There are other qualities that should appeal to programmers. They are easy to reason about because you only need to remember what is happening inside the function. Once we start doing things like calling databases, you need to keep a lot more context in your head. Pure functions are also easy to test, requiring only the most minimal setup, and they are unlikely ever to turn flaky.

Compare this to impure functions like the one from earlier. Reasoning is harder because we need to take into account everything the database might do: return true, return false, throw errors; have connection problems, timeouts, etc. To understand how such a function will behave, we have to dig deep into the underlying functions that it calls, exploring their implementation. Testing also becomes harder because we need mocking or stubbing.

CHAPTER 7 From panic to result: Error handling

Section titled “CHAPTER 7 From panic to result: Error handling”

At this point, you may be wondering why we would ever want impure functions. “Want” is the wrong word, however: we need these functions, because everything useful is a side effect: sending an email to customers, updating a database with the latest orders, etc. So the goal is not to eliminate impurity but rather to limit its impact. If most of our code consists of pure functions, that will make reading and testing most of our functionality easier. Functional programming, with its focus on pure functions, tries to limit impurity by moving side effects to the edge of an application. Hexagonal architecture, similarly, might move side effects to the ports of your application, keeping a “pure” core of business logic in the center.

We have talked about the downsides of breaking control flow with exceptions. But you do need to handle failure paths. So, if not with exceptions, what alternative is there?

One option, available in every language and sometimes seen in the wild, is to use Booleans to signify success or failure. If you need to return a value and your language does not like tuples, just wrap the Boolean and the actual return value in a custom object. While this works, it has several downsides. It is clunky, requiring a lot of conditional checks instead of try-catch blocks, as well as wrapping and unwrapping. Plus, nothing forces you to handle the Boolean you receive. Just ignore it if you want to! At least exceptions were actively stopping you from doing bad things, albeit at run time. (Or partly at compile time in the case of Java’s checked exceptions. These exceptions are hated by developers though, because adding lots of try-catch statements is very clunky, and there is often no good way to handle the checked exception.)

In a variation to the Boolean approach, Go has the convention of returning two values from a call that might fail: a value and an error, with only one of those being present and the other being nil. The convention is good, and it makes Go code easier to understand once you are used to this approach. Seeing errors as ordinary values instead of something exceptional (pun intended) is a good idea as well. But the other problems are still there: boilerplate—all those error nil checks—and no forced handling of the error. Just ignoring the errors is once again a perfectly valid approach but probably not a good idea.

There is another approach, originating largely from the functional programming paradigm. We will focus on a part of that solution, a part that has great support in Rust: algebraic data types (ADTs). Whatever language you currently use, you have some experience with these, because one type of ADT is the product type, which you may know under the name “object” or “struct.” Basically, a product type has a total number of possible “states” equal to the product of its properties. So a struct with two properties, a u8 (which as a number has a total of 256 possible values) and a boolean (two values, either true or false) has 2×256=5122 \times 256 = 512 possible states. That makes sense: a struct with 120 and true is different from one with 119 and true. This large range of values can be a downside. You may need to do a lot of work (e.g., a lot of conditionals) to determine whether the state of a product type matches your requirements.

7.3 Alternatives to exceptions

The other major algebraic data type is the sum type. As the name suggests, here the number of possible states is the sum of its properties (think of the Union type in C). You could see a Boolean as a sum type. It is either true or false—not something in between (see figure 7.2). This sounds like a limitation, but as I have said before, it might prove to be a strength because the restricted number of states makes these types ideal targets for pattern matching. Rust offers a very powerful sum type in the shape of enums. They have properties and methods, plus great pattern-matching support.

A product type, the product of all possible values that the properties might take

Section titled “A product type, the product of all possible values that the properties might take”

plaintext struct Example number_val: u8 boolean_val: bool

↓
```plaintext
Example
number_val: 0
boolean_val: false
Example
number_val: 1
boolean_val: false
Example
number_val: 255
boolean_val: true

and plenty more

enum Example
Num
String
Bool

↓

Example::Num
Example::String
Example::Bool

Figure 7.2 The myriad of options of a product type versus the simplicity of the sum type

But how does all this help us with our error-handling challenge? Well, reformulate the problem at hand: “We need a way to make clear to the developer and type system that the result of this call is either a success or a failure. If it is a success, it should contain the result; if not, an error (message).” Note we said either success or failure—error handling requires a sum type. And enums are ideally suited for that since they can contain properties like a result or error. What we should do is create an enum called

flowchart TD
    S["struct Example<br/>number_val: u8<br/>boolean_val: bool"] --> E1["Example<br/>number_val: 0<br/>boolean_val: false"]
    S --> E2["Example<br/>number_val: 1<br/>boolean_val: true"]
    S --> E3["Example<br/>number_val: 255<br/>boolean_val: true"]
    S -.-> M[and plenty more]

[!visual-conversion] Product-type instantiations Converted from a print product-type diagram (PDF page 145): struct Example (number_val: u8, boolean_val: bool) instantiates to (0, false), (1, true), (255, true), and plenty more.

flowchart TD
    E["enum Example<br/>Num<br/>String<br/>Bool"] --> N[Example::Num]
    E --> S[Example::String]
    E --> B[Example::Bool]

[!visual-conversion] Enum variants Converted from a print enum diagram (PDF page 145): enum Example with variants Num, String, and Bool yields Example::Num, Example::String, and Example::Bool.

CHAPTER 7 From panic to result: Error handling

Section titled “CHAPTER 7 From panic to result: Error handling”

Either, which returns a success or a failure. That, in fact, is the name for this “pattern” in several languages, like Scala and Haskell. For simplicity’s sake, the error message is always a string; the result can be anything you want:

scala enum Either { Success(T), Failure(String), }

If we have a function that returns this `Either`, we have to take into account failures because the answer we seek is wrapped in a variant. Pattern matching is one convenient way to handle all eventualities:
```scala
fn calculate_answer_to_life() -> Either<i32> {
Either::Success(42)
}
fn main() {
match calculate_answer_to_life() {
Either::Success(answer) => {
println!("Got the answer: {}", answer);
}
Either::Failure(_) => {
println!("Should handle failure");
}
}
}

We could add additional convenience methods to make handling the result contained within easier. A map method, for example, manipulates the “success value” if it is present and relies on pattern matching internally (see figure 7.3):

impl<T> Either<T> {
fn map(self, function: fn(T) -> T) -> Either<T> {
match self {
Either::Success(answer) => {
return Either::Success(function(answer))
}
// if it's not a success, no need to do anything
_ => self
}
}
}
fn main() {
let two = Either::Success(1).map(|v| v + 1);
}

And that solves all our problems! We have a type that elegantly encapsulates the result of a function that might fail. It is helpful to the type system, and it forces you to deal with failures. Plus, we can add all kinds of methods that help us transform and use the encapsulated result. There is just one problem: we’ve just reinvented Rust’s Result type.

7.4 Rust’s Result and panics

135

The enum stays the same.

Sum type

Either → map(|v| v + 1) → Either

But we can manipulate the value.

Value

Success(1) → Success(2)

If there is no value, (most) operations are no-op.

Value

Failure(“message”) → Failure(“message”)

Figure 7.3 “What’s in the box?” Manipulating the value

So, yes, this was a long-winded path to “This is why I think Result is pretty neat.” At the center of Rust’s standard library, we have two sum types with a million (bazillion?) use cases. As you know, Result is an enum with either a value (Ok) or an error (Err). This means that your error has now become a value that you can handle and manipulate and the error is embedded in your type system, which will force you to acknowledge that you might have an error. The signature of your function also becomes living documentation: just from seeing Result in the return type, you know that there are failure cases. Suddenly, there’s information on almost every possible place where a failure might occur, and the type system forces you to think about them.

The reader also knows that there is an alternative to Result: just panic! In theory—similar to Go—panic is reserved for situations where you think it is best to stop the program altogether because something that really should not happen happened. A normal failure case is a customer not having enough money in their account or an order being out of stock. Panicking is what you would do if a customer just purchased an order worth infinite dollars. At this point, you may want to stop your application before it starts charging their credit card (or, depending on your moral stance, you could try to charge them as much as possible, I guess). As a more realistic example, consider a server that has just booted and discovers that some of its essential configuration is missing. Since that makes it impossible to do anything useful, panicking becomes a valid course of action.

Panics can also be good for handling situations where you have a good reason to assume something cannot happen. unreachable, for example, can be used for such situations. Another example: within the following function, we call unwrap, which will

[!visual-conversion] Diagram showing manipulation of sum type ‘Either’ with map operation … Cropped from the scan (PDF page 147, printed p. ?): Diagram showing manipulation of sum type ‘Either’ with map operation and value cases Success(1), Success(2), Failure(“message”).

CHAPTER 7 From panic to result: Error handling

Section titled “CHAPTER 7 From panic to result: Error handling”

panic when our character is not a number. But as we just checked that the character is a number, that will never happen:

fn get_digit(ch: char) -> u32 {
if char::is_digit(ch, 10) {
return char::to_digit(ch, 10).unwrap()
}
0
}

In “real” code, it would be wise to switch over to expect and add a message about why you think the panic should never happen (expect("value to be digit since we checked with is_digit")). That way, when something does go wrong, tracking down the problem becomes easier, plus the expect message also serves as a bit of documentation. And it allows you to think deeply about your invariants.

unwrap and expect are also useful when you are writing a POC or a quick script or doing some exploratory work—any time you are experimenting and do not want proper error handling to get in the way. When and if you have to improve that aspect of your code, do a search for unwrap and expect and get busy! Besides using these two methods, you can use panic and variants like unimplemented to handle unforeseen situations in exploratory code. In the code in the following listing, we simply panic when we receive invalid arguments.

Listing 7.1 A function that panics when validation fails

Section titled “Listing 7.1 A function that panics when validation fails”
fn create_person(name: String, age: i32) -> Person {
if name.len() < 2 {
panic!("name should be at least three characters long!")
} else if age > 30 {
panic!("I hope I die before I get old");
}
Person {
name,
age,
}
}

Most of those panics should disappear once you get serious with your code. An unreachable still has its place, but the validation of input should be done with Result. If you’ve used a lot of panic in your code, that might be a boring refactor, though, which is our motivation to write a macro that can do this for us. Whenever it finds a panic, it will replace it with Result.

NOTE This example should not be taken too seriously. It showcases how macros can alter functions and how to give feedback to users. In some rare real use cases, it may even prove useful. But simply rewriting the code to get rid of its panics is obviously preferable.

7.5 Setup of the panic project

Because we are changing existing code, we can’t go for a derive macro. But an attribute macro can work with functions and change code, so that’s ideal.

This chapter takes a middle ground between the simple setup with one subdirectory from earlier chapters and the more complex builder setup with three subdirectories. Instead, we now have two subdirectories: one with the macro and one with the code for verifying our code (see figure 7.4).

Figure 7.4 Avoiding both extremes, we have realized the middle path.

So, to start, we will create a panic-to-result-usage directory and a panic-to-result-macro directory. The first is an executable; the second is a library.

[package]
name = "panic-to-result-macro"
version = "0.1.0"
edition = "2021"
[dependencies]
quote = "1.0.33"
syn = { version = "2.0.39", features = ["full", "extra-traits"] }
[lib]
proc-macro = true

Listing 7.3 Dependencies for the application’s toml

Section titled “Listing 7.3 Dependencies for the application’s toml”
[dependencies]
panic-to-result-macro = { path = "../panic-to-result-macro" }

Next we have the first (dummy) version of the macro code, which takes the incoming tokens and returns them.

[!visual-conversion] Directory structure diagram showing panic-to-result (directory) with subdirectories panic-to-result-usage (application) … Cropped from the scan (PDF page 149, printed p. ?): Directory structure diagram showing panic-to-result (directory) with subdirectories panic-to-result-usage (application) and panic-to-result-macro (library), with application using macro from library.

CHAPTER 7 From panic to result: Error handling

Section titled “CHAPTER 7 From panic to result: Error handling”
use proc_macro::TokenStream;
use quote::{ToTokens};
use syn::ItemFn;
#[proc_macro_attribute]
pub fn panic_to_result(_a: TokenStream, item: TokenStream) -> TokenStream {
let ast: ItemFn = syn::parse(item).unwrap();
ast.to_token_stream().into()
}

This trait gives us the to_token_stream method, which we use later.

Uses parse with type ItemFn to get the function stream

Turns the result into a standard TokenStream

Using parse instead of parse_macro_input is a slight variation. We now need to use ItemFn as the return type, because we are working with functions, which makes DeriveInput and similar types an ill fit. This is the reason why the “full” feature of syn is required, because ItemFn is not available by default (perhaps because macros for structs/enums are more popular macro targets). Another variation is that we use to_token_stream to return a stream, which we convert into a standard TokenStream with Into.

Our main.rs in the “usage” directory already has some basic code and tests that verify the current behavior of our panic-prone create_person function. To keep things simple, the function only has validation on the age field, panicking if it gets a value over 30.

Listing 7.5 Application code (usage directory) with tests for create_person

Section titled “Listing 7.5 Application code (usage directory) with tests for create_person”
use panic_to_result_macro::panic_to_result;
#[derive(Debug)]
pub struct Person {
name: String,
age: u32,
}
#[panic_to_result]
fn create_person(name: String, age: u32) -> Person {
if age > 30 {
panic!("I hope I die before I get old");
}
Person {
name,
age,
}
}
fn main() {}
#[cfg(test)]
mod tests {
use super::*;

This is the example function we will be using to test our macro.

7.6 Mutable or immutable returns

#[test]
fn happy_path() {
let actual = create_person("Sam".to_string(), 22);
assert_eq!(actual.name, "Sam".to_string());
assert_eq!(actual.age, 22);
}
#[test]
#[should_panic]
fn should_panic_on_invalid_age() {
create_person("S".to_string(), 32);
}

This test verifies that the function only works for people younger than 30.

We will work on the implementation before investigating macro errors properly. Our current situation is a bit more complicated than those of previous chapters. When we were doing derives, all we needed from the original input was a bit of handpicked information for generating entirely new code. And our attribute macro for the public fields macro was only slightly more complicated. Yes, we had to reconstruct the original struct with every field set to public, but that was relatively simple because struct definitions often don’t contain all that much of interest besides fields. After all, a lot of stuff is added via implementation blocks.

But now we will be working with a function, changing the signature, and meddling with part of its content—which means we are back to this conundrum: what is the best way to create our output when it replaces the input? We have already seen that we can take the original object, or a clone, and give that back. But since functions are a bit more complex when it comes to content, the easier solution here is mutating the existing function, changing what we want, and then returning everything as an output. In other languages, mutability has downsides due to being more error prone. But, thanks to the Rust compiler, mutability is quite safe here.

As an example, the following is some code to make a function public. We make our AST mutable, and then we can change the visibility (vis) to public (Visibility::Public):

// other imports
use syn::{ItemFn, Visibility};
#[proc_macro_attribute]
pub fn panic_to_result(_a: TokenStream, item: TokenStream) -> TokenStream {
let mut ast: ItemFn = syn::parse(item).unwrap();
ast.vis = Visibility::Public(Default::default());
ast.to_token_stream().into()
}

We set the abstract syntax tree to be mutable.

The visibility of ast is changed—in place—to public. Default makes it easy to generate the boring pub_token (which literally contains pub).

At this point, the immutable approach is not that much more complicated. We just create a new ItemFn and add the visibility. Because we would like everything else to

CHAPTER 7 From panic to result: Error handling

Section titled “CHAPTER 7 From panic to result: Error handling”

remain unchanged, we are spreading the existing struct, which will fill in the existing properties while overriding the ones we defined ourselves (i.e., vis):

// other imports
use syn::{ItemFn, Visibility, VisPublic};
#[proc_macro_attribute]
pub fn panic_to_result(_a: TokenStream, item: TokenStream) -> TokenStream {
let ast: ItemFn = syn::parse(item).unwrap();
let new_ast = ItemFn {
vis: Visibility::Public(Default::default()),
..ast
};
new_ast.to_token_stream().into()
}

Creates a new ItemFn that has public visibility, taking all other functionality from the existing function, which we are spreading

While this is a viable alternative, it requires a bit more boilerplate. And in this particular example, it might also be confusing to have both an ast and new_ast. I can easily see myself changing the first and expecting that to effect a change in the generated code. Finally, the immutable approach seems a bit redundant: in both the immutable and mutable approaches, we are replacing the input with the output. The end result is the same, and internal mutation is generally safe.

DEFINITION By internal mutation, I mean any mutation that has no visible effect outside its function. An example would be a counter (let mut counter...) that never leaves the function (is not returned, not saved in a database, etc.). This kind of mutation is not very harmful because the limited scope means the code makes it less error prone and easier to understand. And since everything is internal to the function, parallelization will—probably—not cause additional, weird bugs to rear their ugly heads. The inverse of internal mutation is a global mutable variable, like the ones you might encounter in JavaScript or Python. The scope of a global variable is huge (possibly the entire program), and all objects and functions can change its value: a proper nightmare. Read-only global variables avoid these problems by not being mutable. In between these extremes are mutable values that are passed to and from functions. These are not as harmful as global mutable variables but are still dangerous in the wrong circumstances.

Let’s get back to the task at hand: a macro that replaces panics with results. Let’s do this step by step. First, we will make our function return a Result. For the error type, we will go with a simple string. The value will have to match the current return type of the function. Once we have changed the signature, the final expression—currently returning a person—will have to be wrapped in an ok. We will ignore more complex situations with multiple possible return expressions. The good thing is that nothing is keeping us from making these changes and still having a panic in our function—meaning we can leave replacing that for later in this chapter.

7.7 Getting results

If we look at ItemFn, we can see that the sig property is hiding the signature information (see figure 7.5). One level deeper, output contains what is returned. And ReturnType is not that complex. It is either the default (when the function returns “nothing,” though in practice it will still return a unit, ()) or an arrow followed by the actual type:

pub enum ReturnType {
Default,
Type(Token![->], Box<Type>),
}

Figure 7.6 shows how we go from ItemFn to ReturnType.

Figure 7.5 Parts of a function with their ItemFn names

Figure 7.6 Drilling down into ItemFn

What we want to do is to change the output to Result<(), String> when there is no return type, or set it to Result<OriginalReturnType, String> when we have a type. With quote and a bit of thinking, that’s not too hard to do.

Listing 7.6 Changing the signature

let output = match ast.sig.output {
ReturnType::Default => {
![](assets/wpm-fig-8-06-diagram-showing-itemfn-signature-and-returntype-with.png)
> [!visual-conversion] Diagram showing ItemFn, Signature, and ReturnType with arrows to Attribute, …
> Cropped from the scan (PDF page 153, printed p. ?): Diagram showing ItemFn, Signature, and ReturnType with arrows to Attribute, Visibility, and Block Vec<Stmts>.
<!-- page: 154 -->
quote! {
-> Result<(), String>
}
ReturnType::Type(_, ty) => {
quote! {
-> Result<#ty, String>
}
};
ast.sig.output = syn::parse2(output).unwrap();
We match on sig.output, which is either a default (with an explicit -> () signature or an ellipse of the signature) or a type. In the first case, we have an empty return value that needs to be put in a Result. So we create a signature for that: -> Result<(), String>. (As we mentioned, we will be using String as an error.)
The other case is only slightly more complicated: we have to get the real type, ty, and add it to our TokenStream. You can also use ref to get a reference to the type instead of the actual value, but that's not required.
Next, we use parse2 to do the hard work for us, converting our tokens into the ReturnType. As usual, parse2 knows what the return type should be because it has to match the type of the output field. Would it be annoying to do this without quote? See for yourself. Here is what the tokens for -> Result<Person, String> look like (with some properties left out for conciseness):
Type(
RArrow,
Type::Path {
path: Path {
segments: [
PathSegment {
ident: Ident { ident: "Result" },
arguments: PathArguments::AngleBracketed {
args: [
GenericArgument::Type(
Type::Path {
path: Path {
segments: [
PathSegment {
ident: Ident {
ident: "Person"
}
}
],
},
},
),
GenericArgument::Type(
Type::Path {
path: // path for "String"
},
),
],
},
},
],
},
},
)
If we have a default signature, the value is the unit type ().
Otherwise, we have a type, and we should put that inside Result.
We can use parse2 to turn the TokenStream into the proper type.
<!-- page: 155 -->
7.7 Getting results
That "Person" identifier in there is our ty. So we get that one for free. But all the other stuff we would have to write ourselves. It’s doable, but it is also a *lot* of boilerplate code. `quote` makes it easier to both write and read this bit of code.
Now our return value should become a `Result`. This time we have to go looking in `block`, which contains the actual function code, and retrieve the statements inside the function. For this particular function (which has no early returns, etc.), we only need the final statement, so we pop it (removing it from the vector), wrap it in an `Ok`, and put the result back in the vector.
### Listing 7.7 Changing the return value
rust
use proc_macro::TokenStream;
use quote::{quote, ToTokens};
use syn::{ItemFn, ReturnType, Stmt};
#[proc_macro_attribute]
pub fn panic_to_result(_a: TokenStream, item: TokenStream) -> TokenStream {
let mut ast: ItemFn = syn::parse2(item).unwrap();
let output = // code for changing the signature
ast.sig.output = syn::parse2(output).unwrap();
let last = ast.block.stmts.pop().unwrap(); // Removes the last statement from the function
let last_modified = quote! {
Ok(#last)
}; // Modifies it by wrapping it inside an Ok
let last_modified_as_expr = Stmt::Expr(
syn::parse2(last_modified).unwrap(),
None
); // Parses the token stream we created as an expression (which is a variant of the statement enum) with no semicolon
ast.block.stmts.push(last_modified_as_expr); // And pushes it to the back of the function statements
ast.to_token_stream()
}

As you can see, putting the result back in the block is slightly more complex than retrieving the statement. The simplest way to do it would be to push the parse result. Sadly, that fails with unexpected end of input, expected semicolon. Digging down into the source code, the reason becomes clear: stmts is a vector of Stmt and the Parse implementation of Stmt does not allow statements without a semicolon. Instead, we have to give Rust some more context and tell it that this is a specific variant of a statement, an expression. And as our (the function’s final) expression does not end in a semicolon, we pass in None as the second optional, representing that missing semicolon.

If you happen to be using major version 1 of syn, this code will not compile, because two variants (Semi and Expr) were merged in version 2. In this particular case, the change is easy, though: just leave out the None.

Listing 7.8 Stmt source code in versions 1 and 2

Section titled “Listing 7.8 Stmt source code in versions 1 and 2”
// syn version 1
pub enum Stmt {
Local(Local),
Item(Item),
Expr(Expr),
Semi(Expr, Token![;]),
}
// syn version 2
pub enum Stmt {
Local(Local),
Item(Item),
Expr(Expr, Option<Token![;]>),
Macro(StmtMacro),
}

Now our happy path test is failing because we return a Result instead of a Person. Perfect! Adding an unwrap is a good solution to fix the test because if we don’t get the expected Person, this will panic and cause the test to fail.

#[test]
fn happy_path() {
let actual = create_person("Sam".to_string(), 22).unwrap();
assert_eq!(actual.name, "Sam".to_string());
assert_eq!(actual.age, 22);
}

Now how about some refactoring? We can move parts of our implementation into separate functions. If you want to clean up even more, you can also move functions to separate files. But this will do for now.

Listing 7.10 Functions for changing the signature and the return value

Section titled “Listing 7.10 Functions for changing the signature and the return value”
// imports
fn signature_output_as_result(ast: &ItemFn) -> ReturnType {
let output = match ast.sig.output {
ReturnType::Default => {
quote! {
-> Result<(), String>
}
}
}
}
<!-- page: 157 -->
7.8 Don't panic
rust
}
ReturnType::Type(_, ref ty) => {
quote! {
-> Result<#ty, String>
}
};
syn::parse2(output).unwrap()
}
fn last_statement_as_result(last_statement: Option<Stmt>) -> Stmt {
let last_unwrapped = last_statement.unwrap();
let last_modified = quote! {
Ok(#last_unwrapped)
};
Stmt::Expr(syn::parse2(last_modified).unwrap(), None)
}
#[proc_macro_attribute]
pub fn panic_to_result(_a: TokenStream, item: TokenStream) -> TokenStream {
let mut ast: ItemFn = syn::parse(item).unwrap();
ast.sig.output = signature_output_as_result(&ast);
let last_statement = ast.block.stmts.pop();
ast.block.stmts.push(last_statement_as_result(last_statement));
ast.to_token_stream().into()
}

We now have a bit of nice, readable code that transforms the return type and value of the function. But the panic is still, well, a panic. We still need to replace it with an Err.

Getting rid of the panic is more complex than changing the final statement in our body: this time we can’t just pop a statement because we don’t know where the panic is hiding. So for a general solution, we would have to loop over all statements to see if they contain a panic. In this section, however, we will write code for retrieving panic from an if statement, leaving some implementation for the exercises.

We will iterate over the statements in our block and use map with a separate function to transform expressions. Statements that are not expressions will just pass through the mapping. Once the iteration is done, we replace the existing block statements with our new ones.

Listing 7.11 Code fragment from lib.rs for mapping statements

let new_statements: Vec<Stmt> = ast.block.stmts
.into_iter()
.map(|s| match s {
<!-- page: 158 -->
# CHAPTER 7 From panic to result: Error handling
rust
Stmt::Expr(e, t) => handle_expression(e, t),
_ => s,
})
.collect();
ast.block.stmts = new_statements;

We will map all expressions to new statements via a custom function.

But any other kind of statement will just be returned.

Finally, we assign the new and the unchanged statements to the block.

The reason we focus on expressions is that if is an expression, and we know the panic is in there. If we wanted to find every possible panic, we would also have to handle Semi (statements that end with a semicolon).

Now let’s move on to the transformation of all the other expressions in handle_expression, where we look for panics and change them to results.

Listing 7.12 Transforming an expression from panic to error

Section titled “Listing 7.12 Transforming an expression from panic to error”
fn handle_expression(expression: Expr, token: Option<Semi>) -> Stmt {
match expression {
Expr::If(mut ex_if) => {
let new_statements: Vec<Stmt> = ex_if.then_branch.stmts
.into_iter()
.map(|s| match s {
Stmt::Macro(ref expr_macro) =>
extract_panic_content(expr_macro)
.map(|t| quote! {
return Err(#t.to_string());
})
.map(syn::parse2)
.map(Result::unwrap)
.unwrap_or(s),
_ => s
})
.collect();
ex_if.then_branch.stmts = new_statements;
Stmt::Expr(Expr::If(ex_if), token)
},
_ => Stmt::Expr(expression, token)
}
}

We are only interested in if expressions.

We go through the statements in the then_branch, and, if we find a macro, we check whether it’s a panic.

And in if expressions, we only want to check macros.

If it is a panic, we map it to a Result.

We update the statements in the if/then branch and rewrap as an expression, passing along the optional semicolon.

In all other cases, we rewrap the expression and token.

We know the if is panicking, so we are only matching on that one variant (see listing 7.14), simply returning all other statements. In a more generic case, we would have to greatly extend the number of match “arms” to handle things like loops, whiles, yields, and the like.

Next, we search for macro statements inside the conditional (Stmt::Macro). At that point, the helper, extract_panic_content, which we will discuss momentarily, can be used to give back an option with the panic’s message—or none if the macro was not a panic. Once we have the message, we use it to replace the panic with an Err containing the original message. As before, we use parse to get back the right type, a statement, which Rust can infer because we specified the result should be Vec<Stmt>.

DEFINITION The shorthands map(syn::parse2) and map(Result::unwrap) are called point-free style in functional lingo. Java calls them method references. This saves us some typing and is quite readable: “Take the (one) parameter you receive and use it to call this function.”

If no panic was present, we instead return the statement and add it to our list. Once our iteration is finished, we replace the existing statements with our new ones, which are the ones we already had, except that the panic has been transformed into a Result. Finally, we have to wrap everything in our original structure: an if expression inside an expression.

This is another piece of code that would behave differently on the first major of syn (although you should be using version 2). For one, we would not have to pass around optional tokens in version 1. Bigger changes are required for the match inside map, because back then macros were a Expr::Macro inside a “semi” (a statement ending with a semicolon) or expression.

Stmt::Semi(Expr::Macro(ref expr_macro), _) =>
extract_panic_content(expr_macro)
// ...

Listing 7.14 Stmt’s variant Expr, another enum

Section titled “Listing 7.14 Stmt’s variant Expr, another enum”
pub enum Expr {
Array(ExprArray),
// ...
If(ExprIf),
// ...
Macro(ExprMacro),
// ...
}

In all other cases, except the one we just discussed, we just return the original statement without any changes.

The extract_panic_content function is relatively simple. It looks for an identifier matching the string “panic” inside the macro. If we have a panic, we get the input from tokens, clone it, and give it back.

Listing 7.15 Helper for determining if the macro is a panic

Section titled “Listing 7.15 Helper for determining if the macro is a panic”
fn extract_panic_content(expr_macro: &StmtMacro) ->
Option<proc_macro2::TokenStream> {
let does_panic = expr_macro.mac.path.segments.iter()
.any(|v| v.ident.to_string().eq("panic"));
if does_panic {
Some(expr_macro.mac.tokens.clone())
} else {
<!-- page: 160 -->
# CHAPTER 7 From panic to result: Error handling
None
}
}
This time around, our failure path test has to change. It now expects an `Err` instead of a panic.
## Listing 7.16 Fixing the unhappy path test
rust
// happy path unchanged
#[test]
fn should_err_on_invalid_age() {
let actual = create_person("S".to_string(), 33);
assert_eq!(
actual.expect_err("this should be an err"),
"I hope I die before I get old".to_string()
);
}

We changed the name of the test and removed the should_panic annotation.

We have now successfully enhanced our function with proper error handling!

While writing this code, I bumped into an annoying problem that I spent way too much time staring at. I was refactoring this part of the code:

extract_panic_content(expr_macro)
.map(|t| quote! {
Err(#t.to_string())
})
.map(syn::parse2)
// ...
}

But I kept getting the following error:

10 | #[panic_to_result]
| ^^^^^^^^^^^^^^^^^^^ cannot infer type of the type parameter `T` declared on the enum `Result`
|
= note: this error originates in the attribute macro `panic_to_result` (in Nightly builds, run with -Z macro-backtrace for more info)
help: consider specifying the generic arguments
|
10 | #[panic_to_result]::<T, String>
|
++++++++++++++

I figured it had something to do with the Result that was returned by parse2 and Rust somehow not being able to guess the correct types. But a cargo check of the macro code worked fine. This was a vital clue that I was looking in the wrong place because

Rust can verify your macro library but not the code you generate. You can put any nonsense in there, and you will only notice when compiling a project that actually uses the macro, not during the compilation of the macro itself.

So, finally, I took a look at cargo expand and had Rust / IntelliJ show me the problem: I had written Err(#t.to_string()); without a return. Without that return, Err(#t.to_string()); was an ordinary statement. But Rust needs to know what type it is, and all it can guess from this piece of code is the value of the error (E), a string, but not the return type (T). As it has no idea what the value should be, the compiler is asking us what T should be. Once you add the return, Rust knows that the Result value and error should match those in the signature. Lesson learned: carefully read your error message (which was pointing to the correct Result) and think about what cargo check and cargo expand tell you about the error(s).

While the aforementioned solution is only a partial one, it is sufficient for now because it’s really time we get started with the chapter’s main topic: error reporting. On the other hand, right now, our macro has only a few error cases except for the occasional unwrap for parsing. To make things interesting, we will add some additional error cases.

For example, it makes sense that our macro should only work for functions that do not yet return Result. The most important reason is extra complexity: we want to return a Result with a string for the error type. What if the existing Result has a different type? Instead of figuring out how to handle that, we will give back a nice error when someone tries to inappropriately use our macro. To verify that the return type is not a Result already, we add a simple check to verify that this type is not present in the function’s signature.

Listing 7.17 Panicking when the return type is Result

Section titled “Listing 7.17 Panicking when the return type is Result”
fn signature_output_as_result(ast: &ItemFn) -> TokenStream {
match ast.sig.output {
// default return code...
ReturnType::Type(_, ref ty) => {
if ty.to_token_stream().to_string().contains("Result") {
unimplemented!("cannot use macro on a function with Result as return type!");
}
Ok(quote! {
-> Result<#ty, String>
})
}
}
}

Right now, this is still poor man’s error handling, throwing a panic. We will get to that. But first, we should verify that the function fails.

Listing 7.18 An example function that should fail (add this to main.rs for now)

Section titled “Listing 7.18 An example function that should fail (add this to main.rs for now)”
#[panic_to_result]
fn create_person_with_result(name: String, age: u32)
-> Result<Person, String> {
if age > 30 {
panic!("I hope I die before I get old");
}
Ok(Person {
name,
age,
})
}

Same function as before, with a different return type and name

If you now run cargo check in panic-to-result-usage, you get an error similar to the following:

error: custom attribute panicked
--> src/main.rs:21:1
|
21 | #[panic_to_result]
| ^^^^^^^^^^^^^^^^^^^
|
= help: message: not implemented: Cannot use macro on a function with Result as return type!

It’s an okay message, and the user might understand it. But this is definitely less beautiful and helpful than the built-in messages. And it just points to the macro. Pointing to the signature would make more sense. There are alternatives that give better results.

First up is syn error handling, which requires changes to both signature_output_as_result and our panic_to_result entrypoint.

Listing 7.19 syn error handling (partial code from lib.rs)

Section titled “Listing 7.19 syn error handling (partial code from lib.rs)”
// other imports
use syn::spanned::Spanned;
fn signature_output_as_result(ast: &ItemFn)
-> Result<ReturnType, syn::Error> {
let output = match ast.sig.output {
// default return code...
ReturnType::Type(_, ref ty) => {
if ty.to_token_stream().to_string().contains("Result") {
return Err(
syn::Error::new(
ast.sig.span(),
"this macro can only be applied to a function that does not return a Result. Signature: {}",
),
);
}
}
};
Ok(output)
}

We need this trait to be in scope if we want to call span().

syn::Error requires a span…

<!-- page: 163 -->
7.9 Error-handling flavors
rust
quote!(#ty)
)
);
}
quote! {
-> Result<#ty, String>
}
};
Ok(syn::parse2(output).unwrap())
}
#[proc_macro_attribute]
pub fn panic_to_result(_a: TokenStream, item: TokenStream) -> TokenStream {
// other code
match signature_output_as_result(&ast) {
Ok(output) => ast.sig.output = output,
Err(err) => return err.to_compile_error().into()
};
// other code
}

… and a message, which we build using format, passing along the faulty signature

When we get back an Ok, everything is the same as before. When we receive an error, we convert it to a stream and return early.

Our signature_output_as_result now returns an Err if the signature contains a Result. Inside that, Err is a value of type syn::Error. The constructor of that error type requires us to pass back a span and a message (which should implement Display). We’ve encountered span before and noted how it points back to the original code. That might finally be useful! One idea is to pass the span of sig, allowing Rust to point to the signature. In the message, we give some information about what we found plus the current signature as a reference. As usual, we use quote, which format! will automatically add to the string for us.

But we still have to do something with the Result that signature_output_as_result is returning. And, unlike main functions that can return a unit or a Result, a proc-macro can only return a TokenStream. So we do a match. If everything is okay, we proceed as before by adding the new signature to our AST. If we have an error, we convert it into a compile error (a proc_macro2::TokenStream) and into a standard stream.

Now we get a better error message in our application:

error: this macro can only be applied to a function that does not return a Result. Signature: Result < Person, String >
--> src/main.rs:22:1
|
22 | fn create_person_with_result(name: String, age: u32)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| fn create_person_with_result(name: String, age: u32)
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
|
| -> Result<Person, String> {
|
| ^^

This is more informative than the previous message. We’re pointing the user to where the problem occurs, the signature (which starts with fn), and telling them exactly what is wrong.

Let’s use our new syn error for a second example. We’ve found it useful to transform existing panics into an Err with a message. But what if there is no message to add? Well, our current code will panic if we don’t have a message. Great. We can test by adding another function that will fail to compile. You can either disable the other failing example or add trybuild and move it into a compilation test.

#[panic_to_result]
fn create_person_with_empty_panic(name: String, age: u32) -> Person {
if age > 30 {
panic!(); // Empty panic, which will provoke a compilation failure.
}
Person {
name,
age,
}
}

We should return a useful error when we encounter that situation instead of a vague custom attribute panicked.

Listing 7.21 Handling empty panic content (partial code from lib.rs)

Section titled “Listing 7.21 Handling empty panic content (partial code from lib.rs)”
// imports
fn handle_expression(expression: Expr, token: Option<Semi>)
-> Result<Stmt, syn::Error> {
match expression {
Expr::If(mut ex_if) => {
let new_statements: Result<Vec<Stmt>, syn::Error> = ex_if
.then_branch.stmts.into_iter()
.map(|s| match s {
Stmt::Macro(ref expr_macro) => {
let output = extract_panic_content(expr_macro);
if output.map(|v| v.is_empty()).unwrap_or(false) {
Err(syn::Error::new(
expr_macro.span(),
"please make sure every panic \
in your function has a message"
))
} else {
Ok(extract_panic_content(expr_macro)
// code to change panic to result
)
}
}
_ => Ok(s)
})
.collect();

We check whether we have an option with empty content. If so, we return an error.

This code is now wrapped in an Ok but otherwise unchanged.

<!-- page: 165 -->
# 7.9 Error-handling flavors
rust
ex_if.then_branch.stmts = new_statements?; ← We now have a Result instead of a Vec, so we use ? to get to the value (if it's present).
Ok(Stmt::Expr(Expr::If(ex_if), token))
}
_ => Ok(Stmt::Expr(expression, token))
}
#[proc_macro_attribute]
pub fn panic_to_result(_a: TokenStream, item: TokenStream) -> TokenStream {
// ...
let new_statements: Result<Vec<Stmt>, syn::Error> = ast.block.stmts
.into_iter()
.map(|s| match s {
Stmt::Expr(e) => handle_expression(e),
_ => Ok(s),
})
.collect();
match new_statements {
Ok(new) => ast.block.stmts = new,
Err(err) => return err.to_compile_error().into()
}
// ...
}

Similar to before, we match on the Result and create an error token stream if we have an error.

That is a lot of minor changes. In handle_expression, we now return a Result, so we’ve added a lot of Ok wrappers. We have also extended the macro check: when we get back the optional value from is_panic, we now check whether the content we received is empty. If it is, we return a syn::Error with a fitting message, and we use the span of the macro to point the user to the relevant panic. Since our new_statements are now a Result, we return early if there is an error using ?. Otherwise, we have our statements and can re-add them to the function.

Another cool Rust feature makes its appearance in the previous code. As you can see, we map over statements and return a Result for each one. That means our output should be Vec<Result<Stmt, syn::Error>>. But the output type I defined for new_statements in handle_expression is Result<Vec<Stmt>, syn::Error>! In the functional world, this is called traverse, which allows stacking your enums (actually, monads, but let’s not get into that) in different ways. The reason this works in Rust is that there is a generic FromIterator implementation for Result for values that turn into something that also implements FromIterator, like a vector.

The details are not important, but you should grasp that this is very convenient. I don’t have to unwrap all the results myself. Instead, I get either an error or a list of statements. To be fair, the two are not entirely equivalent: there is no room for multiple errors in Result<Vec<Stmt>, syn::Error>, meaning every error but the first one will be discarded. To gather all the errors, you would need something like a vector. And preferably you would wrap that vector in some custom struct and make that implement std::error::Error, as any good error type should (even if it’s not strictly required).

In panic_to_result new_statements is now a Result<Vec<Stmt>, syn::Error>. So we transform the error into a token stream and give it back or continue processing if everything is okay. If we now run our faulty function, we get back a new kind of error:

error: please make sure every panic in your function has a message —> panic-to-result-usage/src/main.rs:13:9 | 13 | panic!(); | ^^^^^^

We are pointing to the correct line and the failing statement, with a clear error message. If you want, you can add some extra context:

Err(syn::Error::new( e.span(), format!(“please make sure every panic in your function
has a message, check: {}”, quote!(#statement)) ))

error: please make sure every panic in your function has a message, check: if age > 30 { panic! () ; } —> panic-to-result-usage/src/main.rs:13:9 | 13 | panic!(); | ^^^^^^

If our user still can’t find the problem, they only have themselves to blame! The only downside with this code is that if the user makes multiple mistakes, there will only be a warning for one of them. Though it requires a bit of extra work, we can use the combine method to fix that.

Listing 7.22 Using combine for reporting multiple errors

Section titled “Listing 7.22 Using combine for reporting multiple errors”

// imports and other functions

#[proc_macro_attribute] pub fn panic_to_result(_a: TokenStream, item: TokenStream) -> TokenStream { // … let signature_output = signature_output_as_result(&ast); let statements_output: Result<Vec, syn::Error> = // unchanged

match (statements_output, signature_output) {
(Ok(new), Ok(output)) => {
ast.block.stmts = new;
ast.sig.output = output;
},
(Ok(_), Err(signature_err)) => {
return signature_err.to_compile_error()
.into()
},
(Err(statement_err), Ok(_)) => {
return statement_err.to_compile_error()
.into()
}
}

}

We match on both of our results.

If everything is okay, we can assign to the statements and output.

If we get one error, we give it back.

7.9 Error-handling flavors

},
(Err(mut statement_err), Err(signature_err)) => {
statement_err.combine(signature_err);
return statement_err.to_compile_error()
.into()
}
};
// popping and creating the output
}

And if we have two errors, we combine them.

First, a minor change: we have moved the signature output above the statement iteration. This is an easy way to avoid a partial move problem with ast.block. (In an earlier version, our work with block was done by the time we started handling the signature, hence why we didn’t have problems before.)

Instead of handling the statements and signature separately, we now check their combined outputs in a match arm, which will allow us to take action when we have multiple errors. We handle the happy path by mutating the AST. Separate errors are also handled in the same way as before, by returning the one error. The final match is for when we have two errors. If that is the case, we combine them before returning. Now when you create a function that returns a Result and has an empty panic, you will get two errors in one go.

7.9.2 Using proc_macro_error for error handling

Section titled “7.9.2 Using proc_macro_error for error handling”

Our error handling has clearly improved thanks to syn::Error. Can we do even better? Maybe! And that’s thanks to proc_macro_error (http://mng.bz/Adxe). First, add proc-macro-error = "1.0.4" to our panic-to-result-macro. Next, we need to add an attribute to our macro, as in the following listing.

Listing 7.23 Adding the extra attribute macro to our public lib.rs function

use proc_macro_error::proc_macro_error; // Imports the error macro
#[proc_macro_error] // Annotates our function with the error macro
#[proc_macro_attribute]
pub fn panic_to_result(_a: TokenStream, item: TokenStream) -> TokenStream {
// ...
}

If you don’t do this, you will get an error with a helpful message: proc-macro-error API cannot be used outside of entry_point invocation, perhaps you forgot to annotate your #[proc_macro] function with #[proc_macro_error]. And now we are ready to use the macros (yes, it’s turtles stacked on turtles) that this crate gives us. First up is abort!. This one allows us to pass in a syn struct, from which a span will be taken, as well as several useful messages. We will refactor our handle_expression function. Instead of returning a Result, it will now abort on a missing panic message.

Listing 7.24 Aborting (some unchanged functions not shown)

Section titled “Listing 7.24 Aborting (some unchanged functions not shown)”
// other imports
use proc_macro_error::{abort};
fn handle_expression(expression: Expr, token: Option<Semi>) -> Stmt {
match expression {
Expr::If(mut ex_if) => {
let new_statements: Vec<Stmt> = ex_if.then_branch.stmts
.into_iter()
.map(|s| match s {
Stmt::Macro(ref expr_macro) => {
let output = extract_panic_content(expr_macro);
if output.map(|v| v.is_empty()).unwrap_or(false) {
abort!(
expr_macro,
"panic needs a message!".to_string();
help =
"try to add a message: \
panic!(\"Example\".to_string())";
note =
"we will add the message to Result's Err"
);
} else {
// continue
}
}
_ => s
})
.collect();
// return statement
}
_ => Stmt::Expr(expression, token)
}
}
#[proc_macro_error]
#[proc_macro_attribute]
pub fn panic_to_result(_a: TokenStream, item: TokenStream) -> TokenStream {
// ...
let new_statements = ast.block.stmts
.into_iter()
.map(|s| match s {
Stmt::Expr(e, t) => handle_expression(e, t),
_ => s,
})
.collect();
ast.block.stmts = new_statements;
// ...
}

You can see how abort allows us to do all kinds of things, like adding a help and note, separated by semicolons, in addition to the message. The resulting error applied to our empty panic function looks pretty neat. We are really doing our best to be helpful.

<!-- page: 169 -->
7.9 Error-handling flavors
157
(Aside: As you can see from the location of the fail, I’ve moved my test function with the empty panic to the tests directory):
error: panic needs a message!
= help: try to add a message: panic!("Example".to_string())
= note: we will add the message to Result's Err
--> tests/fails/create_person_with_empty_panic.rs:13:9
13 | panic!();
| ^^^^^^^^^
But we could go a step further—why not give feedback on all possible problems? For that, we will need `emit_error!`. The difference between these two is that `abort` stops processing, whereas `emit_error` allows you to keep looking for problems, similar to what `combine` allowed us to do for `syn` errors but with less work involved. Let’s use this one for both the empty panic and the faulty signature.
### Listing 7.25 Using emit_error (partial, two unchanged functions not shown)
rust
//imports
fn signature_output_as_result(ast: &ItemFn) -> ReturnType {
let output = match ast.sig.output {
// default return
ReturnType::Type(_, ref ty) => {
if ty.to_token_stream().to_string().contains("Result") {
emit_error!(ty,
format!(
"this macro can only be applied to a function \
that does not yet return a Result. Signature: {}",
quote!(#ty)
)
);
ast.sig.output.to_token_stream()
} else {
quote! {
-> Result<#ty, String>
}
}
}
};
syn::parse2(output).unwrap()
}
fn handle_expression(expression: Expr, token: Option<Semi>) -> Stmt {
match expression {
Expr::If(mut ex_if) => {
let new_statements: Vec<Stmt> = ex_if.then_branch.stmts
.into_iter()
.map(|s| match s {
Stmt::Macro(ref expr_macro) => {
let output = extract_panic_content(expr_macro);

The signature already contains Result, so we emit an error, with ty for the span and a helpful message.

But we want to continue processing, so we return the existing signature (output).

CHAPTER 7 From panic to result: Error handling

Section titled “CHAPTER 7 From panic to result: Error handling”
if output.map(|v| v.is_empty()).unwrap_or(false) {
emit_error!(
expr_macro,
"panic needs a message!".to_string();
help =
"try to add a message: \
panic!(\"Example\".to_string())";
note =
"we will add the message to Result's Err"
);
s
} else {
// continue
}
}
} => s
})
.collect();
// return the statement
}
// return
}
#[proc_macro_error]
#[proc_macro_attribute]
pub fn panic_to_result(_a: TokenStream, item: TokenStream) -> TokenStream {
// ...
ast.sig.output = signature_output_as_result(&ast);
// ...
}

Similarly, we emit the error and then return the original statement.

The Result wrapper is gone, so we pass on the return directly.

The change in handle_panic_to_result is not too complex. We now use emit_error for both of our error cases, and we have—again—removed every Result wrapper. More interesting is that we are still returning something after emitting an error. That is because we want to go on for as long as possible, emitting errors—but continuing with parsing—until we’ve done everything we could. And because our code will not stop on the first error, we want to give back something sensible. If multiple functions are manipulating the code (say, the signature) and the first one fails and decides to put a garbage stream of tokens in the signature, the next function receives that garbage and fails for a totally unexpected reason. So returning the original value is an easy solution, even if an empty TokenStream could also work in simple examples.

We now add an example function that looks like the one in the following listing.

Listing 7.26 Function with faulty panic and signature

Section titled “Listing 7.26 Function with faulty panic and signature”
#[panic_to_result]
fn create_person_two_issues(name: String, age: u32)
-> Result<String, Person> {
if age > 30 {
panic!();
}
}
<!-- page: 171 -->
Ok(Person {
name,
age,
})
}
We get back two errors: the one we already had for empty panics as well as the one for faulty signature:
error: panic needs a message!
// rest of the error message from before //
error: this macro can only be applied to a function that does not yet return a Result. Signature: Result < String, Person >
--> tests/fails/create_person_two_issues.rs:11:56
|
11 | fn create_person_two_issues(name: String, age: u32)
-> Result<String, Person> {
| ^^^^^^^^^^^^^^^^^^^^^^^^^^
Besides abort! and emit_error!, the crate offers several other macros. abort_call_site! and emit_call_site_error! are similar to the other two except they contain a default span (pointing to the call site). Meanwhile emit_warning! and emit_call_site_warning! are used for logging warnings that won’t stop compilation. But this is all quite similar to what we already discussed, so we won’t go into more detail.
## 7.9.3 Deciding between syn and proc_macro_error
Use `syn::Error` if you dislike adding another dependency to your project since you probably already use syn. Its Result makes the behavior of your functions very clear, signaling that these are functions with failure cases. On the other hand, the `proc_macro_error` macros have a lot of useful functionality and require less ceremony. In either case, your users will be glad you didn’t go for vanilla panicking.
## 7.10 From the real world
Most macro crates handle errors by using one of these two approaches. Tokio, for example, is one of the libraries that uses `syn::Error`. Say you’ve added the Tokio macro to a function that is not actually async. The following piece of code will inform you of your mistake:
rust
if input.sig.asyncness.is_none() {
let msg = "the `async` keyword is missing from the function declaration";
return Err(syn::Error::new_spanned(input.sig.fn_token, msg));
}

syn::Error::new_spanned is an alternative to syn::Error::new. The difference is that the latter works with a span and the former allows you to pass in anything that implements ToTokens, which allows for more advanced errors. But, in this case, the output produced will be exactly the same as with syn::Error::new(input.sig.fn_token.span(), msg).

CHAPTER 7 From panic to result: Error handling

Section titled “CHAPTER 7 From panic to result: Error handling”

As an example, the following is a somewhat more creative use of new_spanned:

let msg = "a message";
let token = ast.sig.fn_token;
let name = ast.sig.ident;
let fn_token_plus_function_name = quote!(#token #name);
syn::Error::new_spanned(fn_token_plus_function_name, msg)
.to_compile_error()
.to_token_stream()
.into()

If this was used in this chapter’s macro, we would get back something like this:

error: a message
--> src/main.rs:11:1
|
11 | fn create_person(name: String, age: u32) -> Person {
| ^^^^^^^^^^^^^^^^^^^

Note how the message is pointing to both the function token and function name.

Yew similarly relies on syn errors. Interestingly, it does throw an unimplemented panic when the input is not a struct:

impl Parse for DerivePropsInput {
fn parse(input: ParseStream) -> Result<Self> {
let input: DeriveInput = input.parse()?;
let prop_fields = match input.data {
syn::Data::Struct(data) => match data.fields {
syn::Fields::Named(fields) => {
// code
}
syn::Fields::Unit => Vec::new(),
_ => unimplemented!("only structs are supported"),
},
_ => unimplemented!("only structs are supported"),
};
// more code
}
}

Shuttle, an “infrastructure from code” project that we mentioned in chapter 1, relies on proc_macro_error. Here they are checking the return type—just like us! Besides a hint, Shuttle also adds a reference to documentation with doc:

fn check_return_type(signature: &Signature) {
match &signature.output {
ReturnType::Default => emit_error!(
signature,
"shuttle_service::main functions need to return a service";
hint = "See the docs for services with first class support";
doc = "https://docs.rs/shuttle-service/latest/..."
),
// another check and emit error
}
}
<!-- page: 173 -->
7.10 From the real world
Leptos uses `proc_macro_errors` as well. In the following code, `abort` is used when there’s a useful span to point to, or `abort_call_site` when it is lacking:
rust
#[proc_macro_error::proc_macro_error]
#[proc_macro]
pub fn view(tokens: TokenStream) -> TokenStream {
// getting cx and comma
match (cx, comma) {
(Some(TokenTree::Ident(cx)), Some(TokenTree::Punct(punct)))
if punct.as_char() == ',' =>
{
// more code
let global_class = match (&first, &second) {
(Some(TokenTree::Ident(first)), Some(TokenTree::Punct(eq)))
if *first == "class" && eq.as_char() == '=' =>
{
match &fourth {
Some(TokenTree::Punct(comma))
if comma.as_char() == ',' =>
{
third.clone()
}
_ => {
abort!(
punct,
"To create a scope class with the view! \
macro you must put a comma `,`...";
help =
r#"e.g., view! {
cx,class="my-class", <div>...</div>
}"#
)
}
}
}
_ => None,
};
// more code
}
_ => {
abort_call_site!(
"view! macro needs a context and RSX: e.g., view! {{ cx, \
<div>...</div> }}"
)
}
}
}

Rocket, meanwhile, uses Diagnostics from proc_macro2_diagnostics, which has some neat extension traits for proc_macro2. They add an error and help to a span when checking a signature:

CHAPTER 7 From panic to result: Error handling

Section titled “CHAPTER 7 From panic to result: Error handling”
if catch.function.sig.inputs.len() > 2 {
return Err(catch.function.sig.paren_token.span
.error("invalid number of arguments: must be zero, one, or two")
.help("catchers optionally take `&Request` or `Status, &Request`"));
}

Those two return a Diagnostic that you can add more information to. You turn it into an output using emit_as_item_tokens():

let uri_display = match uri_display {
Ok(tokens) => tokens,
Err(diag) => return diag.emit_as_item_tokens()
};

Tokio, Leptos, Shuttle, Rocket—all of them report errors in a way that should be at least superficially familiar to you after reading this chapter. So, congratulations: you now have the tools to give awesome feedback to the users of your macros.

See the appendix for solutions.

  1. Rewrite the public fields macro to mutate the incoming TokenStream instead of creating a brand-new one.

  2. Our function-like macro for generating methods throws unimplemented for non-struct inputs. Use syn::Error instead. You can point to the span of the name.

  3. Now avoid the unimplemented with proc_macro_error.

  4. Expand our “panic checks” to also transform panics in while expressions.

  • Pure functions, whose return only depends on the parameters they receive, are easier to understand, test, and use than impure, side effect–producing functions.

  • Exceptions make code harder to understand because they break control flow, making Rust’s Result enum an excellent alternative for error handling.

  • Panics should only be used for situations that cannot happen or should never happen or when you are exploring ideas.

  • Besides creating entirely new token streams, you can manipulate the ones you receive, changing only what is necessary while leaving the rest of the code untouched.

  • With ItemFn, we can view the signature and body (statements) of a function.

  • Using panics for error handling in a macro works, but the resulting compilation error is not very useful to your users.

  • syn::Error gives you an error type for use in Result that can be transformed into a much more informative output.

  • proc_macro_error offers additional power in reporting helpful errors.

  • With emit_error, you can easily report multiple errors in one go.