Going meta
local graph
Chapter 2 — Going meta
Section titled “Chapter 2 — Going meta”1 Going meta
Section titled “1 Going meta”This chapter covers
Section titled “This chapter covers”- What metaprogramming is
- Metaprogramming in Rust
- When to use macros
- What this book will teach you
Macros are some of the most important and powerful tools Rust has to offer. Because they have powers that Rust’s normal tooling (like functions) lacks, they can serve as “a light in dark places when all other lights go out.” That of itself is enough to make macros a core topic of this book. They have another neat quality though: they can be a pathway to other abilities. When you want to write a macro, you need knowledge of testing and debugging. You have to know how to set up a library because you cannot write a procedural macro without creating a library. Some knowledge about Rust internals, compilation, types, code organization, pattern matching, and parsing also comes in handy. Thus, teaching about macros allows me to talk about a variety of other programming topics. We will be learning about Rust macros and using them to explore other subjects.
CHAPTER 1 Going meta
But we are getting ahead of ourselves. Let’s take a step back and start from the beginning.
1.1 A day in the life of a Rust developer
Section titled “1.1 A day in the life of a Rust developer”You are a Rust developer, starting a new application that will accept JSON requests containing user data, like first and last names, and output useful information, say, the user’s full name. You start by simply adding a function that generates a full name based on a combination of first and last names, using format!. To turn JSON into a struct, you annotate Request with #[derive(Deserialize)]. And you always write tests, so you add a function for testing, annotating it with the #[test] attribute. To make sure everything matches your expectations, you use assert_eq!. And when something goes wrong, you either turn to a debugger or add some logging with dbg!.
Listing 1.1 The program you just wrote
Section titled “Listing 1.1 The program you just wrote”use serde::Deserialize;
#[derive(Deserialize)]struct Request { given_name: String, last_name: String,}
fn full_name(given: &str, last: &str) -> String { format!("{} {}", given, last)}
fn main() { let r = Request { given_name: "Sam".to_string(), last_name: "Hall".to_string() }; dbg!(full_name(&r.given_name, &r.last_name));}
#[cfg(test)]mod tests { use super::*;
#[test] fn test_deserialize() { let actual: Request = serde_json::from_str("{ \"given_name\": \"Test\", \"last_name\": \"McTest\" }") .expect("deserialize to work");
assert_eq!(actual.given_name, "Test".to_string()); assert_eq!(actual.last_name, "McTest".to_string()); }}A procedural macro
This bit of code contains several declarative macros.
And suddenly it dawns on you. Even when writing the simplest of Rust code, you just cannot stop using macros. You are surrounded by the fruits of Rust’s metaprogramming.
1.2 What is metaprogramming?
Section titled “1.2 What is metaprogramming?”In brief, metaprogramming is when you write code that will use other code as a data input. That means you can manipulate existing code, generate additional code, or add new capabilities to an application. To enable metaprogramming, Rust has macros, which are a specific form of metaprogramming. Rust’s macros run at compile time, expanding into “normal” code (structs, functions, and the like). When this process is complete, your code is ready for the next step, such as being linted, type-checked (cargo check), compiled into a linkable library, or transformed into a—runnable—binary by rustc (see figure 1.1).
#[derive(Deserialize)]struct Request { given_name: String, last_name: String,}Expands to
struct Request { given_name: String, last_name: String,}
#[allow(unused_imports, unused_attributes, unused_qualifications)]const _: () = { #[allow(unused_extern_crates, clippy::unused_attribute)] extern crate serde as _serde; #[automatically_derived] impl<'de> _serde::Deserialize<'de> for Request { fn deserialize<D>(_deserializer: D) -> _serde::__private::Result<Self, _D::Error> where D: _serde::Deserializer<'de> { struct _FieldVisitor; impl<'de> _serde::de::Visitor<'de> for _FieldVisitor { type Value = _Field;
fn expecting( &self, _formatter: &mut _serde::__private::Formatter, ) -> _serde::__private::fmt::Result { _serde::__private::Formatter::write_str(_formatter, "field identifier") } }
fn visit_u64<_E>(self, _value: u64) -> _serde::__private::Result<Self::Value, _E> where _E: _serde::de::Error, { match _value { 0u64 => _serde::__private::Ok(_Field::_field0), 1u64 => _serde::__private::Ok(_Field::_field1), _ => _serde::__private::Ok(_Field::_ignore), } }
fn visit_str<_E>( self, _value: &str, ) -> _serde::__private::Result<Self::Value, _E> where _E: _serde::de::Error { match _value { "given_name" => _serde::__private::Ok(_Field::_field0), "last_name" => _serde::__private::Ok(_Field::_field1), _ => _serde::__private::Ok(_Field::_ignore), } }
fn visit_bytes<_E>( self, _value: &[u8], ) -> _serde::__private::Result<Self::Value, _E> where _E: _serde::de::Error { match _value { b"given_name" => _serde::__private::Ok(_Field::_field0), b"last_name" => _serde::__private::Ok(_Field::_field1), _ => _serde::__private::Ok(_Field::_ignore), } } } }};Figure 1.1 I contain multitudes! How our simple example hides many more lines of code, generated by macros.
CHAPTER 1 Going meta
Section titled “CHAPTER 1 Going meta”Rust is not the only language to offer metaprogramming capabilities. C and Clojure also have powerful macros, with C also offering templates. Java has reflection to manipulate classes, which famously allowed the Spring framework to develop some of its most impressive capabilities, including using annotations for dependency injection. JavaScript has eval, a function that takes in a string as data that will be evaluated as an instruction at run time. In Python, you get eval as well as better options like metaclasses and the very popular decorators, which can manipulate both classes and functions.
1.3 Metaprogramming in Rust
Section titled “1.3 Metaprogramming in Rust”At some point in their career, most programmers will come into contact with a form of metaprogramming—often to do things that would be hard to do with normal coding tools. But unless you write a lot of Common Lisp or Clojure, where macros are very popular, on average such experiences are bound to be limited. So why on earth should we care about metaprogramming in Rust? Because Rust is different. This is something you have heard too many times before, but hear me out!
The first difference from many other languages is that, similar to Clojure, it is hard to imagine Rust code without macros. Macros are used extensively in both the standard library (think of the ubiquitous dbg! and println!) and custom crates. At the time of writing (mid-2024), among the top 10 downloaded packages on crates.io, three are for creating procedural macros (syn, quote, and proc-macro2). One of the others is serde, where procedural macros ease your serialization work. Or search for the keyword “derive,” which often signifies that the package has a macro. You will get back over 10,661 results, about 7% of all packages! In brief, in Rust macros are not just some syntactic sugar but core functionality.
Why are so many people writing macros? Well, in Rust they offer a very powerful form of metaprogramming that is also relatively easy and safe to use. Part of that safety comes from being a compiled language. Compare that with Clojure, a difficult language (in my opinion) that makes macros easy to use but without the aid of any compile-time checking. The same can be said for JavaScript and Python. And for JavaScript, safety/security is an important reason for the “Never use direct eval()” advice in the Mozilla documentation (http://mng.bz/4JMv).
Meanwhile, all of Rust’s macros are evaluated at compile time and have to withstand the thorough checks that the language employs to verify code. This means that what you generate is as safe as normal code, and you still get to enjoy the compiler telling you exactly why you are wrong! Especially for declarative macros, hygiene is part of that safety, avoiding clashes with names used elsewhere in your code. This means you get more safety than you would get with C macros, as these are unhygienic, allowing macros to unintentionally reference or capture symbols from other code. C macros are also less safe since they are expanded when type information is not available. Templates are safer, though the errors you get back can be cryptic.
Another advantage of doing everything at compile time is that the performance effect on your final binary is, in most cases, negligible. You are adding a bit of code.
1.3 Metaprogramming in Rust
Section titled “1.3 Metaprogramming in Rust”Nothing to lose sleep over. (Meanwhile, there is an obvious effect on compile times, but those are annoyingly long with or without macros.) Compare that to Java, where the aforementioned Spring framework does a lot of reflection at startup for dependency injection. This means performance takes a hit, and metaprogramming becomes—I’m sounding like a broken record—less safe because you only find out if everything works at run time, perhaps only when you go to production.
Finally, for me, metaprogramming can sometimes be too “magical,” with a Spring Bean in one part of your application altering behavior in an entirely different part. And while Rust macros may seem magical, there is less of Spring’s, to paraphrase Einstein, “spooky action at run time.” That is because macros in Rust are (a) more localized and (b) run at compile time, allowing for easier inspection and better verification.
1.3.1 Macro galore
Section titled “1.3.1 Macro galore”To make the localized argument more concrete, let me introduce one of the main protagonists of this book, the procedural macro. Procedural macros take a piece of your code as a stream of tokens and return another stream of tokens, which will be processed together with the rest of your code by the compiler. This low-level manipulation stands in contrast to the approach of the better-known declarative macros (which feature in the next chapter). Those allow you to generate code using a higher (“declarative”) level of abstraction. This makes declarative macros a safe and easy option to get started with—even if they lack the raw power of their procedural brothers.
NOTE Streams of tokens, expanding macros: as you may have guessed, we will talk about all of this in more depth in the upcoming chapters.
There are three kinds of procedural macros (see figure 1.2). First are derive macros. You use them by adding a #[derive] attribute to a struct, enum, or union. When that is done, the code of that struct/enum/union will be passed as an input to your macro. This input is not modified. Instead, new code is generated as an output. These macros are for extending the capabilities of types by adding functions or implementing traits. So whenever you see #[derive] decorating a struct, you know it is adding some kind of additional functionality to that specific struct. No functionality is added to some random part of your application, and neither is the struct modified in any way. Despite (or maybe because of) these limits, these are probably the most widely used procedural macros.
Attribute macros, the second type, can be placed on structs, enums, and unions as well as trait definitions and functions. They get their name from the fact that they define a new, custom attribute (one well-known example is #[tokio::main]), whereas derive macros are required to use #[derive]. They are more powerful and thus more dangerous because they transform the item they are decorating: the output they produce replaces the input. Whereas derive macros are only additive, with an attribute macro, the definition of your type might change. But at least the annotation is telling you what struct it is transforming and is not changing other code and other files.
CHAPTER 1 Going meta
Section titled “CHAPTER 1 Going meta”mermaid
graph TD
A[Macros in Rust] —> B[Declarative macros]
A —> C[Procedural macros
work with token streams.]
C —> D[Derive macros
#[derive] attribute
can add code.]
C —> E[Attribute macros
#[custom-attribute]
can add or manipulate code.]
C —> F[Function-like macros
macro_name!
can add or manipulate code “anywhere.”]
Figure 1.2 The types of macros in Rust
The third kind of procedural macro is called *function-like*. This one is invoked with the `!` operator and works with any input you pass in. That input will disappear, replaced by what you generate as output, quite similar to attribute macros. But unlike the others, a function-like macro is not limited to annotating things like structs or functions. Instead, you can call it from almost anywhere within your code. As we shall see, this can produce some powerful magic. But—you probably already know where I am going with this—the input of that magic is whatever you decided to pass along. Rust, once again, seems to have found a way to take a known programming concept and make it safe(r) to work with.
## 1.3.2 Appropriate use cases
“Okay, so since macros are so great and safe, I should use them everywhere for everything.” Wow, slow down there, straw man! Obviously, you should start any application without turning to *custom macros*. *Zero to Production in Rust* (https://www.zero2prod.com/index.html) built an entire deployable newsletter application without ever writing a macro. (The author uses a lot of those that are provided by the language and its libraries, though.) Structs, enums, and functions are just easier to understand and use, plain and simple. And while macros won’t have a lot of effect on run-time performance, they still add to compile times and binary size. And the former is already the biggest pain point reported by Rust developers! For small macros, like the examples in this book, that compile-time cost is negligible. But for many “production-grade” macros, the tradeoff will be real—but hopefully worth it.
When and why would you use macros? In larger applications, they might be tempting to use for reducing boilerplate. But that might make the code harder to understand
```mermaidflowchart TD M[Macros in Rust] --> D[Declarative macros] M --> P[Procedural macros<br/>work with token streams] P --> DM[Derive macros<br/>#derive attribute<br/>can add code] P --> AM[Attribute macros<br/>#custom-attribute<br/>can add or manipulate code] P --> FM[Function-like macros<br/>macro_name!<br/>can add or manipulate code anywhere][!visual-conversion] Macro taxonomy in Rust Converted from a print taxonomy diagram (PDF page 016): Rust macros divide into declarative macros and procedural macros; procedural macros subdivide into derive, attribute, and function-like macros, with each kind’s annotation and capability noted.
1.3 Metaprogramming in Rust
Section titled “1.3 Metaprogramming in Rust”for people unfamiliar with the project because, compared to a function, the signature of a macro gives no insight into what is happening. In addition, your readers are bound to have more experience mentally parsing ordinary Rust code, so even if they have to “dive into” a function definition, it will take them less time to get the gist of it. And generic functions are a great tool for avoiding duplication, so they offer a valid alternative. Similarly, generic implementation blocks—or blanket implementations—are very powerful. Just look at the crazy piece of code in listing 1.2, an example of the “extension trait” pattern, combining a custom trait with a blanket implementation. We implement our trait for everything that implements Copy. Numbers, characters, Booleans, etc., suddenly have a new function available. We should probably be afraid of using blanket implementations as well as macros.
Listing 1.2 The powers and dangers of generics
Section titled “Listing 1.2 The powers and dangers of generics”rust trait Hello { fn hello(&self); }
impl<T: Copy> Hello for T { fn hello(&self) { println!(“Hello world”); } }
fn main() { 2.hello(); true.hello(); ‘c’.hello(); }
So, the first takeaway: avoiding boilerplate, as well as duplication, is a good reason to use macros, but only if it doesn’t make the code hard to understand. And if, in order to use the macro, developers often look at the implementation, that’s bad. Consider the macros offered by the standard library: `Debug`, `Clone`, `Default`, etc. They all do the grunt work for one well-defined, repetitive task (e.g., `Clone` does only one thing: it makes your object cloneable). As a bonus, developers reading your code will immediately grasp your intent when they see the `#[derive(Clone)]` attribute. And they probably won’t care about the actual details of how this is done. This is perfect, as it avoids the additional mental strain involved in diving into the code. This approach to avoiding duplication is far better than the automatic code generation offered by some languages. Yes, code generation might help with writing code by adding useful boilerplate to your application. But it adds noise and makes it *harder to read* the code. And writing is often not the difficult part of programming. Making things understandable for those who come after you is.
**NOTE** I was reading about the `Decode` trait that `sqlx` offers and instinctively thought: “That trait probably has a derive macro, seems like a perfect use case.” Lo and behold, there was indeed a derive macro available.
<!-- page: 018 -->
# CHAPTER 1 Going meta
So look for repetitive tasks that are very easy to describe from a bird’s-eye view (“clone this, copy that, print it”) and whose output will be predictable (debug prints *every* property of your struct). These are often tasks with a universal appeal, useful in many applications and easy to understand. For example, making sure that something can be compared to others of the same kind (`PartialEq`) is a common task that most developers have been confronted with. Functions can help fight duplication as well, but they can’t manipulate structs or add helper methods. (Blanket implementations can, but they are limited to working through traits.) Outside the standard library, you can find a lot of other examples that help you avoid duplication and boilerplate while being easy to describe and producing predictable results. Serde allows for easy serialization/deserialization of structs. Tokio manages the boilerplate involved in creating an async main for you.
Another reason to turn to macros, closely related to the previous category, would be ease of use. You want to take away the uninteresting technical details of a task that developers do not need to know about when they are writing an application. You could argue that Serde and Tokio belong to this category since they hide the details of serialization and asynchronous behavior. Only rarely will you have to look under the hood of these macros; most of the time they will “just work.” How won’t matter—once again, a win for both the reader and the writer. Also worth mentioning is Clap, which hides the details—and boilerplate—of parsing command-line arguments, and Rocket, which uses macros to hide REST application complexities.
One final use case is simulating capabilities that are not available in Rust. We will see an example of how declarative macros add varargs to the language in the next chapter. Outside the core language, Tokio is again worth mentioning as it enables you to have asynchronous main functions. But there are lots of other examples in this category. Static assertions also make guarantees about your code without ever running it, checking, for instance, whether a struct implements given traits. SQLx lets you write SQL strings, checks whether they are valid at compile time, and transforms the results into structs. Yew and Leptos allow you to write type-checked HTML within Rust. Shuttle sets up cloud infrastructure for you based on annotations. Obviously, a lot of these offer validation at compile time. After all, that is when your macro will run. But it is also the most interesting time to check and verify before you start doing more expensive, time-consuming things to verify your code, like unit testing, integration testing, end-to-end testing, or even testing in production (see figure 1.3). All of these have their place in modern application building. However, when a simple cargo check can point out errors before a single test has run, you are saving yourself a lot of time and effort. In addition, everything you do at compile time is a performance win for your users.
Besides verification, macros from this category add *Domain-Specific Language (DSL)* capabilities that allow you to write code in an easier, more elegant way than would be possible with native Rust. Using macros for DSLs is also interesting for application developers who want to enable easier expression of ideas in a way that is closer to the
<!-- page: 019 -->
# 1.3 Metaprogramming in Rust
<div style="text-align: center;"> ```mermaidflowchart LR C[Compilation] --> UT[Unit testing] --> IT[Integration testing] --> E2E[End-to-end testing] --> TP[Testing in production] TP -.->|More certainty| E2E C -.->|Cheaper, faster, easier| UT[!visual-conversion] Spectrum of testing Converted from a print spectrum diagram (PDF page 019): Compilation → Unit testing → Integration testing → End-to-end testing → Testing in production, with certainty rising to the right and cost/speed/ease rising to the left.
Figure 1.3 Spectrum of testing
language of the business experts. When done well, this type also belongs to the ease-of-use category.
DEFINITION What is a Domain-Specific Language (DSL)? The programming languages with which we programmers are most familiar are general-purpose languages, applicable to practically any domain. You can use JavaScript to write code regardless of the sector you are working in. But DSLs are written with a specific domain in mind. Think of SQL, which is designed specifically for interacting with databases. That means the creator can focus on making business concepts easier to express. If you were writing a language for use by banks, you might make it very easy for developers (or even end users) to write code that transfers money between accounts. A DSL can also allow you to optimize. If you were writing one for working with DNA, you could assume you would only need four letters (A, C, G, T) to represent your data, which could allow for better compression (and since A always pairs with T and G with C, maybe you would only need two options). DSLs come in two varieties: some are created entirely from the start, and others are created by using a general-purpose language like Rust as a base. In this book, we are interested in the latter.
To summarize, macros are a great fit when you are confronted with a task that has a predictable output, whose details are irrelevant to (most) developers, and that needs to be performed frequently. Additionally, macros are the best or only choice for extending the language and writing elegant or complex DSLs. In other cases, you probably want to turn to functions, structs, and enums. For example, avoiding the duplication of filtering and mapping incoming data in two or three places calls for a function, not a new macro.
NOTE If you do find a good use case for a procedural or declarative macro, do a (Google) search before you start coding. Someone may have beaten you to the punch.
CHAPTER 1 Going meta
1.3.3 Unfit for purpose: When not to use macros
Section titled “1.3.3 Unfit for purpose: When not to use macros”When it comes to inappropriate use cases for macros, two categories come to mind. The first was mentioned already: things that you can easily accomplish with functions. Starting with functions and moving to macros when things become too complicated or require too much boilerplate is often a good idea. Don’t try to overengineer things. The other category where I have some doubts is business logic. Your business code is specific to your use case and application. So almost all publicly available macros are disqualified from the get-go. Now you might write a custom macro for use inside your company. But in a microservice world, sharing business code between services and teams is often a bad idea. Your idea of a “user,” “aircraft,” “basket,” or “factory” within a microservice will differ from that in the next microservice. It’s a road paved with good intentions that leads to confusion and bugs or customization of an already custom macro. There are exceptions to this category, though. First, in larger codebases, macros could help you avoid some rare business boilerplate. Second, we already noted how DSLs can improve your quality of life as an application engineer—especially in a complex domain. And macros are a great tool for writing DSLs.
One final—but minor—point to keep in mind before we move to the next section: integrated development environment (IDE) support for macros will always be less advanced than that for “normal” programming. This is pretty much an unavoidable downside. With more powerful tools come more options. That makes it harder for your computer to guess what you can and cannot legally do. Imagine a programming language whose only valid statement is . An IDE would be incredibly helpful in pointing out mistakes (“You typed b - @? !, did you mean ?”) and giving code completions. Now imagine a language where everything is allowed. Does struvt Example { } have a typo? Maybe, maybe not. Who knows? This is also why it is harder for an IDE to help you when you work with dynamic languages; that is, types are helpful for the machine too! A type system limits your options, and that can limit the power of your language. But it can offer things like more safety, performance, and ease of use in return.
In the case of procedural macros, one additional complexity is that your IDE has to expand the code in the same way that Rust would. Only that way can it tell you whether the fields or methods you think will be added by a macro are actually there. IntelliJ, RustRover, and Visual Studio Code (to a lesser extent) do this, as we will briefly discuss in a later chapter, but even so, their advice can still run into trouble when expansion fails, at which point they should report back to the user with details on what went wrong. But that is easier said than done. Where, for example, should they point to when it comes to that error?
1.4 Approach of this book
Section titled “1.4 Approach of this book”The approach of this book can be summarized as example driven and step by step. Most chapters will have one application as a central theme to explore a macro topic as well as other relevant themes from Rust. Starting with a simple “Hello, World,” we will
add layers of knowledge, piece by piece: how to parse, how to test, how to handle errors. We will also point out common errors that you might run into and give you some debugging hints. Finally, the chapters will briefly point out how popular crates (including those mentioned in this chapter) use the explained techniques or accomplish specific feats. This will give you insights into how you can apply what you have learned. Finally, while the next chapter will give a pretty thorough overview of declarative macros, the rest of the book will focus on the procedural ones, mainly because the latter are harder to use, and there is already a lot of useful content on the former.
Exercise
Section titled “Exercise”Think of a recent application that you worked on. Can you think of places where duplication and boilerplate were unavoidable? Did you have the feeling you were lacking a tool to make the application easier to use? Was there something that could not be done within the constraints of the language? Hopefully, by the end of this book, you will think of macros as one possible tool for fixing such problems.
Summary
Section titled “Summary”- Metaprogramming allows you to write code that generates more code.
- Many languages offer some way to do metaprogramming, but these tools are often difficult to use and not well integrated into the language, which can lead to hard-to-understand or buggy code.
- Rust’s macros are powerful and avoid many of these shortcomings, with a focus on safety and without real effect on run-time performance.
- Macros in Rust are “expanded” into code checked by the compiler.
- Rust has high-level declarative macros and three kinds of procedural macros (derive macros, attribute macros, and function-like macros) that process code as a stream of tokens.
- Metaprogramming should not be your first choice when solving problems, but it can help you avoid boilerplate and duplication, make your applications easier to use, or do things that are difficult to do with “normal” Rust.
- This book will explore macros, all the while using them to discuss other advanced subjects through an example-driven approach.