Skip to content
ImagineWorld

Declarative macros

node_idnode-book_write-powerful-rust-macros_chapter-03-declarative-macros
node_typechapter-node
schema_profileworld.chapter_node.v1
statusactive
entropyhigh
manifoldworld
domainimagineworld.net
authorityinforms
layercorpus
chapter_num3
chapter_titleDeclarative macros
governed_byCORPUS
constitutional_citationCONSTITUTION
figure_reviewassets/wpm-fig-3-01-flowchart-showing-macro-expansion-steps-from-generategetvaluefirstname.png, assets/wpm-fig-3-02-flowchart-showing-macro-expansion-steps-for-composef1.png
reviewunbalanced $ inline delimiters
local graph
  • Writing declarative macros
  • Avoiding boilerplate and duplication, implementing newtypes, writing simple domain specific languages, and composing functions
  • Understanding the lazy_static crate

We will start this book in easy mode with declarative macros. These macros have a syntax that will immediately remind you of pattern matching, with a combination of matchers and transcribers. The matchers contain what you want to match against; the transcriber has the code you will generate when you find that match. It’s just that simple.

NOTE This chapter’s focus is a broad overview of declarative macros and their usage. This stands in contrast with the rest of this book, where we will focus on specific topics and a limited number of examples. The reason is that declarative macros are not the main focus of this book, and I expect the reader to know more about them than procedural macros. That means we can go through the subject of this chapter more quickly.

But wait, this is an example-driven book! That means we should drag a first example into this. vec! is used in several beginner’s explanations of declarative macros. We will go through a simplified implementation that shows how the aforementioned matchers and transcribers work together to generate the correct kind of code output for any given situation.

Listing 2.1 my_vec, our first declarative macro

Section titled “Listing 2.1 my_vec, our first declarative macro”
macro_rules! my_vec {
() => [
Vec::new()
];
(make an empty vec) => (
Vec::new()
);
{$x:expr} => {
{
let mut v = Vec::new();
v.push($x);
v
}
};
[$( $x:expr),+ ] => (
{
let mut v = Vec::new();
$(
v.push($x);
)+
v
}
)
}
fn main() {
let empty: Vec<i32> = my_vec![];
println!("{}", empty);
let also_empty: Vec<i32> = my_vec!(make an empty vec);
println!("{}", also_empty);
let three_numbers = my_vec!(1, 2, 3);
println!("{}", three_numbers);
}

We declare a new macro called my_vec.

() is our first matcher. Since it is empty, it will match a macro call without any arguments.

Everything between the pair of square brackets is the first transcriber. This is what we will generate for an empty invocation of our macro. Note the semicolon at the end.

(make an empty vec) is our second matcher. It will match when our input literally matches “make an empty vec.”

This is our second transcriber, this time between parentheses. We generate the same output as before, in the first transcriber.

The next two matcher-transcriber pairs. The first accepts one expression (expr) and will bind it to x. The second accepts multiple expressions separated by a comma. These will similarly be bound to x.

These two print [].

This one prints [1, 2, 3].

You start your declaration of a declarative macro with macro_rules!, followed by the name you would like to use for the macro, similar to how you would create a function by writing fn followed by a function name. Inside the curly braces, you put the desired matchers and transcribers. A matcher and its transcriber are (similar to the syntax of

pattern matching) separated by an arrow: (matcher) => (transcriber). In this case, we have four pairs of matchers and transcribers. Our first pair consists of an empty matcher, represented by some empty brackets, and a transcriber whose content is wrapped in square brackets. Square brackets are not a requirement though: for both matcher and transcriber, you have your choice of brackets: (), {}, and [] are all valid. You need to pick one of these three alternatives though, as removing them entirely (e.g. () => Vec::new()) will lead to Rust getting confused. It will start complaining about the double colons: no rules expected the token ::. If you remove those, it becomes more helpful, saying that the “macro’s right-hand side must be delimited”—that is, by using brackets!

NOTE The alert reader will notice that every pair in the example has a different syntax. This is only intended as a demonstration of your options regarding brackets. Your code will look cleaner if you settle for one of these options. Which one should you pick? Going for the curly braces can have the downside of making your code a bit less clear if you have code blocks within your transcriber (see the second pair in listing 2.1). And square brackets seem to be the less popular choice, so parentheses are probably a good default.

Another important syntactic element is that the pairs are separated by a semicolon. If you forget to do this, Rust will complain:

5 | {$x:expr} => { | ^ no rules expected this token in macro call

This is its way of saying that there should not be any rules if you end a matcher-transcriber without a semicolon. So keep adding them as long as you have more matcher-transcriber pairs coming. When you get to your last pair, the semicolon is optional.
## 2.1.2 Declaring and exporting declarative macros
A limitation to consider is that declarative macros can only be used after they have been declared. If I had placed the macro below the main function, Rust would complain like this:

error: cannot find macro my_vec in this scope —> src/main.rs:5:25 | 5 | let three_numbers = my_vec!(1, 2, 3); | ^^^^^^ | = help: have you added the #[macro_use] on the module/import?

Once you start exporting macros, this is no longer a problem, because `#[macro_use]` on top of a module or import (e.g., `#[macro_use] mod some_module;`) adds the macros to the “macro_use prelude.” In programming, a *prelude* is used as a term for the collection of things from the language that are globally available for coding. For example, `Clone` (`#[derive(Clone)]`) does not require an import because it is in
<!-- page: 025 -->
# 2.1 Creating vectors
Rust’s prelude. When you add a `#[macro_use]`, the same becomes true for macros from the chosen import: available everywhere, without an import. So the tip from the previous error message will solve the error, albeit by using a cannon to kill a mosquito. Also, this is the “older way” of exporting macros, and it is no longer the recommended approach. But we will get to that.
When you need to invoke your macro, you use its name followed by an exclamation mark and arguments between brackets. Similar to the macro itself, during invocation you can have any bracket you like, as long as it is normal, curly, or square. No doubt you have often seen `vec![]`, but `vec!()` and `vec!{}` are also valid, though curly brackets do not seem to be very popular for brief invocations. In this book, you will see me use curly braces for multiline `quote!` calls throughout.
## 2.1.3 The first matcher explained
Now that we have covered the basic syntax, here is our first matcher again:
rust
() => [
Vec::new()
];

Since our matcher is empty, it will match any empty invocation of our macro. So when we called let empty: Vec<i32> = my_vec!(); in our main function, this is the matcher we ended up in, since (a) Rust goes through the matchers from top to bottom and (b) we did not pass anything in within the brackets. We said that the content of the transcriber is located between the (in this case, square) brackets, so that means Vec::new() is the code that Rust will generate when we have a match. So, in this case, we are telling it that we want to call the new method of the vector struct. This piece of code will be added to our application in the location where the macro was called.

That brings us back to the first call in main. Rust sees my_vec!() and thinks, “An exclamation mark! This must be a macro invocation.” And since there are no imports in our file, this is either a macro from the standard library or a custom one. It turns out to be a custom one because Rust finds it in the same file. With the macro found, Rust starts with the first matcher, which turns out to be the correct one. Now it can replace my_vec!() with the content of the transcriber, Vec::new(). So by the time you do anything with your code (check, lint, run, etc.), let empty: Vec<i32> = my_vec!(); has already changed to let empty: Vec<i32> = Vec::new();. This is a minor but important detail: since only my_vec!() is being replaced, the semicolon at the end of the statement remains where it is. Because of this, we did not need to add one to our transcriber.

Let’s turn to the second matcher, which looks like this:

(make an empty vec) => (
Vec::new()
);
<!-- page: 026 -->
# CHAPTER 2 Declarative macros
In this case, the matcher contains *literal values*. This means that to match this particular “arm” of the macro, you would need to put that exact literal value between brackets when calling the macro, which is what we do in the second example from our main function: `let also_empty: Vec<i32> = my_vec!(make an empty vec);`. Our transcriber has not changed, so the output is still `Vec::new()` and the code becomes `let also_empty: Vec<i32> = Vec::new();`. In this case, the literals do not add anything interesting. But we will see some more useful sample cases later on.
The next pair is more interesting:
rust
{$x:expr} => {
{
let mut v = Vec::new();
v.push($x);
v
}
};

This time we are telling Rust that we want it to match any single Rust expression (expr) and bind it to a value called x. The dollar sign preceding x is significant, since it signifies that this is a macro variable. Without it, Rust thinks that this is just another literal, in which case there would be exactly one match (i.e., my_vec![x:expr]). Besides expressions, which are a common target for matching, you can also match identifiers, literals, types, and so on.

expr is called a metavariable in Rust lingo, or fragment specifier. The most powerful of these metavariables is tt (TokenTree), and it will accept almost anything you pass to it. That’s a powerful option. But its comprehensiveness can also be a downside. For simpler types, Rust can catch mistakes, like when you pass in a literal while the macro only matches an ident. Plus, with tt your matchers become less fine-grained since this one is screaming “Give me anything you’ve got!” For the very same reason, tt can be overeager. There is really a lot that will match a token tree! This is somewhat similar to regexes. \d+, which will only capture one or more digits and is less powerful than .*, which will capture anyone and anything. But a limitation is also an advantage, making \d more predictable and easier to manage. In the case of metavariables, it is advisable to start with a more concrete type and only move up to things like tt when that proves necessary. And if you do need it, think and test carefully.

The following is a list of all the fragment specifiers. Don’t worry; we will only use a limited subset of these to accomplish this chapter’s goals:

  • block—A block expression; that is, statements between curly braces.
  • expr—An expression; a very wide variety of things within Rust.
  • ident—An identifier or keyword. For example, the start of a function declaration (fn hello) has a keyword followed by an identifier, and we can capture them both by using ident twice.
  • item—Things like structs, enums, imports (“use declarations”).
  • lifetime—A Rust lifetime (‘a).
  • literal—A literal, like a number or a character.
  • meta—The content of an attribute, so Clone or rename = "true". You get a good idea of what an attribute might contain in later chapters.
  • pat—A pattern. 1 | 2 | 3 is one example.
  • pat_param—Similar to pat, except it can have | as a separator. So the rule ($first:pat_param | $second:ident) will work, but ($first:pat | $second:ident) tells you that | is not allowed after pat. This also means you need to do some extra work to parse 1 | 2 | 3 with pat_param (as it sees three separate tokens instead of one).
  • path—A path; things like ::A::B::C, or Self::method.
  • stmt—A statement; for example, an assignment (let foo = "bar").
  • tt—A TokenTree; see the previous explanation.
  • ty—A type, for example, String.
  • vis—A visibility modifier; pub comes to mind.

Within the transcriber, we are creating a new vector, adding the input expression, and returning the entire vector, which now contains the expression as its only element. This is basic Rust code with only two things worth mentioning. The first is that we have to use the dollar sign within the transcriber as well. Remember, with $ we have identified x as a macro variable. So what we are telling Rust is to push this variable, which was bound to the input, into the vector. Without the dollar sign, Rust will tell you that it cannot find value x in this scope because there is no x, only $x.

The second thing to note is the extra pair of curly braces. Without those, Rust gives you back an error saying expected expression, found let statement. The reason becomes clear once you try to mentally substitute the macro call with its output. Take this example, which should match our current rule: let a_number_vec = my_vec!(1);. We know that my_vec!(1) will be replaced with the content of the transcriber. So since let a_number_vec = will stay in place, we need something that can be assigned to a let—say, an expression. Instead, we are getting back two statements and an expression! How is Rust supposed to give that to let? Once again, the error sounded cryptic, but it makes perfect sense. And the solution is simply to turn our output into a single expression. The curly braces do just that. The following is the code after our macro has run:

let a_number_vec = {
let mut v = Vec::new();
v.push(1);
v
}

Yes, writing macros does require some thinking and (a lot of) tinkering. But since you have chosen Rust, you know that thinking is definitely on the menu.

We are now almost past the basics! The final matcher-transcriber pair is

$[($x:expr),+] => (:
{
let mut v = Vec::new();
$(
v.push($x);
)+
v
}
)

This is basically the same one as before, except with more dollar signs and some pluses. Within our matcher, we can see that $x:expr is now wrapped with $(), +. That tells Rust to accept “one or more expressions, separated by a comma.” As a programmer, it will not surprise you to hear that in addition to a +, you can use a * for zero or more occurrences and ? for zero or one. Like macros, regular expressions are everywhere. A slight gotcha is that this will not match an input with a trailing comma. my_vec![1,2,3] will work, whereas my_vec![1,2,3,] will not. For that, you need an extra rule (see the exercises at the end of this chapter).

Inside the transcriber, the only thing that has changed is that a similar dollar-bracket-plus combo is surrounding our push statement, except, this time, without the comma. Here, too, this indicates repetition. “For every expression from the matcher, repeat what is inside these brackets.” That is, write a push statement for every expression that you found. That means my_vec![1,2,3] will generate three push statements.

NOTE By now it might be obvious that the third matcher-transcriber pair is covered by this pair. But that additional pair made it easier to explain things step by step.

There are a lot of alternatives that won’t compile. For example, maybe you were hoping that Rust would be smart enough to figure out by itself that you want to push every expression into the vector. So you remove the $()+ from $ (v.push($x))+—only to be greeted by variable x is still repeating at this depth. With “repeating,” the compiler is telling you that x contains more than one expression, which is a problem since your code seems to assume you only have one expression to push into the vec.

And if you like playing around with this code, like one of my reviewers, you will eventually discover that you can use any repetition operator you want within the transcriber, regardless of the one in your matcher. You can do a push with ? and * and everything will work as expected, for now at least, since this is an open bug in Rust (see https://github.com/rust-lang/rust/issues/61053 for some context). If you want to make sure your code won’t break because of this in a future version of the language, you can add the #![deny(meta_variable_misuse)] lint to your file, which may, however, trigger false positives.

One final point before we end this section: what happens when you try to do illegal things inside a macro? What if you try to mix integers and strings as input, something

a vec cannot accept? Your integrated development environment might not realize that anything is amiss. After all, it’s all valid expressions being passed in! But Rust is not fooled because it generates “normal” code from the “rules” of your macro. And that code has to obey Rust’s compilation rules. This means that you will get an error expecting x, found y (with the names depending on what you passed in first) if you try to mix types.

Now that you have seen the basics, we can move on to more interesting stuff.

In this section, we will show common ways declarative macros increase the power of applications. In some cases, their utility is straightforward: they help you avoid writing boilerplate code, as we will see in our newtypes example. But other examples show you how we can do things with macros that are hard or impossible to do in any other way, like creating DSLs and fluent composition of functions or adding additional functionality to functions. Let’s get started.

First, how about when we bump into the limits of functions? For example, unlike Java or C#, Rust functions do not allow variadic arguments. One reason might be that variadic arguments make the compiler’s life harder. Or it could be that it is not an important enough feature. Apparently, the discussion about adding them to the language is very old and extremely contentious (and the same goes for default arguments!). Be that as it may, if you do need varargs, there are always macros. In fact, our vector macro performs this exact trick. Pass in any number of arguments, and Rust will generate code to handle your needs.

If you are coming to Rust from one of the many, many languages that permit overloading or default arguments, macros have you covered as well. For example, I have a function for greeting, and I would like it to default to “Hello” while also allowing more creative, custom salutations. I could create two functions with slightly different names to cover these cases. But it’s a bit annoying that the names would differ when they offer the same functionality. Instead, we will write a greeting macro.

Listing 2.2 Greeting people, with defaults, in greeting.rs

pub fn base_greeting_fn(name: &str, greeting: &str) -> String {
format!("{}, {}", greeting, name)
}
macro_rules! greeting {
($name:literal) => {
base_greeting_fn($name, "Hello")
};
($name:literal, $greeting:literal) => {
base_greeting_fn($name, $greeting)
}
}
<!-- page: 030 -->
# CHAPTER 2 Declarative macros
For the first time in this chapter, our implementation is not located in the same file as our main function. Instead, it is placed in a separate file called `greeting.rs`. To use the macro outside the file with its definition, we have to put `#[macro_use]` above the module declaration that we add in `main`.
## Listing 2.3 Example usage of our greeting macro in main.rs
rust
use crate::greeting::base_greeting_fn; // Imports base_greeting_fn
#[macro_use]
mod greeting; // Imports the module that contains our macro. With the annotation #[macro_use], we tell Rust that we want to import macros that are defined in that file.
fn main() {
let greet = greeting!("Sam", "Heya");
println!("{}", greet); // Prints "Heya, Sam!"
let greet_with_default = greeting!("Sam");
println!("{}", greet_with_default); // Prints "Hello, Sam!"
}

In a more complicated setup, with mod.rs importing and reexporting modules, you will need to put the annotation both in the “root” (your main.rs file) and any mod.rs files that do reexporting. But don’t worry: Rust will keep complaining with have you added the #[macro_use] on the module/import? until you fix all of them. It can be tedious at times, but this focus on keeping things private unless they are explicitly made public does force you to think about information hiding. But, as we previously mentioned, this is the older way of exposing macros. Instead, you should prefer a “use declaration” for reexporting the macro—for example, pub(crate) use greeting. This is the approach you’ll encounter in more recent Rust code.

Note that we had to make our base_greeting_fn function public (and import it into our main.rs). When you consider it, the reason is once again obvious: our declarative macro is expanded in our main function. In the previous section, we already learned that we can mentally take the content of our transcriber and replace the invocation with that content. In this case, greeting!("Sam", "Heya") is replaced by base_greeting_fn. And if base_greeting_fn is not public, you are trying to invoke an unknown function. This behavior might not be what you desire (because you might want the macro to be the entry point to all your holiday greetings), but it is a logical consequence of the way macros and visibility work in Rust.

We interrupt this broadcast to talk a bit more about expanding, a more official term for “replacing with the content of the transcriber,” because while replacing content in your mind is great, sometimes you want to see what is really going on. To help with that, Rust has a nice feature called trace macros (itself a declarative macro—turtles all the way down). They are still unstable in Rust 1.77.2, the most recent version of Rust at the time of writing, which means you have to activate them as a feature and run

2.2 Use cases

your code with the nightly build. You can do that with rustup default nightly, which sets nightly as your default. Or—if you would like to stay with a stable version of Rust—you can instruct Cargo to run a specific command with nightly using cargo +nightly your-command.

The following code shows how to activate and deactivate the trace macros feature.

Listing 2.4 Using the trace macros feature

Section titled “Listing 2.4 Using the trace macros feature”
#![feature(trace_macros)]
use crate::greeting::base_greeting_fn;
#[macro_use]
mod greeting;
fn main() {
trace_macros!(true);
let _greet = greeting!("Sam", "Heya");
let _greet_with_default = greeting!("Sam");
trace_macros!(false);
}

Adds the unstable trace macros feature

Activates the trace macros

Deactivates the trace macros

This is our code from before with the println! statements removed and calls to trace_macros! added. With true, they are activated; with false, they are disabled. In our case, deactivation is not strictly necessary since we have reached the end of our program in any case. Running this code will print something like this:

--> ch2-trace-macros/src/main.rs:9:18
9 | let _greet = greeting!("Sam", "Heya");
| ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^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^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^
<!-- page: 032 -->
# CHAPTER 2 Declarative macros
`log_syntax!` to tell the user what arguments were received, calls `println!` to inform them that the default greeting was returned, and calls the `greeting` function. All of this is wrapped in an additional pair of braces. That is because our macro has to return *a single expression* to bind to `let`. And by adding that second pair of braces, we create one expression by enclosing the two statements and the expression.
## Listing 2.5 Using log syntax
rust
macro_rules! greeting {
($name:literal) => {
base_greeting_fn($name, "Hello")
};
($name:literal, $greeting:literal) => {
base_greeting_fn($name, $greeting)
};
(test $name:literal) => {{
log_syntax!("The name passed to test is ", $name);
println!("Returning default greeting");
base_greeting_fn($name, "Hello")
}}
}

We are using log_syntax! to log our input.

Double braces because we want to surround this generated code with { }, thereby creating just a single expression as our output

In our main file, nothing much has changed. We have added another feature and a macro invocation that will end up in our third matcher:

#![feature(trace_macros)]
#![feature(log_syntax)]

Log syntax is unstable, so we need to activate it with a feature.

use crate::greeting::greetingu;
#[macro_use]
mod greeting;
fn main() {
trace_macros!(true);
let _greet = greeting!("Sam", "Heya");
let _greet_with_default = greeting!("Sam");
let _greet_with_default_test = greeting!(test "Sam");
trace_macros!(false);
}

We invoke the new branch of our greeting macro.

Now if you run this with cargo +nightly check, you will see the log_syntax! output (The name passed to test is Sam) because it is executed at compile time. Only when we invoke cargo +nightly run will we see both the log syntax output and the println! statements that we added inside the macro. This difference is important for anyone debugging things that happen at compile time. Using the former, you can debug declarative macros via print statements (objectively the best kind of debugging). Together, these tools allow you to trace the route from macro to expanded Rust code. It is not the power of a real debugger, but it is certainly better than nothing. It’s a pity that you have to use nightly Rust. Later, we will see some tooling that works with stable Rust versions.

2.2 Use cases

23

Another way declarative macros can help you is by avoiding boilerplate and duplication. To explore that theme, we will introduce newtypes. Newtypes are a concept from the world of functional programming. Essentially, they are a “wrapper” around an existing value that forces your type system to help you avoid bugs. Say I have a function that calculates pay raises. The problem with that function is that it not only requires four parameters, but the first and second parameters have the same type as the third and fourth. That means it is easy to make stupid mistakes.

fn calculate_raise(first_name: String,
_last_name: String,
_age: i32,
current_pay: i32) -> i32 {
if first_name == "Sam" {
current_pay + 1000
} else {
current_pay
}
}
fn main() {
let first_raise = calculate_raise(
"Smith".to_string(),
"Sam".to_string(),
20,
1000
);
println!("{}", first_raise); // Prints "1000"
let second_raise = calculate_raise(
"Sam".to_string(),
"Smith".to_string(),
1000,
20
);
println!("{}", second_raise); // Prints "1020"
}

Only people with first name “Sam” will get a raise.

Whoops, I switched my first and last name. No raise for me!

This time, at least the names are in the right order and I will get a raise. But despite being a thousand years old (!), my raise is only $20.

By creating unique wrappers (FirstName, LastName, Age, CurrentPay) for our parameters, the type system can keep us from making such mistakes. In addition, our code becomes more readable because we are making everything a bit more explicit. All of this makes this pattern popular among clean code and domain-driven design (see section 2.2.4) advocates. And hiding the “real” value of our parameters and giving them types with more meaning within our domain also makes newtypes ideal for making public APIs easier to understand and easier to evolve.

NOTE Rust also has type aliases that create an alternative name (alias) for a chosen type. If we wanted to do this for FirstName, we would write type

FirstName = String;. This can make your code more readable to other developers, who can now see that you desire one specific type of String, a first name. Type aliases are often used when you have a more complex type that you want to make easier to read and use. Crates often have one custom error that is used everywhere. The syn crate, for example, has syn::Error. Because of this, it is also convenient to offer a type alias for Result with the default crate error already filled in, for example, type Result<T> = std::result::Result<T, syn::Error>. Now code in the package can use Result<T> for its return type. But type aliases do not make your type system smarter: I can still pass in a String when my function requires a FirstName type alias.

You can see an example for the FirstName newtype in listing 2.7. I have kept the internal value of the wrapper private while presenting the rest of my application with a new method. In that method, I can do additional checks to make sure a valid value was passed in, giving back an error when this is not the case. Why would I do that? Because it will make using these types easier in other functions that can now rely on this validation to make additional assumptions. If there is only one way to create these wrappers, we know that our newtype passed all its validations. In the case of FirstName, I now know that it is not empty. For Age, functions can assume validation will check that we have, say, a positive number under 150. But even without safeguards, newtypes have their value because they make the type system more powerful and force you to think about the values you pass in. If a function requires a FirstName and you are required to manually wrap your String into one, maybe that will keep you from accidentally passing in a String called last_name.

NOTE An easy way to mitigate mistakes for our age versus pay problem without using newtypes would be to make the age parameter a u8. This would already guarantee a positive number below 256.

Besides the constructor, we are also exposing a get_value method that will give back an immutable reference to “my inner value” to be used, safely, by other parts of the code. We could also add some conveniences like AsRef and AsRefMut trait implementations, but that is beyond the scope of this example.

struct FirstName {
value: String,
}
impl FirstName {
pub fn new(name: &str) -> Result<FirstName, String> {
if name.len() < 2 {
Err("Name should be at least two characters".to_string())
} else {
Ok(FirstName {
value: name.to_string(),
})
}
}
}
<!-- page: 035 -->
2.2 Use cases
25
rust
}
}
pub fn get_value(&self) -> &String {
&self.value
}
// code for the other three newtypes
fn calculate_raise(first_name: FirstName,
_last_name: LastName,
_age: Age,
current_pay: Pay) -> Pay {
// ...
}

Usage example: passes in the newtypes instead of the built-in types. If you accidentally switch arguments one and two or three and four, the compiler will throw an error.

Everything is a tradeoff in programming. Here, one downside to our approach is how bloated our code has become. Just to create a single newtype, we had to write 18 additional lines of code! We can turn to macros to reduce this overhead. Let’s start with the get_value method for the FirstName struct.

Listing 2.8 A macro for the newtype get_value method

Section titled “Listing 2.8 A macro for the newtype get_value method”
struct FirstName {
value: String,
}
struct LastName {
value: String,
}
macro_rules! generate_get_value {
($struct_type:ident) => {
impl $struct_type {
pub fn get_value(&self) -> &String {
&self.value
}
}
}
}
generate_get_value!(FirstName);
generate_get_value!(LastName);

We want one input argument, an identifier.

We use that argument to implement a get_value method for the given struct.

Now our FirstName and LastName structs will get the new method implemented for them.

By now, you can read this code with ease. We declare a new macro with macro_rules! and write a single matcher-transcriber pair. The only thing that we need to receive is the name of our struct. ident (identifier) seems like the most suitable kind of input. Everything except this name is hardcoded in the transcriber. Note that you can have

multiple impl blocks for a struct. If this was not the case, our macro would prevent users from implementing any methods of their own!

Are we done? Unfortunately, no. When we try this for the next two structs, Age and Pay, we are greeted by a compile error: mismatched types: expected reference &String found reference &i32. Rust is right! We were keeping things simple, assuming the return type would always be String. But that is not the case. One way to solve this problem is to make our macro accept an additional argument, a return type override. While ident would work, ty—which stands for “Type”—is more suitable. String will be the default when we only get one identifier. That way our existing code will keep working. With this override in place, we can use the macro for Age and Pay as well.

Listing 2.9 Making it work for types other than Strings

Section titled “Listing 2.9 Making it work for types other than Strings”
struct Age {
value: i32,
}
struct Pay {
value: i32,
}
macro_rules! generate_get_value {
($struct_type:ident) => {
impl $struct_type {
pub fn get_value(&self) -> &String {
&self.value
}
}
};
($struct_type:ident, $return_type:ty) => {
impl $struct_type {
pub fn get_value(&self) -> &$return_type {
&self.value
}
}
}
}
generate_get_value!(FirstName);
generate_get_value!(LastName);
generate_get_value!(Age, i32);
generate_get_value!(Pay, i32);

This pair is new. It takes an additional input, a type (ty), which is used to specify the correct return type in the signature of our get_value method.

And so we have exchanged some 18 lines of boilerplate code for 20? Okay, but we can do better than that. Another nice feature of macros, and one that we have avoided using for simplicity’s sake, is that they can call themselves. You may have noticed that there is a lot of overlap between our two code paths. Why not have one of our cases use the other? Since the String pair is a special case of the other one (which can handle any type), it makes sense for our special case to use the generic internally. So we will call our macro and pass along the input, with String as a second argument. Rust sees the two identifiers and knows it has to move to the second matcher (see figure 2.1).

2.2 Use cases

27

Listing 2.10 Final version of the get_value macro

Section titled “Listing 2.10 Final version of the get_value macro”
macro_rules! generate_get_value {
($struct_type:ident) => {
generate_get_value!($struct_type, String);
};
($struct_type:ident, $return_type:ty) => {
impl $struct_type {
pub fn get_value(&self) -> &$return_type {
&self.value
}
}
}
}

Inside our first transcriber, we are now calling our own macro with two identifiers.

This means we end up in this matcher, which accepts two identifiers.

Figure 2.1 What happens when we call generate_get_value with only one identifier

We are now writing less boilerplate than before; all our logic for generating get_value methods is in one place; and the more newtypes we use, the more profit we gain from our macros. In a larger project, we could have additional macros for additional convenience methods and perhaps another one that calls all the others. But that is left as an exercise for the reader.

NOTE The derive_more crate (https://docs.rs/derive_more/latest/derive_more/) is worth a mention before you start writing too much yourself. It can automatically implement some basic traits for wrappers like these. It uses procedural macros though, not declarative ones.

Before ending this section, I should mention that there is a Rust-specific reason for using newtypes: orphan rules. If you want to implement a given trait in Rust, either the trait, the type (e.g. a struct), or both should be local to your code. This avoids all kinds of problems. If I decide to reimplement Clone for String, what implementation should Rust prefer? In an application, maybe it would make sense to prefer the local implementation. But what if people write new implementations in libraries? Should Rust prefer the Clone implementation from the standard library? or the one from library A, B … X?

[!visual-conversion] Flowchart showing macro expansion steps from generate_get_value!(FirstName) to impl FirstName … Cropped from the scan (PDF page 037, printed p. ?): Flowchart showing macro expansion steps from generate_get_value!(FirstName) to impl FirstName with bind operations.

On the other hand, sometimes these rules keep you from doing cool—eh, useful—things. So the workaround is to wrap the nonlocal type (String) in a newtype (MyString). This newtype is local, so we are free to add an implementation of Clone to MyString. All kinds of built-in and custom macros will make handling the boilerplate that this entails easier to bear. Oh, and how about using declarative macros to ease the burden even further? Like we just did? Plus, newtypes are a zero-cost abstraction: no runtime overhead as the compiler should optimize them out.

Finally, since we just saw how macros can call themselves, it’s important to add that the recursive behavior of a declarative macro is not always equal to that of a function or method. Take, for example, the following piece of code.

plaintext macro_rules! count { (val: expr) => { if val == 1 { 1 } else { count!($val - 1) } } }

If this was a function, you would expect any invocation (e.g., `counter!(1)`, `counter!(5)`...) to return 1. Sadly, you will bump into a recursion limit reached error at compile time instead. Add trace macros, and the resulting output is revealing. Here are the first few lines:

= note: expanding count! { 5 } = note: to if 5 == 1 { 1 } else { count! (5 - 1) } = note: expanding count! { 5 - 1 } = note: to if 5 - 1 == 1 { 1 } else { count! (5 - 1 - 1) } = note: expanding count! { 5 - 1 - 1 } = note: to if 5 - 1 - 1 == 1 { 1 } else { count! (5 - 1 - 1 - 1) }

`$val - 1` is not evaluated, and so we never reach our terminal condition. That is not to say that recursion with an unknown number of arguments is impossible. See section 2.2.5 for an example of how you can make this work.
## 2.2.4 DSLs
Declarative macros are also good for creating DSLs. As mentioned in the introduction, DSLs encapsulate knowledge about the domain—that the developers have learned from domain experts—into the application. This idea of capturing domain knowledge is related to that of a ubiquitous language, which comes from Domain-Driven Design and argues that communication between experts and developers is easier when they use the same words and concepts. This leads to better code.
The goal of a DSL is to create a specialized language that is suitable to the domain and hides irrelevant complexities. Among these complexities could be things like
<!-- page: 039 -->
# 2.2 Use cases
additional validation and taking care of certain subtleties. Some think that a DSL could make a codebase understandable to nonprogrammers, and one idea behind testing frameworks like Cucumber (https://github.com/cucumber-rs/cucumber) is to write tests in a language that the domain experts could understand. Another idea is that experts would even be able to add their own tests using these tools! Within the Rust ecosystem, mini-DSLs abound, and they are often created by using macros. Two simple examples from the standard library are println! and format!, which offer a special syntax using curly braces to determine how to print specified variables.
As an example, we will write a DSL for handling transfers between accounts. First, we create an Account struct that contains the amount of money in our account. It also has methods for adding and removing money from the account. We only want positive amounts (hence the use of u32), but handling accounts going into the negative is beyond scope. Account also derives Debug. This is a good idea in general, though our motivation here is simply to print some outcomes.
## Listing 2.12 The Account structure
```rust
use std::ops::{Add, Sub};
#[derive(Debug)]
struct Account {
money: u32,
}
impl Account {
fn add(&mut self, money: u32) {
self.money = self.money.add(money)
}
fn subtract(&mut self, money: u32) {
self.money = self.money.sub(money)
}
}

Now check out the exchange macro in listing 2.13, which presents users with a mini-DSL. As you can see, this macro allows us to use natural language, understandable to outsiders, to describe actions. And when the macro does not understand a command, it will complain about this at compile time. Also, when transferring money between two accounts (third pair), we are hiding the complexity of a transaction from the DSL user.

Listing 2.13 Macro that presents a mini-DSL for exchanging money

Section titled “Listing 2.13 Macro that presents a mini-DSL for exchanging money”
macro_rules! exchange {
(Give $amount:literal to $name:ident) => {
$name.add($amount)
};
(Take $amount:literal from $name:ident) => {
$name.subtract($amount)
};
}

rust (Give amount:literalfromamount:literal from giver:ident to receiver:ident) => { giver.subtract(amount);amount); receiver.add($amount) };

> We have to end `$giver.subtract($amount)` with a semicolon because the transcriber has two statements instead of one, and the compiler would complain about expecting a `;`.
```rust
fn main() {
let mut the_poor = Account {
money: 0,
};
let mut the_rich = Account {
money: 200,
};
exchange!(Give 20 to the_poor);
exchange!(Take 10 from the_rich);
exchange!(Give 30 from the_rich to the_poor);
println!("Poor: {the.poor?}, rich: {the.rich?}");
}

This prints “Poor: Account { money: 50 }, rich: Account { money: 160 }”.

Uses natural language to specify transactions

And there is no need to stop here. You could add currency types and automatically convert them. Or you could have special rules for overdraft. Good testing is needed to make sure that your macro scenarios do not “collide” (which is when you think you will land in matcher X but you end up in Y) with each other, though. As a simple example, the following macro is meant for giving money to the poor and berates people who don’t give anything. We call our macro and are complimented for giving nothing. That’s because the first clause accepts any literal, which includes zero. And since the macro checks the matcher in order and always matches the first more general clause, the second one is never reached.

Listing 2.14 A faulty wealth-transfer macro

Section titled “Listing 2.14 A faulty wealth-transfer macro”
macro_rules! give_money_to_the_poor {
(Give $example:literal) => {
println!("How generous");
};
(Give 0) => {
println!("Cheapskate");
};
}
fn main() {
give_money_to_the_poor!(Give 0);
}

Prints “How generous”! That is not what we expected.

The solution—in this case—is simple. Just switch the order of the cases! The underlying rule is this: write macro rules/matchers from most-specific to least-specific. This rule also applies to pattern matching with match, though the order is not enforced by the compiler, which only produces a warning. (Try putting the catchall _ before other matches.) More worrisome is ignoring this rule still results in a valid macro implementation

according to Rust, which won’t even produce a warning. So static checks are insufficient to root out these bugs, and you should test all your “branches.”

Besides avoiding boilerplate, macros also help us do things that are inelegant, hard, or even impossible to do in plain old Rust. (And you could see DSLs as a specific example of this more general category.) Take composition, which is a common feature of functional programming and a design pattern in object-oriented programming. Composition allows you to combine simple functions into bigger ones, creating larger functionality from smaller building blocks. This is a very interesting way to build applications when you want to keep your functions simple, understandable, and easy to test. And it is useful as a way to combine components in a paradigm that avoids object interactions for application building. To make things more concrete: say we have functions to increment a number, to change a number to a string, and to prefix a string. These three are shown in the following listing.

fn add_one(n: i32) -> i32 {
n + 1
}
fn stringify(n: i32) -> String {
n.to_string()
}
fn prefix_with(prefix: &str) -> impl Fn(String) -> String + '_ {
move |x| format!("{}", prefix, x)
}

The String + _ in the return type is needed because we are passing in a &str and that lifetime has to be made explicit.

The following pseudocode shows how we would like to compose these functions, similar to how it works in other languages. We pass our three functions to compose and get back a new function that expects one input. That input is the same type as the parameter of the first function we passed in. In our case, that function is add_one, which expects an i32. Internally, our composed will pass this argument to add_one, which will output an incremented number. That incremented number is given to the next function, stringify, which turns the number into a string. Finally, this string is passed to prefix_with. Since this last function needs two arguments, both a prefix and an input string, we already passed in a prefix. In functional lingo, the function has been partially applied:

fn main() {
let composed = compose(
add_one,
stringify,
prefix_with("Result: ")
);
println!("{}", composed(5));
}

This should print “Result: 6”.

And you are not limited to a few functions! You can keep adding more, as long as they accept a single parameter that matches the output of the previous function and return a value that the next one accepts.

NOTE In some implementations, the order in which compose calls the functions might be reversed (i.e., from the rightmost argument to the leftmost). In that case, you first give it the last function it should call and end with the first.

But how do we write this compose? We will start simply with two input functions. No macros are required to make this work—just a lot of generics. compose_two (see the code in listing 2.16) requires two functions as parameters, both of which take a single parameter and return a result. The second one has to take the first one’s output as its single input:

Fn(FIRST) -> SECOND Fn(SECOND) -> THIRD

For easier reading, we can put these in a `where` clause, binding to generics `F` and `G`: `where F: Fn(FIRST) -> SECOND, G: Fn(SECOND) -> THIRD`. We also return a function that takes the first function’s input and has an output equal to the second one’s output:

Fn(FIRST) -> THIRD

Compared to the signature, the implementation is simple: it’s a closure that takes one argument (our generic `FIRST`), gives it to our first function, and gives that output (`SECOND`) to our second function, which will produce the final result (`THIRD`). Because of the closure, we add `impl` to our return type, since every closure is unique and won’t match a normal generic function type.
## Listing 2.16 A function to compose two functions
```rust
fn compose_two<FIRST, SECOND, THIRD, F, G>(f: F, g: G)
-> impl Fn(FIRST) -> THIRD
where
F: Fn(FIRST) -> SECOND,
G: Fn(SECOND) -> THIRD
{
move |x| g(f(x))
}
fn main() {
let two_composed_function = compose_two(
compose_two(add_one, stringify),
prefix_with("Result: ")
);
}

compose_two is a function that takes two generic parameters, called f and g, and returns a function (well, something that implements a function) that takes one generic argument and returns another generic argument.

In this part of the where clause, we determine that f is a function that takes a generic argument called FIRST and returns a generic result that we call SECOND. FIRST becomes the input of compose_two.

Also in the where clause, we decide that g takes SECOND and returns THIRD. THIRD is the output of our compose_two.

Given an argument, passes it to the first function we received and passes that result to the second one we received

Repeatedly calls compose_two to compose our three functions from before

2.2 Use cases

That is the first step. How would we go about making this work for multiple functions? One approach that I have occasionally seen in other languages is to just write an implementation for the most common number of arguments: compose_three, compose_four, etc. up to compose_ten. That should cover 90% of all cases. And if we need more, we could also start nesting the existing implementations (a compose_ten within a compose_ten). It is a decent workaround, and it is hard to do better with plain Rust tooling. Say we decided to write a compose with a vector of functions as a parameter. We would need some way to tell the compiler that each function in this vector takes the previous output as input if we want our code to compile. That’s hard to express in Rust.

But expressing this idea in a declarative macro is trivial (see listing 2.17). Let’s go through it step by step. If our compose macro receives a single expression, a function, it returns that expression—a simple base case. If the macro is invoked with two or more arguments (note the + after $tail, which is for when there is more than a single expression in our tail), we need recursive magic. What we do is call our compose_two and pass in the two required arguments. The first is the first function we receive, head. The second is the result of calling our compose macro again, this time on the remaining arguments. If this second compose invocation receives a single expression, we end up in the first matcher, and we only have to compose two functions with a simple compose_two call. In the other case, we end up in our second branch—again—and return a function that is the result of compose_two—again. This is, in fact, what we suggested doing manually with nesting, except now the macro takes care of everything in the background (see figure 2.2).

Listing 2.17 compose macro

rust macro_rules! compose { (last:expr) => { last }; (head:expr,head:expr, (tail:expr),+) => { compose_two(head, compose!(((tail),+)) } }

fn main() { let composed = compose!( add_one, stringify, prefix_with(“Result: ”) ); println!(”{}”, composed(5)); // Prints “Result: 6” }

Commas are not the only way to separate the arguments that you pass to your macro. Similar to the brackets, you have some alternatives. In the case of `expr`, you can also go for a semicolon or an arrow. But if you’re a Haskell fan and you would like to compose using periods, that won’t do. You will get an error that says `$head:expr` is followed
<!-- page: 044 -->
# CHAPTER 2 Declarative macros
plaintext
compose!(F1, F2, F3)
|
| Expand compose!
| More than one expression, so second match arm.
v
compose_two(
F1, compose!(F2,F3))
|
| Expand compose! More than one expression.
v
compose_two(F1,
compose_two(F2,
compose!(F3)))
|
| Expand compose! One expression, first arm
| which just returns the input.
v
compose_two(F1,
compose_two(F2, F3))

Figure 2.2 The compose macro with three functions, creatively called F1, F2, and F3

by ’.’, which is not allowed for expr fragments. Other macro input types, like tt, have more options, though.

Listing 2.18 Alternative with arrows separating the inputs to the macro

Section titled “Listing 2.18 Alternative with arrows separating the inputs to the macro”
macro_rules! compose_alt {
($last:expr) => { $last };
($head:expr => $($tail:expr)=>+) => {
compose_two($head, compose_alt!($($tail)=>+))
}
}
fn main() {
let composed = compose_alt!(
add_one => stringify => prefix_with("Result: ")
);
println!("{}", composed(5));
}

Within the second matcher, we have replaced the commas with arrows.

Now we use arrows in our invocation as well.

Suppose you are now hooked on a functional style of Rust, but you find the “one-input” requirement of compose an annoyance, because, in reality, you often have functions that require multiple parameters to be passed in at the same time. And composition can’t handle that. Luckily, you find out that there is something called currying. Currying is when you have a function that requires more than one argument and gives back a “recursive” function that takes only one argument at a time. For example, currying turns

Fn(i32, i32) -> i32

into

Fn(i32) -> Fn(i32) -> i32
![](assets/wpm-fig-3-02-flowchart-showing-macro-expansion-steps-for-composef1.png)
> [!visual-conversion] Flowchart showing macro expansion steps for compose!(F1, F2, F3) with …
> Cropped from the scan (PDF page 044, printed p. ?): Flowchart showing macro expansion steps for compose!(F1, F2, F3) with arrows and text labels.
<!-- page: 045 -->
That makes *partial application* of functions—that is, supplying only a part of all the arguments that a function needs—easier, which in turn makes composing easier. You would like to make this possible in Rust. And after your positive experience with composing, you think declarative macros are the way to go.
You would soon discover that currying with declarative macros is harder, though. One problem is the lack of “visibility” of the function’s signature: what does it require as parameters, and what does it return? Going back to our previous approach, we could start with the easiest case, a `curry2` function for changing a function with two arguments into a curried version. Now all we have to do is recursively call this function. But how many times should we (well, the macro) call it? Without access to the signature, we’re in the dark, whereas with composing, we knew how many calls had to happen because the functions *were given to our macro as arguments*.
Whereas composing was trivial, currying is hard. And while explicitly passing in details would help, that is exactly the kind of busywork we are trying to avoid. Because they are explicit about their number of arguments, closures are easier. And so there’s a crate for currying them (https://mng.bz/v8Pm). Take a look at the simplest rule in that crate:
```rust
macro_rules! curry {
(| $first_arg:ident $ (, $arg:ident )*| $function_body:expr) => {
move |$first_arg| $(move |$arg|)* {
$function_body
}
};
// ...
}

This matcher expects one or more identifiers within pipes (| |), followed by an expression. Take the call curry!(|a, b| a + b); as an example. a and b are our two identifiers, and a + b is our expression. All the transcriber has to do is add a move for each of these identifiers and pass them to the function. In our example, this becomes move |a| move |b| a + b;. Suddenly, we have two closures, each of which takes one argument. But again, this works because everything we need to know is passed in as an argument. Normal functions have this information in their signature, making good solutions harder (though probably not impossible). Instead, as the blog post, “Auto-currying Rust Functions” (https://peppe.rs/posts/auto-currying_rust_functions) shows, procedural macros offer the right tools for the job. And while its result is more complicated and has more lines of code than the average declarative macro from this chapter, the actual solution is still decently short: under 100 lines.

2.2.7 Hygiene is something to consider as well

Section titled “2.2.7 Hygiene is something to consider as well”

You should be aware that not everything you generate will be added as is to your code because declarative macros have a concept of hygiene for identifiers. Simply put, identifiers inside your macro will always be different from those in code outside the macro,

CHAPTER 2 Declarative macros

even if their names overlap, which means a number of things are impossible. For example, I cannot let generate_x!() output let x = 0 and then increment that named variable in my ordinary code. If I try that, Rust will complain that it cannot find value x in this scope. That’s because the x I initialized in my macro is not the x I am trying to increment in my application.

The way I am presenting this, hygiene sounds like a bad thing. But it is useful as a safeguard against contamination. A difference in intent is something to consider. If I am getting an identifier via my input and writing an implementation block, I want to affect code outside of the macro, or else what would be the point of that implementation? But identifiers created within my macro can serve other goals. Maybe I want to perform a calculation or push things into a vector. That stuff is independent of what I am doing outside the macro. And since developers often go for variable names that are easy to understand, there is a chance that a user of my macro will have the same variable name(s) in their own code. So when you see compiler errors around “unresolved” and “unknown” identifiers that are somehow related to macro code, remember this behavior. And if you want to have an effect on an identifier, just pass it into the macro as an argument.

Once upon a time, there was no good built-in way to create lazily initiated static values in Rust. But lazy statics are useful for several reasons. For one, maybe the value inside your static requires a lot of computation. If it turns out the value is never needed, you never pay its initialization price. Another advantage is that the initialization happens at run time, which has some additional options on top of those available at compile time. (Yes, this contradicts the preference for compile-time stuff that often bubbles up in this book. As always in software, it depends. Compile-time work makes things safer and faster. But at run time, you can do some things you could not do during compilation.) Seeing this lack, lazy_static (https://docs.rs/lazy_static/latest/lazy_static/) jumped in and filled a need. Nowadays, though, once_cell can be used for “initialization of global data.” So lazy_static is no longer the recommended crate for this type of functionality. But that doesn’t mean its code is not interesting anymore!

Listing 2.19 Lazy static example from the documentation

Section titled “Listing 2.19 Lazy static example from the documentation”
lazy_static! {
static ref EXAMPLE: u8 = 42;
}

At the very root of the crate is the lazy_static macro. A #[macro_export] makes sure we can use it outside this file. The matchers can have meta (i.e., metadata) optionally (note the asterisk in the next listing) passed in, and the static ref is literally required as an input. A static also has an identifier, a type, and an initialization expression as well

2.3 From the real world

as some optional additional information (thrown together in TokenTrees). Most of the incoming variables are simply passed on to an internal macro called __lazy_static_internal. But to avoid parsing ambiguity, () is added as an indicator of the (default) visibility modifier. (In some other matchers of the macro, (pub) is passed along instead to indicate public visibility.)

Listing 2.20 lazy_static macro entry point, simplified slightly

Section titled “Listing 2.20 lazy_static macro entry point, simplified slightly”

spin #[macro_export] macro_rules! lazy_static { ((#[attr:meta])* static ref N:ident:N:ident : T:ty = e:expr;e:expr; (t:tt)*) => { __lazy_static_internal!((#[attr])∗()staticrefattr])* () static ref N : T=T = e; ((t)*); }; // other arms… }

Most of the implementation is hidden inside the internal macro, shown in listing 2.21. You could call the `@MAKE TY` and `@TAIL` a mini (nano?) DSL. It is used to make sure the other matcher-transcriber pairs within the macro are called, a pattern that appears in *The Little Book of Rust Macros* (https://veykril.github.io/tlborm/). The first of these two additional arms (`@MAKE TY`) is, as the name indicates, responsible for creating the type, which is just a struct with an empty internal field, decorated with the original metadata that was passed in (so it doesn’t get lost). The second arm (`@TAIL`) creates a Deref and initialization. This is where the magic happens. If you need your lazily initialized static somewhere in your code, you will dereference it as soon as you start using it. It is at that point that the initialization expression that you provided will run. You can see that expression (`$e`) being passed to the `__static_ref_initialize` function within the deref method. Underneath it all, once, from the spin library (https://docs.rs/spin/latest/spin), is used to make sure this initialization only happens one time. This is done in the `lazy_static_create` macro, which is called inside the generated deref.
### Listing 2.21 lazy_static internal, again simplified
```spin
macro_rules! __lazy_static_internal {
($(#[$attr:meta])* ($($vis:tt)*) static ref $N:ident : $T:ty = $e:expr; $($t:tt)*) => {
__lazy_static_internal!(@MAKE TY, $(#[$attr])* ,

This is a declarative macro declaration for a macro called lazy_static_internal.

The first matcher expects optional attributes, optional visibility, a literal “static ref” value, an identifier, type, and expression. Finally, and again optionally, we capture everything else in a TokenTree.

CHAPTER 2 Declarative macros

rust (((vis)*), $N);

```rust
__lazy_static_internal!(@TAIL, $N : $T = $e);
};
(@TAIL, $N:ident : $T:ty = $e:expr) => {
impl $crate::__Deref for $N {
type Target = $T;
fn deref(&self) -> &$T {
fn __static_ref_initialize() -> $T { $e }
fn __stability() -> &'static $T {
__lazy_static_create!(LAZY, $T);
LAZY.get(__static_ref_initialize)
}
__stability()
}
}
impl $crate::LazyStatic for $N {
fn initialize(lazy: &Self) {
let _ = &**lazy;
}
};
(@MAKE TY, $(#[ $attr:meta])* , ($($vis:tt)*),
$N:ident) => {
$(#[ $attr])*
$($vis)* struct $N {__private_field: ()}
$($vis)* static $N: $N = $N {__private_field: ()};
};

We call our own macro, and the @MAKE TY literal makes sure we end up in the last arm.

Similarly, here @TAIL makes sure we end up in the next arm.

This contains a lot of the magic of lazy static, using Deref to initialize our static.

Here, $crate is used to make sure that there is no collision with a LazyStatic defined anywhere else (i.e., we only want the LazyStatic defined in our crate).

macro_rules! __lazy_static_create {
($NAME:ident, $T:ty) => {
static $NAME: $crate::lazy::Lazy<$T> = $crate::lazy::Lazy::INIT;
};
}

Now you know like 80% (citation needed) of how the lazy_static crate works!

See the appendix for solutions.

  1. Fill in the question marks (???) and make the following declarative macro compile:
macro_rules! ??? {
??? => {
impl $something {
fn hello_world(&self) {
println!("Hello world")
}
}
};
}
<!-- page: 049 -->
rust
}
struct Example {}
hello_world!(Example);
fn main() {
let e = Example {};
e.hello_world(); // prints "Hello world"
}

2 In our first declarative macro example, we use expr in some of our matches. But that was not our only option. Try to replace that with literal, tt, ident, or ty. Which ones work? Which don’t? Do you understand why?

3 Allow trailing comments in the my_vec macro. You can do this by writing another matcher, but there’s a simple solution with even less repetition. If you need help, take a look at the vec macro from the standard library for inspiration.

4 Another thing I like for newtypes is convenient From implementations. Write a macro that generates them for our four newtypes. Alternatively, you can go for TryFrom since that is a more suitable choice when input validation is required.

5 Now that we have two macros, we could make our lives even easier by creating a third macro, generate_newtypes_methods, that calls our existing two macros behind the scene.

6 Expand our Account example in listings 2.12 and 2.13 with dollar and euro currencies. You can use a hardcoded exchange rate of 2 dollars to 1 euro. All existing commands will require a currency type.

7 In the upcoming procedural chapters, ask yourself: Could I have done this with a declarative macro? Why not? What would be hard to do?

  • Declarative macros are the first group of macros that Rust has to offer.
  • They consist of one or more pairs of matchers and transcribers.
  • The matcher has to match the content that was passed into the macro when it was invoked.
  • If there is a match, the code inside the transcriber will be written to where the macro was invoked.
  • Pieces of input can be captured in the matcher and used in the transcriber.
  • Macros can call themselves to avoid duplication and to allow for more complex scenarios.
  • To use macros outside the file where they were defined, you will need to export them.
  • Declarative macros have hygiene, which means local identifiers do not collide with external ones.
  • There are several use cases for declarative macros: avoiding duplication and boilerplate is a major one. Another is doing things that are hard—or impossible—to do otherwise, like default arguments, varargs, or DSLs.

  • If declarative macros fall short, you still have procedural macros waiting in the corridor to assist you with even more powerful weapons.